[jbpm-commits] JBoss JBPM SVN: r6257 - in jbpm3/branches/jbpm-3.2-soa/modules: core/src/main/java/org/jbpm/bytes and 48 other directories.
do-not-reply at jboss.org
do-not-reply at jboss.org
Thu Apr 15 09:46:37 EDT 2010
Author: alex.guizar at jboss.com
Date: 2010-04-15 09:46:26 -0400 (Thu, 15 Apr 2010)
New Revision: 6257
Added:
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/NodeIterator.java
Modified:
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/AbstractJbpmTestCase.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/JbpmConfiguration.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/bytes/ByteArray.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/calendar/BusinessCalendar.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractCancelCommand.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractGetObjectBaseCommand.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractProcessInstanceBaseCommand.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractTokenBaseCommand.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/BatchSignalCommand.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/ChangeProcessInstanceVersionCommand.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/DeployProcessCommand.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/ExecuteJobsCommand.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/SignalCommand.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/impl/CommandServiceImpl.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/JbpmContextInfo.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/JbpmTypeObjectInfo.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/ListInfo.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/MapInfo.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/ObjectFactoryImpl.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/ObjectFactoryParser.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/def/Access.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/def/VariableAccess.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/ContextInstance.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/VariableContainer.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/VariableInstance.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/matcher/HibernateLongIdMatcher.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/matcher/HibernateStringIdMatcher.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/variableinstance/JcrNodeInstance.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/variableinstance/NullInstance.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/log/VariableCreateLog.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/log/VariableLog.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/AbstractDbTestCase.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/JbpmSessionFactory.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/LoggingSession.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/compatibility/JbpmSchemaUpdate.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/hibernate/Converters.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/hibernate/HibernateHelper.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/action/ActionTypes.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/action/Script.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/def/EventCallback.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/def/GraphElement.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/def/Transition.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/exe/Token.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/Decision.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/Join.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/NodeTypes.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/ProcessState.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/TaskNode.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jcr/impl/AbstractJcrServiceFactory.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jcr/impl/JcrServiceImpl.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/job/Timer.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/job/executor/JobExecutor.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/job/executor/JobExecutorThread.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/el/impl/BeanMethod.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/el/impl/JbpmExpressionEvaluator.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/el/impl/JbpmVariableResolver.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/xml/JpdlParser.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/logging/exe/LoggingInstance.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/logging/log/CompositeLog.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/logging/log/ProcessLog.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/mail/Mail.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/msg/db/DbMessageService.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/db/DbPersistenceService.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/db/StaleObjectLogConfigurer.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/jta/JtaDbPersistenceService.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/scheduler/db/DbSchedulerService.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/scheduler/def/CreateTimerAction.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/svc/save/CascadeSaveOperation.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/svc/save/HibernateSaveOperation.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/svc/save/SaveLogsOperation.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/taskmgmt/def/TaskController.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/taskmgmt/exe/TaskInstance.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/taskmgmt/exe/TaskMgmtInstance.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/ClassLoaderUtil.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/JndiUtil.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/XmlUtil.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/SerializabilityTest.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/graph/node/CustomSubProcessResolverTest.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/jbpm983/JBPM983Test.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/jpdl/el/DecisionExpressionTest.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/jpdl/par/ProcessClassLoaderTest.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/logging/log/ProcessLogDbTest.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/persistence/db/PersistenceConfigurationDbTest.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/persistence/db/PersistenceServiceDbTest.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/scheduler/exe/SchedulerTest.java
jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/resources/log4j.xml
jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/CommandListenerBean.java
jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/CommandServiceBean.java
jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/ExecuteJobCommand.java
jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/TimerEntityBean.java
jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/EjbSchedulerService.java
jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/EntitySchedulerService.java
jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/ExecuteTimerCommand.java
jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/TimerServiceBean.java
jbpm3/branches/jbpm-3.2-soa/modules/examples/src/test/java/org/jbpm/examples/assignment/RulesAssignmentHandler.java
jbpm3/branches/jbpm-3.2-soa/modules/examples/src/test/java/org/jbpm/examples/rulesaction/RulesActionHandler.java
jbpm3/branches/jbpm-3.2-soa/modules/identity/src/main/java/org/jbpm/identity/assignment/ExpressionAssignmentHandler.java
jbpm3/branches/jbpm-3.2-soa/modules/identity/src/main/java/org/jbpm/identity/hibernate/IdentitySchema.java
jbpm3/branches/jbpm-3.2-soa/modules/identity/src/main/java/org/jbpm/identity/hibernate/IdentitySessionFactory.java
Log:
JBPM-2091: guard log debug statements
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/AbstractJbpmTestCase.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/AbstractJbpmTestCase.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/AbstractJbpmTestCase.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -33,15 +33,11 @@
protected final Log log = LogFactory.getLog(getClass());
protected void setUp() throws Exception {
- log.debug("### START "
- + getName()
- + " ####################################################");
+ log.info("### START " + getName() + " ####################");
}
protected void tearDown() throws Exception {
- log.debug("### END "
- + getName()
- + " ######################################################");
+ log.info("### END " + getName() + " ####################");
}
protected String getShortName() {
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/JbpmConfiguration.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/JbpmConfiguration.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/JbpmConfiguration.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -287,14 +287,11 @@
if (instance == null) {
// configuration does not exist or was evicted, construct it
if (defaultObjectFactory != null) {
- if (log.isDebugEnabled()) {
- log.debug("creating configuration from default object factory: "
- + defaultObjectFactory);
- }
+ log.info("configuring from default object factory");
instance = new JbpmConfiguration(defaultObjectFactory);
}
else {
- log.info("using configuration resource: " + resource);
+ log.info("configuring from resource: " + resource);
InputStream jbpmCfgXmlStream = ClassLoaderUtil.getStream(resource, false);
/*
* if a custom resource is specified, but not found in the classpath, log a warning;
@@ -302,7 +299,7 @@
* their resource cannot be found
*/
if (jbpmCfgXmlStream == null && !"jbpm.cfg.xml".equals(resource)) {
- log.warn("configuration resource '" + resource + "' was not found");
+ log.warn("configuration resource not found: " + resource);
}
ObjectFactory objectFactory = parseObjectFactory(jbpmCfgXmlStream);
instance = createJbpmConfiguration(objectFactory, resource);
@@ -319,25 +316,19 @@
}
protected static ObjectFactory parseObjectFactory(InputStream inputStream) {
- log.debug("loading defaults in jbpm configuration");
ObjectFactoryParser objectFactoryParser = new ObjectFactoryParser();
ObjectFactoryImpl objectFactoryImpl = new ObjectFactoryImpl();
objectFactoryParser.parseElementsFromResource("org/jbpm/default.jbpm.cfg.xml", objectFactoryImpl);
if (inputStream != null) {
- log.debug("loading specific configuration...");
objectFactoryParser.parseElementsStream(inputStream, objectFactoryImpl);
}
-
return objectFactoryImpl;
}
public static JbpmConfiguration parseXmlString(String xml) {
- log.debug("creating jbpm configuration from xml string");
- InputStream inputStream = null;
- if (xml != null) {
- inputStream = new ByteArrayInputStream(xml.getBytes());
- }
+ log.info("configuring from xml string");
+ InputStream inputStream = xml != null ? new ByteArrayInputStream(xml.getBytes()) : null;
ObjectFactory objectFactory = parseObjectFactory(inputStream);
return createJbpmConfiguration(objectFactory);
}
@@ -371,15 +362,13 @@
}
public static JbpmConfiguration parseInputStream(InputStream inputStream) {
- log.debug("creating jbpm configuration from input stream");
+ log.info("configuring from input stream");
ObjectFactory objectFactory = parseObjectFactory(inputStream);
return createJbpmConfiguration(objectFactory);
}
public static JbpmConfiguration parseResource(String resource) {
- if (log.isDebugEnabled()) {
- log.debug("creating jbpm configuration from resource: " + resource);
- }
+ log.info("configuring from resource: " + resource);
InputStream inputStream = resource != null ? ClassLoaderUtil.getStream(resource, false)
: null;
ObjectFactory objectFactory = parseObjectFactory(inputStream);
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/bytes/ByteArray.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/bytes/ByteArray.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/bytes/ByteArray.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -26,33 +26,26 @@
import java.util.Arrays;
import java.util.List;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
import org.jbpm.util.ArrayUtil;
-import org.jbpm.util.StringUtil;
/**
- * is a persistable array of bytes. While there is no generic way of storing
- * blobs that is supported by many databases, all databases are able to handle
- * small chunks of bytes properly. It is the responsibility of this class to
- * chop the large byte array into small chunks of 1K (and combine the chunks
- * again in the reverse way). Hibernate will persist the list of byte-chunks in
- * the database.
+ * is a persistable array of bytes. While there is no generic way of storing blobs that is
+ * supported by many databases, all databases are able to handle small chunks of bytes properly.
+ * It is the responsibility of this class to chop the large byte array into small chunks of 1K
+ * (and combine the chunks again in the reverse way). Hibernate will persist the list of
+ * byte-chunks in the database.
*
- * ByteArray is used in process variableInstances and in the file module (that
- * stores the non-parsed process archive files).
+ * ByteArray is used in process variableInstances and in the file module (that stores the
+ * non-parsed process archive files).
*/
public class ByteArray implements Serializable {
private static final long serialVersionUID = 1L;
- long id;
+ private long id;
protected String name;
protected List byteBlocks;
- private static final Log log = LogFactory.getLog(ByteArray.class);
-
public ByteArray() {
}
@@ -65,13 +58,6 @@
this.name = name;
}
- void logBlocks(String msg) {
- for (int blockIndex = 0; blockIndex < byteBlocks.size(); blockIndex++) {
- byte[] block = (byte[]) byteBlocks.get(blockIndex);
- log.debug(msg + "[" + block.length + "] " + StringUtil.toHexString(block));
- }
- }
-
public ByteArray(ByteArray other) {
List otherByteBlocks = other.getByteBlocks();
if (otherByteBlocks != null) {
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/calendar/BusinessCalendar.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/calendar/BusinessCalendar.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/calendar/BusinessCalendar.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -37,15 +37,15 @@
* a calendar that knows about business hours.
*/
public class BusinessCalendar implements Serializable {
-
+
private static final long serialVersionUID = 1L;
- static Properties businessCalendarProperties = null;
-
- private Day[] weekDays = null;
- private List holidays = null;
+ private static Properties businessCalendarProperties;
+ private Day[] weekDays;
+ private List holidays;
+
public static synchronized Properties getBusinessCalendarProperties() {
- if (businessCalendarProperties==null) {
+ if (businessCalendarProperties == null) {
String resource = JbpmConfiguration.Configs.getString("resource.business.calendar");
businessCalendarProperties = ClassLoaderUtil.getProperties(resource);
}
@@ -53,32 +53,34 @@
}
public BusinessCalendar() {
- // don't load the properties during creation time!
- // see http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4158259
+ // do not load properties during creation time!
+ // see http://community.jboss.org/message/404365
// this(getBusinessCalendarProperties());
}
-
+
public BusinessCalendar(Properties calendarProperties) {
try {
weekDays = Day.parseWeekDays(calendarProperties, this);
holidays = Holiday.parseHolidays(calendarProperties, this);
-
- } catch (Exception e) {
- throw new JbpmException("couldn't create business calendar", e);
}
+ catch (Exception e) {
+ throw new JbpmException("could not create business calendar", e);
+ }
}
-
+
public Day[] getWeekDays() {
- if (weekDays==null)
+ if (weekDays == null) {
// lazy load properties if not set during creation
weekDays = Day.parseWeekDays(getBusinessCalendarProperties(), this);
+ }
return weekDays;
}
public List getHolidays() {
- if (holidays==null)
+ if (holidays == null) {
// lazy load properties if not set during creation
holidays = Holiday.parseHolidays(getBusinessCalendarProperties(), this);
+ }
return holidays;
}
@@ -86,15 +88,16 @@
Date end = null;
if (duration.isBusinessTime()) {
DayPart dayPart = findDayPart(date);
- boolean isInbusinessHours = (dayPart!=null);
- if (! isInbusinessHours) {
+ boolean isInbusinessHours = (dayPart != null);
+ if (!isInbusinessHours) {
Object[] result = new Object[2];
findDay(date).findNextDayPartStart(0, date, result);
date = (Date) result[0];
dayPart = (DayPart) result[1];
}
end = dayPart.add(date, duration);
- } else {
+ }
+ else {
end = duration.addTo(date);
}
return end;
@@ -109,7 +112,7 @@
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
date = calendar.getTime();
- while(isHoliday(date)) {
+ while (isHoliday(date)) {
calendar.setTime(date);
calendar.add(Calendar.DATE, 1);
date = calendar.getTime();
@@ -124,49 +127,43 @@
}
public boolean isHoliday(Date date) {
- Iterator iter = getHolidays().iterator();
- while (iter.hasNext()) {
+ for (Iterator iter = getHolidays().iterator(); iter.hasNext();) {
Holiday holiday = (Holiday) iter.next();
- if (holiday.includes(date)) {
- return true;
- }
+ if (holiday.includes(date)) return true;
}
return false;
}
- DayPart findDayPart(Date date) {
+ private DayPart findDayPart(Date date) {
DayPart dayPart = null;
- if (! isHoliday(date)) {
+ if (!isHoliday(date)) {
Day day = findDay(date);
- for (int i=0; ((i < day.dayParts.length)
- && (dayPart==null)); i++) {
+ for (int i = 0; ((i < day.dayParts.length) && (dayPart == null)); i++) {
DayPart candidate = day.dayParts[i];
- if (candidate.includes(date)) {
- dayPart = candidate;
- }
+ if (candidate.includes(date)) dayPart = candidate;
}
}
return dayPart;
}
- public DayPart findNextDayPart(Date date) {
- DayPart nextDayPart = null;
- while(nextDayPart==null) {
- nextDayPart = findDayPart(date);
- if (nextDayPart==null) {
- date = findStartOfNextDay(date);
- Object result[] = new Object[2];
- Day day = findDay(date);
- day.findNextDayPartStart(0, date, result);
- nextDayPart = (DayPart) result[1];
- }
- }
- return nextDayPart;
- }
+ public DayPart findNextDayPart(Date date) {
+ DayPart nextDayPart = null;
+ while (nextDayPart == null) {
+ nextDayPart = findDayPart(date);
+ if (nextDayPart == null) {
+ date = findStartOfNextDay(date);
+ Object result[] = new Object[2];
+ Day day = findDay(date);
+ day.findNextDayPartStart(0, date, result);
+ nextDayPart = (DayPart) result[1];
+ }
+ }
+ return nextDayPart;
+ }
- public boolean isInBusinessHours(Date date) {
- return (findDayPart(date)!=null);
- }
+ public boolean isInBusinessHours(Date date) {
+ return (findDayPart(date) != null);
+ }
public static Calendar getCalendar() {
return new GregorianCalendar();
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractCancelCommand.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractCancelCommand.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractCancelCommand.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -15,21 +15,25 @@
private static final long serialVersionUID = 1L;
/**
- * Name of a standardized process variable written during cancellation in
- * order to indicate that this process has been 'canceled' and not just ended.
- * The variable value is the cancellation timestamp.
+ * Name of a standardized process variable written during cancellation in order to indicate
+ * that this process has been 'canceled' and not just ended. The variable value is the
+ * cancellation timestamp.
*/
public static String CANCELLATION_INDICATOR_VARIABLE_NAME = "canceled";
- protected transient JbpmContext jbpmContext = null;
+ protected transient JbpmContext jbpmContext;
protected static final Log log = LogFactory.getLog(AbstractCancelCommand.class);
protected void cancelTokens(Collection tokens) {
if (tokens != null && !tokens.isEmpty()) {
- log.debug("canceling " + tokens.size() + " tokens");
+ boolean debug = log.isDebugEnabled();
+ if (debug) log.debug("cancelling " + tokens.size() + " tokens");
+
for (Iterator itr = tokens.iterator(); itr.hasNext();) {
- cancelToken((Token) itr.next());
+ Token token = (Token) itr.next();
+ if (debug) log.debug("cancelling " + token);
+ cancelToken(token);
}
}
}
@@ -43,10 +47,10 @@
if (!token.hasEnded()) {
// end token but do not propagate to parent
- // to prevent inadvertent termination
+ // to prevent inadvertent termination
token.end(false);
}
- log.debug("canceled " + token);
+ if (log.isDebugEnabled()) log.debug("cancelled " + token);
}
protected List getTasksForToken(Token token) {
@@ -58,11 +62,12 @@
protected void cancelTasks(List tasks) {
if (tasks != null && !tasks.isEmpty()) {
- log.debug("cancelling " + tasks.size() + " tasks");
+ boolean debug = log.isDebugEnabled();
+ if (debug) log.debug("cancelling " + tasks.size() + " tasks");
for (Iterator it = tasks.iterator(); it.hasNext();) {
TaskInstance ti = (TaskInstance) it.next();
- log.debug("cancelling " + ti);
+ if (debug) log.debug("cancelling " + ti);
// manually turn off signaling for task instance,
// otherwise it may signal its associated token
ti.setSignalling(false);
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractGetObjectBaseCommand.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractGetObjectBaseCommand.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractGetObjectBaseCommand.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -4,6 +4,8 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.hibernate.Hibernate;
+
import org.jbpm.JbpmContext;
import org.jbpm.graph.def.Node;
import org.jbpm.graph.def.ProcessDefinition;
@@ -15,13 +17,12 @@
/**
* abstract base class for "get" commands which also implements default pre-fetching.
*
- * Note: pre-fetching logs is not possible here, so you have to load Logs explicitly
- * with GetProcessInstanceLogCommand
+ * Note: pre-fetching logs is not possible here, so you have to load Logs explicitly with
+ * GetProcessInstanceLogCommand
*
* @author Bernd Ruecker (bernd.ruecker at camunda.com)
*/
-public abstract class AbstractGetObjectBaseCommand extends AbstractBaseCommand
-{
+public abstract class AbstractGetObjectBaseCommand extends AbstractBaseCommand {
static final Log log = LogFactory.getLog(AbstractGetObjectBaseCommand.class);
@@ -30,7 +31,7 @@
/**
* if true, all process variables in the context (process instance / task) are prefetched too
*/
- private boolean includeAllVariables = false;
+ private boolean includeAllVariables;
/**
* specify the names of the variables to prefetch
@@ -39,190 +40,156 @@
private transient JbpmContext jbpmContext;
- public AbstractGetObjectBaseCommand()
- {
+ public AbstractGetObjectBaseCommand() {
}
- public AbstractGetObjectBaseCommand(boolean includeAllVariables, boolean includeLogs)
- {
+ public AbstractGetObjectBaseCommand(boolean includeAllVariables, boolean includeLogs) {
this.includeAllVariables = includeAllVariables;
}
- public AbstractGetObjectBaseCommand(String[] variablesToInclude)
- {
+ public AbstractGetObjectBaseCommand(String[] variablesToInclude) {
this.variablesToInclude = variablesToInclude;
}
- public void retrieveTaskInstanceDetails(TaskInstance ti)
- {
- try
- {
- ti.getToken().getProcessInstance().getProcessDefinition().getName();
+ public void retrieveTaskInstanceDetails(TaskInstance ti) {
+ try {
+ Token token = ti.getToken();
+ // process instance
+ ProcessInstance processInstance = token.getProcessInstance();
+ // in TaskInstances created with jbpm 3.1, this association was not present!
+ ti.setProcessInstance(processInstance);
+ // process definition
+ Hibernate.initialize(processInstance.getProcessDefinition());
+ // node
+ Hibernate.initialize(token.getNode());
+ // definition
+ Hibernate.initialize(ti.getTask());
+ // available transitions
+ // Hibernate.initialize(ti.getAvailableTransitions());
- // in TaskInstances created with jbpm 3.1, this association was
- // not present!
- ti.setProcessInstance(ti.getToken().getProcessInstance());
- ti.getToken().getNode().getName();
- ti.getTask().getName();
-
- ti.getAvailableTransitions();
-
retrieveVariables(ti);
}
- catch (Exception ex)
- {
- log.warn("exception while retrieving task instance data for task instance " + ti.getId(), ex);
+ catch (RuntimeException ex) {
+ log.warn("failure retrieving " + ti, ex);
}
}
- public ProcessInstance retrieveProcessInstance(ProcessInstance pi)
- {
- try
- {
- pi.getProcessDefinition().getName();
+ public ProcessInstance retrieveProcessInstance(ProcessInstance pi) {
+ try {
+ // process definition
+ Hibernate.initialize(pi.getProcessDefinition());
+ // root token
retrieveToken(pi.getRootToken());
-
- // load at least the super process id and token id
- if (pi.getSuperProcessToken() != null)
- {
- pi.getSuperProcessToken().getId();
- pi.getSuperProcessToken().getProcessInstance().getId();
+ // super process token
+ Token superProcessToken = pi.getSuperProcessToken();
+ if (superProcessToken != null) {
+ Hibernate.initialize(superProcessToken);
+ Hibernate.initialize(superProcessToken.getProcessInstance());
}
retrieveVariables(pi);
}
- catch (Exception ex)
- {
- log.warn("exception while retrieving process instance data for process instance " + pi.getId(), ex);
+ catch (RuntimeException ex) {
+ log.warn("failure retrieving " + pi, ex);
}
return pi;
}
- public ProcessDefinition retrieveProcessDefinition(ProcessDefinition pd)
- {
- try
- {
- pd.getName();
+ public ProcessDefinition retrieveProcessDefinition(ProcessDefinition pd) {
+ try {
// often needed to start a process:
- Iterator iter = pd.getStartState().getLeavingTransitions().iterator();
- while (iter.hasNext())
- {
- Transition t = (Transition)iter.next();
- t.getName();
+ for (Iterator iter = pd.getStartState().getLeavingTransitions().iterator(); iter.hasNext();) {
+ Transition transition = (Transition) iter.next();
+ Hibernate.initialize(transition);
}
}
- catch (Exception ex)
- {
- log.warn("exception while retrieving process instance data for process definiton " + pd.getName(), ex);
+ catch (RuntimeException ex) {
+ log.warn("failure retrieving " + pd, ex);
}
return pd;
}
- protected void retrieveToken(Token t)
- {
- retrieveNode(t.getNode());
- t.getAvailableTransitions();
+ protected void retrieveToken(Token token) {
+ retrieveNode(token.getNode());
+ // Hibernate.initialize(token.getAvailableTransitions());
- // if (includeLogs)
- // t.getProcessInstance().getLoggingInstance().
-
- Iterator iter = t.getChildren().values().iterator();
- while (iter.hasNext())
- {
- retrieveToken((Token)iter.next());
+ for (Iterator iter = token.getChildren().values().iterator(); iter.hasNext();) {
+ retrieveToken((Token) iter.next());
}
}
- protected void retrieveNode(Node n)
- {
- n.getName();
- n.getLeavingTransitions();
- if (n.getSuperState() != null)
- retrieveNode(n.getSuperState());
+ protected void retrieveNode(Node node) {
+ Hibernate.initialize(node);
+ // Hibernate.initialize(node.getLeavingTransitions());
+ if (node.getSuperState() != null) retrieveNode(node.getSuperState());
}
- public void retrieveVariables(ProcessInstance pi)
- {
- if (includeAllVariables)
- {
+ public void retrieveVariables(ProcessInstance pi) {
+ if (includeAllVariables) {
pi.getContextInstance().getVariables();
}
- else
- {
- for (int i = 0; i < variablesToInclude.length; i++)
- {
+ else {
+ for (int i = 0; i < variablesToInclude.length; i++) {
pi.getContextInstance().getVariable(variablesToInclude[i]);
}
}
}
- public void retrieveVariables(TaskInstance ti)
- {
- if (includeAllVariables)
- {
+ public void retrieveVariables(TaskInstance ti) {
+ if (includeAllVariables) {
ti.getVariables();
}
- else
- {
- for (int i = 0; i < variablesToInclude.length; i++)
- {
+ else {
+ for (int i = 0; i < variablesToInclude.length; i++) {
ti.getVariable(variablesToInclude[i]);
}
}
}
- public boolean isIncludeAllVariables()
- {
+ public boolean isIncludeAllVariables() {
return includeAllVariables;
}
- public void setIncludeAllVariables(boolean includeAllVariables)
- {
+ public void setIncludeAllVariables(boolean includeAllVariables) {
this.includeAllVariables = includeAllVariables;
}
- public String[] getVariablesToInclude()
- {
+ public String[] getVariablesToInclude() {
return variablesToInclude;
}
- public void setVariablesToInclude(String[] variablesToInclude)
- {
+ public void setVariablesToInclude(String[] variablesToInclude) {
this.variablesToInclude = variablesToInclude;
}
- public void setVariablesToInclude(String variableToInclude)
- {
- this.variablesToInclude = new String[] { variableToInclude };
+ public void setVariablesToInclude(String variableToInclude) {
+ this.variablesToInclude = new String[] {
+ variableToInclude
+ };
}
- protected JbpmContext getJbpmContext()
- {
+ protected JbpmContext getJbpmContext() {
return jbpmContext;
}
- protected void setJbpmContext(JbpmContext jbpmContext)
- {
+ protected void setJbpmContext(JbpmContext jbpmContext) {
this.jbpmContext = jbpmContext;
}
-
+
// methods for fluent programming
-
- public AbstractGetObjectBaseCommand variablesToInclude(String[] variablesToInclude)
- {
+
+ public AbstractGetObjectBaseCommand variablesToInclude(String[] variablesToInclude) {
setVariablesToInclude(variablesToInclude);
return this;
}
- public AbstractGetObjectBaseCommand variablesToInclude(String variableToInclude)
- {
+ public AbstractGetObjectBaseCommand variablesToInclude(String variableToInclude) {
setVariablesToInclude(variableToInclude);
return this;
}
-
- public AbstractGetObjectBaseCommand includeAllVariables(boolean includeAllVariables)
- {
- setIncludeAllVariables( includeAllVariables );
+
+ public AbstractGetObjectBaseCommand includeAllVariables(boolean includeAllVariables) {
+ setIncludeAllVariables(includeAllVariables);
return this;
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractProcessInstanceBaseCommand.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractProcessInstanceBaseCommand.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractProcessInstanceBaseCommand.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -13,22 +13,22 @@
import org.jbpm.util.ArrayUtil;
/**
- * Abstract base class for all commands working on {@link org.jbpm.graph.exe.ProcessInstance}s. The
- * {@link ProcessInstance} can either be specified by id or multiple ids. The alternative is to
- * specify a {@link ProcessDefinition} name and version. In this case <b>all</b> found
- * {@link ProcessInstance}s are processed. If no version is specified, <b>all</b> versions are taken
- * into account. if onlyRunning is set to false (default is true) already ended
+ * Abstract base class for all commands working on {@link org.jbpm.graph.exe.ProcessInstance}s.
+ * The {@link ProcessInstance} can either be specified by id or multiple ids. The alternative is
+ * to specify a {@link ProcessDefinition} name and version. In this case <b>all</b> found
+ * {@link ProcessInstance}s are processed. If no version is specified, <b>all</b> versions are
+ * taken into account. if onlyRunning is set to false (default is true) already ended
* {@link ProcessInstance}s are processed too.
*
* @author bernd.ruecker at camunda.com
*/
public abstract class AbstractProcessInstanceBaseCommand extends AbstractBaseCommand {
- protected Log log = LogFactory.getLog(this.getClass());
+ protected final Log log = LogFactory.getLog(getClass());
- private long[] processInstanceIds = null;
- private String processName = null;
- private int processVersion = 0;
+ private long[] processInstanceIds;
+ private String processName;
+ private int processVersion;
private boolean onlyRunning = true;
private boolean operateOnSingleObject;
@@ -45,8 +45,6 @@
ArrayList result = new ArrayList();
this.jbpmContext = jbpmContext;
try {
- log.debug("executing " + this);
-
// batch tokens
if (processInstanceIds != null && processInstanceIds.length > 0) {
for (int i = 0; i < processInstanceIds.length; i++) {
@@ -64,50 +62,36 @@
cmd.setOnlyRunning(onlyRunning);
if (processVersion > 0) cmd.setVersion(String.valueOf(processVersion));
- // Query query = null;
- // if (processVersion>0) {
- // query = jbpmContext.getSession().getNamedQuery("GraphSession.findProcessDefinitionByNameAndVersion");
- // query.setInteger("version", processVersion);
- // }
- // else {
- // query = jbpmContext.getSession().getNamedQuery("GraphSession.findTokensForProcessInNode");
- // }
- // query.setString("name", processName);
List processInstanceList = (List) cmd.execute(jbpmContext);
-
- Iterator iter = processInstanceList.iterator();
- while (iter.hasNext()) {
+ for (Iterator iter = processInstanceList.iterator(); iter.hasNext();) {
ProcessInstance pi = (ProcessInstance) iter.next();
execute(pi);
}
}
if (operateOnSingleObject) {
- if (result.size() < 1)
- return null;
- else
- return result.get(0);
+ return result.isEmpty() ? null : result.get(0);
}
else {
return result;
}
}
finally {
- this.jbpmContext = null;
+ jbpmContext = null;
}
}
public abstract ProcessInstance execute(ProcessInstance processInstance);
public void setProcessInstanceIds(long[] processInstanceIds) {
- this.operateOnSingleObject = false;
+ operateOnSingleObject = false;
this.processInstanceIds = processInstanceIds;
}
public void setProcessInstanceId(long processInstanceId) {
- this.operateOnSingleObject = true;
- this.processInstanceIds = new long[1];
- this.processInstanceIds[0] = processInstanceId;
+ operateOnSingleObject = true;
+ processInstanceIds = new long[1];
+ processInstanceIds[0] = processInstanceId;
}
/**
@@ -115,24 +99,15 @@
*/
public String toString() {
if (processName != null) {
- return this.getClass().getName()
- + " [tokenIds="
- + ArrayUtil.toString(processInstanceIds)
- + ";processName="
- + processName
- + ";processVersion="
- + (processVersion > 0 ? Integer.toString(processVersion) : "NA")
- + getAdditionalToStringInformation()
- + "]";
+ return getClass().getName() + " [tokenIds=" + ArrayUtil.toString(processInstanceIds)
+ + ";processName=" + processName + ";processVersion="
+ + (processVersion > 0 ? Integer.toString(processVersion) : "NA")
+ + getAdditionalToStringInformation() + "]";
}
else {
- return this.getClass().getName()
- + " [tokenIds="
- + ArrayUtil.toString(processInstanceIds)
- + ";operateOnSingleObject="
- + operateOnSingleObject
- + getAdditionalToStringInformation()
- + "]";
+ return getClass().getName() + " [tokenIds=" + ArrayUtil.toString(processInstanceIds)
+ + ";operateOnSingleObject=" + operateOnSingleObject
+ + getAdditionalToStringInformation() + "]";
}
}
@@ -163,7 +138,7 @@
public long getProcessInstanceId() {
if (processInstanceIds == null || processInstanceIds.length > 1) {
throw new IllegalStateException("multiple process instance ids set: "
- + ArrayUtil.toString(processInstanceIds));
+ + ArrayUtil.toString(processInstanceIds));
}
return processInstanceIds[0];
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractTokenBaseCommand.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractTokenBaseCommand.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/AbstractTokenBaseCommand.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -13,21 +13,21 @@
import org.jbpm.util.ArrayUtil;
/**
- * Abstract base class for commands working on Tokens. The {@link Token} can either be specified by
- * id or multiple ids. The alternative is to specify a {@link ProcessDefinition} name, a required
- * node name and version. In this case <b>all</b> found {@link Token}s are processed. If no version
- * is specified, <b>all</b> versions are taken into account.
+ * Abstract base class for commands working on Tokens. The {@link Token} can either be specified
+ * by id or multiple ids. The alternative is to specify a {@link ProcessDefinition} name, a
+ * required node name and version. In this case <b>all</b> found {@link Token}s are processed.
+ * If no version is specified, <b>all</b> versions are taken into account.
*
* @author bernd.ruecker at camunda.com
*/
public abstract class AbstractTokenBaseCommand implements Command {
- protected Log log = LogFactory.getLog(this.getClass());
+ protected final Log log = LogFactory.getLog(getClass());
- private long[] tokenIds = null;
- private String processName = null;
- private String stateName = null;
- private int processVersion = 0;
+ private long[] tokenIds;
+ private String processName;
+ private String stateName;
+ private int processVersion;
private boolean operateOnSingleObject;
@@ -43,8 +43,6 @@
this.jbpmContext = jbpmContext;
try {
ArrayList result = new ArrayList();
- log.debug("executing " + this);
-
// batch tokens
if (tokenIds != null && tokenIds.length > 0) {
for (int i = 0; i < tokenIds.length; i++) {
@@ -55,22 +53,22 @@
// search for tokens in process/state
if (processName != null && stateName != null) {
- this.operateOnSingleObject = false;
+ operateOnSingleObject = false;
- Query query = null;
+ Query query;
if (processVersion > 0) {
- query = jbpmContext.getSession().getNamedQuery(
- "GraphSession.findTokensForProcessVersionInNode");
+ query = jbpmContext.getSession()
+ .getNamedQuery("GraphSession.findTokensForProcessVersionInNode");
query.setInteger("processDefinitionVersion", processVersion);
}
else {
- query = jbpmContext.getSession().getNamedQuery("GraphSession.findTokensForProcessInNode");
+ query = jbpmContext.getSession()
+ .getNamedQuery("GraphSession.findTokensForProcessInNode");
}
query.setString("processDefinitionName", processName);
query.setString("nodeName", stateName);
- Iterator iter = query.list().iterator();
- while (iter.hasNext()) {
+ for (Iterator iter = query.list().iterator(); iter.hasNext();) {
Token token = (Token) iter.next();
result.add(execute(token));
}
@@ -94,14 +92,14 @@
public abstract Object execute(Token token);
public void setTokenIds(long[] tokenIds) {
- this.operateOnSingleObject = false;
+ operateOnSingleObject = false;
this.tokenIds = tokenIds;
}
public void setTokenId(long tokenId) {
- this.operateOnSingleObject = true;
- this.tokenIds = new long[1];
- this.tokenIds[0] = tokenId;
+ operateOnSingleObject = true;
+ tokenIds = new long[1];
+ tokenIds[0] = tokenId;
}
public String getAdditionalToStringInformation() {
@@ -149,26 +147,15 @@
public String toString() {
if (processName != null && stateName != null) {
- return this.getClass().getName()
- + " [tokenIds="
- + ArrayUtil.toString(tokenIds)
- + ";processName="
- + processName
- + ";processVersion="
- + (processVersion > 0 ? Integer.toString(processVersion) : "NA")
- + ";stateName="
- + stateName
- + getAdditionalToStringInformation()
- + "]";
+ return getClass().getName() + " [tokenIds=" + ArrayUtil.toString(tokenIds)
+ + ";processName=" + processName + ";processVersion="
+ + (processVersion > 0 ? Integer.toString(processVersion) : "NA") + ";stateName="
+ + stateName + getAdditionalToStringInformation() + "]";
}
else {
- return this.getClass().getName()
- + " [tokenIds="
- + ArrayUtil.toString(tokenIds)
- + ";operateOnSingleObject="
- + operateOnSingleObject
- + getAdditionalToStringInformation()
- + "]";
+ return getClass().getName() + " [tokenIds=" + ArrayUtil.toString(tokenIds)
+ + ";operateOnSingleObject=" + operateOnSingleObject
+ + getAdditionalToStringInformation() + "]";
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/BatchSignalCommand.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/BatchSignalCommand.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/BatchSignalCommand.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -5,8 +5,8 @@
import org.jbpm.graph.exe.Token;
/**
- * a bunch of processes is signaled with this command. you can specify the tokens either <li>by a
- * array of token ids <li>or by processName, processVersion (optional, without all versions),
+ * a bunch of processes is signaled with this command. you can specify the tokens either <li>by
+ * a array of token ids <li>or by processName, processVersion (optional, without all versions),
* stateName transitionName specifies the transition to take (if null, the default transition is
* taken).
*
@@ -17,17 +17,17 @@
private static final long serialVersionUID = -4330623193546102772L;
/**
- * if set, only tokens which are started after this date are signaled (interesting to implement
- * some timeout for example)
+ * if set, only tokens which are started after this date are signaled (interesting to
+ * implement some timeout for example)
*/
- private Date inStateAtLeastSince = null;
+ private Date inStateAtLeastSince;
- private String transitionName = null;
+ private String transitionName;
public Object execute(Token token) {
if (inStateAtLeastSince == null || token.getNodeEnter().before(inStateAtLeastSince)) {
- log.debug("signal token " + token);
+ if (log.isDebugEnabled()) log.debug("signalling " + token);
if (transitionName == null) {
token.signal();
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/ChangeProcessInstanceVersionCommand.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/ChangeProcessInstanceVersionCommand.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/ChangeProcessInstanceVersionCommand.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -27,22 +27,24 @@
/**
* <b>THIS COMMAND IS NOT YET STABLE, BUT FEEL FREE TO TEST :-)</b><br>
* Status update: Still not complete, but refactored and added simple test cases.<br>
- * Change the version of a running process instance. This works only, if the current node is also
- * available in the new version of the process definition or a name mapping has to be provided.<br>
+ * Change the version of a running process instance. This works only, if the current node is
+ * also available in the new version of the process definition or a name mapping has to be
+ * provided.<br>
* <b>Currently known limitations:</b>
* <ul>
- * <li> {@link Task}s cannot move "into" another node. If an active {@link TaskInstance} exists, the
- * {@link Task} definition must exist in the {@link TaskNode} with the same (or mapped) name.
- * Otherwise the right node cannot be found easily because it may be ambiguous.</li>
- * <li>Sub processes aren't yet tested. Since the {@link ProcessState} is a {@link Node} like any
- * other, it should work anyway.</li>
- * <li>Can have <b>negative impact on referential integrity</b>! Because one {@link ProcessInstance}
- * can have {@link ProcessLog}s point to old {@link ProcessDefinition}s. Hence, delete a
- * {@link ProcessDefinition} may not work and throw an Exception (Integrity constraint violation)</li>
+ * <li> {@link Task}s cannot move "into" another node. If an active {@link TaskInstance} exists,
+ * the {@link Task} definition must exist in the {@link TaskNode} with the same (or mapped)
+ * name. Otherwise the right node cannot be found easily because it may be ambiguous.</li>
+ * <li>Sub processes aren't yet tested. Since the {@link ProcessState} is a {@link Node} like
+ * any other, it should work anyway.</li>
+ * <li>Can have <b>negative impact on referential integrity</b>! Because one
+ * {@link ProcessInstance} can have {@link ProcessLog}s point to old {@link ProcessDefinition}s.
+ * Hence, delete a {@link ProcessDefinition} may not work and throw an Exception (Integrity
+ * constraint violation)</li>
* <li>In combination with ESB the ESB uses {@link Token}.id <b>and</b> {@link Node}.id as
- * correlation identifier. After changing the version of a {@link ProcessInstance} the {@link Node}
- * .id has changed, so a signal from ESB will result in an exception and has to be corrected
- * manually.</li>
+ * correlation identifier. After changing the version of a {@link ProcessInstance} the
+ * {@link Node} .id has changed, so a signal from ESB will result in an exception and has to be
+ * corrected manually.</li>
* </ul>
*
* @author Bernd Ruecker (bernd.ruecker at camunda.com)
@@ -59,9 +61,9 @@
private static final Log log = LogFactory.getLog(ChangeProcessInstanceVersionCommand.class);
/**
- * the map configures for every node-name in the old process definition (as key) which node-name
- * to use in the new process definition. if a node is not mentioned in this Map, old node name =
- * new node name is applied
+ * the map configures for every node-name in the old process definition (as key) which
+ * node-name to use in the new process definition. if a node is not mentioned in this Map, old
+ * node name = new node name is applied
*/
private Map nodeNameMapping = new HashMap();
@@ -91,27 +93,20 @@
ProcessDefinition newDef = loadNewProcessDefinition(oldDef.getName());
if (newDef == null) {
- throw new JbpmException("Process definition " +
- oldDef.getName() +
- " in version " +
- newVersion +
- " not found.");
+ throw new JbpmException("Process definition " + oldDef.getName() + " in version "
+ + newVersion + " not found.");
}
- log.debug("Start changing process id " +
- pi.getId() +
- " from version " +
- pi.getProcessDefinition().getVersion() +
- " to new version " +
- newDef.getVersion());
+ if (log.isDebugEnabled()) {
+ log.debug("changing " + pi + " from version " + oldDef.getVersion() + " to new version "
+ + newDef.getVersion());
+ }
pi.setProcessDefinition(newDef);
-
changeTokenVersion(pi.getRootToken());
- log.debug("process id " +
- pi.getId() +
- " changed to version " +
- pi.getProcessDefinition().getVersion());
+ if (log.isDebugEnabled()) {
+ log.debug(pi + " changed to version " + newDef.getVersion());
+ }
return pi;
}
@@ -121,7 +116,9 @@
private void changeTokenVersion(Token token) {
ProcessDefinition newDef = getNewProcessDefinition(token);
- log.debug("change token id " + token.getId() + " to new version " + newDef.getVersion());
+ if (log.isDebugEnabled()) {
+ log.debug("changing " + token + " to version " + newDef.getVersion());
+ }
// change node reference on token (current node)
Node oldNode = token.getNode();
@@ -145,6 +142,8 @@
private void adjustTaskInstancesForToken(Token token) {
ProcessDefinition newDef = getNewProcessDefinition(token);
+ boolean debug = log.isDebugEnabled();
+
for (Iterator i = getTasksForToken(token).iterator(); i.hasNext();) {
TaskInstance ti = (TaskInstance) i.next();
@@ -154,7 +153,7 @@
Task newTask = findReplacementTask(newDef, oldNode, oldTask);
ti.setTask(newTask);
- log.debug("change dependent task-instance with id " + oldTask.getId());
+ if (debug) log.debug("adjusted " + ti);
}
}
@@ -190,7 +189,8 @@
String name = getReplacementNodeName(oldNode);
Node newNode = newDef.findNode(name);
if (newNode == null) {
- throw new JbpmException("node with name '" + name + "' not found in new process definition");
+ throw new JbpmException("node with name '" + name
+ + "' not found in new process definition");
}
return newNode;
}
@@ -200,27 +200,26 @@
Node newTaskNode = findReplacementNode(newDef, oldNode);
Session session = getJbpmContext().getSession();
- Long newTaskId = (Long) session.getNamedQuery("TaskMgmtSession.findTaskForNode").setString(
- "taskName", replacementTaskName).setLong("taskNodeId", newTaskNode.getId()).uniqueResult();
+ Long newTaskId = (Long) session.getNamedQuery("TaskMgmtSession.findTaskForNode")
+ .setString("taskName", replacementTaskName)
+ .setLong("taskNodeId", newTaskNode.getId())
+ .uniqueResult();
if (newTaskId == null) {
- throw new JbpmException("Task '" +
- replacementTaskName +
- "' for node '" +
- newTaskNode.getName() +
- "' not found in new process definition");
+ throw new JbpmException("Task '" + replacementTaskName + "' for node '"
+ + newTaskNode.getName() + "' not found in new process definition");
}
return (Task) session.load(Task.class, newTaskId);
}
/**
* @param oldNode
- * @return the name of the new node (given in the map or return default value, which is the old
- * node name)
+ * @return the name of the new node (given in the map or return default value, which is the
+ * old node name)
*/
private String getReplacementNodeName(GraphElement oldNode) {
String oldName = oldNode instanceof Node ? ((Node) oldNode).getFullyQualifiedName()
- : oldNode.getName();
+ : oldNode.getName();
if (nodeNameMapping.containsKey(oldName)) {
return (String) nodeNameMapping.get(oldName);
}
@@ -238,12 +237,12 @@
}
/**
- * We may still have open tasks, even though their parent tokens have been ended. So we'll simply
- * get all tasks from this process instance and cancel them if they are still active.
+ * We may still have open tasks, even though their parent tokens have been ended. So we'll
+ * simply get all tasks from this process instance and cancel them if they are still active.
*/
private List getTasksForToken(Token token) {
- Query query = getJbpmContext().getSession().getNamedQuery(
- "TaskMgmtSession.findTaskInstancesByTokenId");
+ Query query = getJbpmContext().getSession()
+ .getNamedQuery("TaskMgmtSession.findTaskInstancesByTokenId");
query.setLong("tokenId", token.getId());
return query.list();
@@ -332,7 +331,7 @@
}
public ChangeProcessInstanceVersionCommand nodeNameMappingAdd(String oldNodeName,
- String newNodeName) {
+ String newNodeName) {
if (nodeNameMapping == null) {
this.nodeNameMapping = new HashMap();
}
@@ -342,7 +341,7 @@
}
public ChangeProcessInstanceVersionCommand taskNameMappingAdd(String oldTaskName,
- String newNodeName) {
+ String newNodeName) {
if (taskNameMapping == null) {
this.taskNameMapping = new HashMap();
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/DeployProcessCommand.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/DeployProcessCommand.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/DeployProcessCommand.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -3,8 +3,6 @@
import java.io.ByteArrayInputStream;
import java.util.zip.ZipInputStream;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
import org.jbpm.JbpmContext;
import org.jbpm.JbpmException;
import org.jbpm.graph.def.ProcessDefinition;
@@ -12,103 +10,84 @@
/**
* Deploys a process, given as XML-String or process archive.
*
- * If both are given, the byte-array will be preferred The deployed process definition is returned
+ * If both are given, the byte-array will be preferred The deployed process definition is
+ * returned
*
* @author Bernd Ruecker (bernd.ruecker at camunda.com)
*
*/
-public class DeployProcessCommand extends AbstractGetObjectBaseCommand
-{
+public class DeployProcessCommand extends AbstractGetObjectBaseCommand {
+
private static final long serialVersionUID = -5861811926680981061L;
private String xml;
private byte[] par;
- private static final Log log = LogFactory.getLog(DeployProcessCommand.class);
-
- public DeployProcessCommand()
- {
+ public DeployProcessCommand() {
}
- public DeployProcessCommand(byte[] par)
- {
+ public DeployProcessCommand(byte[] par) {
setPar(par);
}
- public DeployProcessCommand(String xml)
- {
+ public DeployProcessCommand(String xml) {
setXml(xml);
}
/**
* @return deployed ProcessDefinition
*/
- public Object execute(JbpmContext jbpmContext) throws Exception
- {
- if (par == null && xml == null)
+ public Object execute(JbpmContext jbpmContext) throws Exception {
+ if (par == null && xml == null) {
throw new JbpmException("either xml string or process archive must be given.");
+ }
ProcessDefinition processDefinition;
- if (par != null)
- {
- log.debug("parse process from archive");
-
+ boolean debug = log.isDebugEnabled();
+ if (par != null) {
+ if (debug) log.debug("parsing process from archive");
// Thanks to George Mournos who helped to improve this:
ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(par));
processDefinition = ProcessDefinition.parseParZipInputStream(zipInputStream);
}
- else
- {
- log.debug("parse process from string");
- if (log.isTraceEnabled())
- log.trace("deploy process:\n" + xml);
-
+ else {
+ if (debug) log.debug("parsing process from string");
processDefinition = ProcessDefinition.parseXmlString(xml);
}
jbpmContext.deployProcessDefinition(processDefinition);
- log.debug("deployment sucessfull");
+ if (debug) log.debug(processDefinition + " deployed successfully");
return retrieveProcessDefinition(processDefinition);
}
- public byte[] getPar()
- {
+ public byte[] getPar() {
return par;
}
- public void setPar(byte[] par)
- {
+ public void setPar(byte[] par) {
+ if (par == null) throw new IllegalArgumentException("process archive is null");
this.par = par;
-
- if (par == null || par.length == 0)
- throw new IllegalArgumentException("Cannot process null process archive");
}
- public String getXml()
- {
+ public String getXml() {
return xml;
}
- public void setXml(String xml)
- {
+ public void setXml(String xml) {
+ if (xml == null) throw new IllegalArgumentException("xml is null");
this.xml = xml;
-
- if (xml == null || xml.length() == 0)
- throw new IllegalArgumentException("Cannot process null process definition");
}
-
+
// methods for fluent programming
- public DeployProcessCommand xml(String xml)
- {
+ public DeployProcessCommand xml(String xml) {
setXml(xml);
return this;
}
-
- public DeployProcessCommand par(byte[] par)
- {
+
+ public DeployProcessCommand par(byte[] par) {
setPar(par);
return this;
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/ExecuteJobsCommand.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/ExecuteJobsCommand.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/ExecuteJobsCommand.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -1,175 +1,128 @@
package org.jbpm.command;
-import java.io.PrintWriter;
-import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
-import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.hibernate.Hibernate;
-import org.hibernate.StaleStateException;
+
import org.jbpm.JbpmContext;
-import org.jbpm.JbpmException;
import org.jbpm.db.JobSession;
+import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.job.Job;
-import org.jbpm.job.Timer;
/**
* Execute all overdue Jobs (may be enhanced with more attributes in future if needed)
*
* @author ruecker
*/
-public class ExecuteJobsCommand extends AbstractBaseCommand
-{
+public class ExecuteJobsCommand extends AbstractBaseCommand {
private static final long serialVersionUID = -2457066688404533959L;
private static final Log log = LogFactory.getLog(ExecuteJobsCommand.class);
- private static final int maxLockTime = 60000;
-
private transient JbpmContext jbpmContext;
- public Object execute(JbpmContext jbpmContext) throws Exception
- {
+ public Object execute(JbpmContext jbpmContext) throws Exception {
this.jbpmContext = jbpmContext;
- try
- {
+ try {
+ // acquire jobs; on exception, call returns empty collection
Collection acquiredJobs = acquireJobs();
-
- if (!acquiredJobs.isEmpty())
- {
- Iterator iter = acquiredJobs.iterator();
- while (iter.hasNext())
- {
- Job job = (Job)iter.next();
- executeJob(job);
- }
+ // execute jobs
+ for (Iterator i = acquiredJobs.iterator(); i.hasNext();) {
+ Job job = (Job) i.next();
+ executeJob(job);
}
-
- // Job job = jbpmContext.getJobSession().getFirstAcquirableJob("");
- // if (job != null) {
- // log.info("execution job: " + job);
- // job.execute(jbpmContext);
- // }
}
- catch (JbpmException ex)
- {
- log.warn("exception while executing job", ex);
+ finally {
+ this.jbpmContext = null;
}
- this.jbpmContext = null;
return null;
}
- private String getName()
- {
+ private String getName() {
return this.toString();
}
- protected Collection acquireJobs()
- {
- Collection acquiredJobs = null;
- Collection jobsToLock = new ArrayList();
- log.debug("acquiring jobs for execution...");
-
- try
- {
+ protected Collection acquireJobs() {
+ boolean debug = log.isDebugEnabled();
+ Collection jobs;
+ try {
+ // search for acquirable job
+ String lockOwner = getName();
JobSession jobSession = jbpmContext.getJobSession();
- log.debug("querying for acquirable job...");
- Job job = jobSession.getFirstAcquirableJob(getName());
- if (job != null)
- {
- if (job.isExclusive())
- {
- log.debug("exclusive acquirable job found (" + job + "). querying for other exclusive jobs to lock them all in one tx...");
- List otherExclusiveJobs = jobSession.findExclusiveJobs(getName(), job.getProcessInstance());
- jobsToLock.addAll(otherExclusiveJobs);
- log.debug("trying to obtain a process-instance exclusive locks for '" + otherExclusiveJobs + "'");
+ Job firstJob = jobSession.getFirstAcquirableJob(lockOwner);
+ // is there a job?
+ if (firstJob != null) {
+ // is job exclusive?
+ if (firstJob.isExclusive()) {
+ // find other exclusive jobs
+ ProcessInstance processInstance = firstJob.getProcessInstance();
+ jobs = jobSession.findExclusiveJobs(lockOwner, processInstance);
+ if (debug) log.debug("acquiring exclusive " + jobs + " for " + processInstance);
}
- else
- {
- log.debug("trying to obtain a lock for '" + job + "'");
- jobsToLock.add(job);
+ else {
+ jobs = Collections.singletonList(firstJob);
+ if (debug) log.debug("acquiring " + firstJob);
}
- Iterator iter = jobsToLock.iterator();
- while (iter.hasNext())
- {
- job = (Job)iter.next();
- job.setLockOwner(getName());
- job.setLockTime(new Date());
- // jbpmContext.getSession().update(job);
+ // acquire jobs
+ Date lockTime = new Date();
+ for (Iterator i = jobs.iterator(); i.hasNext();) {
+ // lock job
+ Job job = (Job) i.next();
+ job.setLockOwner(lockOwner);
+ job.setLockTime(lockTime);
+ // has job failed previously?
+ if (job.getException() == null) {
+ // initialize retry count
+ job.setRetries(3);
+ }
+ else {
+ // decrease retry count
+ int retries = job.getRetries() - 1;
+ job.setRetries(retries);
+ if (debug) log.debug(job + " has " + retries + " retries remaining");
+ }
}
-
- // HACKY HACK : this is a workaround for a hibernate problem that is fixed in hibernate 3.2.1
- if (job instanceof Timer)
- {
- Hibernate.initialize(((Timer)job).getGraphElement());
- }
-
+ if (debug) log.debug("acquired " + jobs);
}
- else
- {
- log.debug("no acquirable jobs in job table");
+ else {
+ jobs = Collections.EMPTY_LIST;
+ if (debug) log.debug("no acquirable job found");
}
-
- acquiredJobs = jobsToLock;
- log.debug("obtained locks on following jobs: " + acquiredJobs);
-
}
- catch (StaleStateException e)
- {
- log.debug("couldn't acquire lock on job(s): " + jobsToLock);
+ catch (RuntimeException e) {
+ jobs = Collections.EMPTY_LIST;
+ if (debug) log.debug("failed to acquire jobs", e);
}
- return acquiredJobs;
+ return jobs;
}
- protected void executeJob(Job job)
- {
+ protected void executeJob(Job job) throws Exception {
JobSession jobSession = jbpmContext.getJobSession();
- job = jobSession.loadJob(job.getId());
+ jobSession.reattachJob(job);
- try
- {
- log.debug("executing job " + job);
- if (job.execute(jbpmContext))
- {
- jobSession.deleteJob(job);
- }
+ // register process instance for automatic save
+ // see https://jira.jboss.org/jira/browse/JBPM-1015
+ jbpmContext.addAutoSaveProcessInstance(job.getProcessInstance());
- }
- catch (Exception e)
- {
- log.debug("exception while executing '" + job + "'", e);
- StringWriter sw = new StringWriter();
- e.printStackTrace(new PrintWriter(sw));
- job.setException(sw.toString());
- job.setRetries(job.getRetries() - 1);
- }
-
- // if this job is locked too long
- long totalLockTimeInMillis = System.currentTimeMillis() - job.getLockTime().getTime();
- if (totalLockTimeInMillis > maxLockTime)
- {
- jbpmContext.setRollbackOnly();
- }
-
+ if (log.isDebugEnabled()) log.debug("executing " + job);
+ if (job.execute(jbpmContext)) jobSession.deleteJob(job);
}
- protected Date getNextDueDate()
- {
+ protected Date getNextDueDate() {
Date nextDueDate = null;
JobSession jobSession = jbpmContext.getJobSession();
Job job = jobSession.getFirstDueJob(getName(), new ArrayList());
- if (job != null)
- {
+ if (job != null) {
nextDueDate = job.getDueDate();
}
return nextDueDate;
}
-
+
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/SignalCommand.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/SignalCommand.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/SignalCommand.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -23,9 +23,6 @@
import java.util.Map;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
import org.jbpm.JbpmContext;
import org.jbpm.JbpmException;
import org.jbpm.graph.exe.ProcessInstance;
@@ -34,26 +31,25 @@
/**
* Signals a token. After signalling the token is returned
*
- * @author ??, Bernd Ruecker
+ * @author Bernd Ruecker
*/
public class SignalCommand extends AbstractBaseCommand {
private static final long serialVersionUID = 1L;
- private static Log log = LogFactory.getLog(SignalCommand.class);
- private long tokenId = 0;
+ private long tokenId;
- private String transitionName = null;
+ private String transitionName;
/**
- * if given, it is checked if the state is as expected. If not, a exception is thrown Ignored if
- * null
+ * if given, it is checked if the state is as expected. If not, a exception is thrown Ignored
+ * if null
*/
- private String expectedStateName = null;
+ private String expectedStateName;
- private Token previousToken = null;
+ private Token previousToken;
- private ProcessInstance previousProcessInstance = null;
+ private ProcessInstance previousProcessInstance;
private Map variables;
@@ -66,7 +62,6 @@
}
public Object execute(JbpmContext jbpmContext) {
- log.debug("executing " + this);
if (previousProcessInstance != null) {
if (variables != null && variables.size() > 0)
@@ -84,11 +79,8 @@
Token token = getToken(jbpmContext);
if (expectedStateName != null && !expectedStateName.equals(token.getNode().getName()))
- throw new JbpmException("token is not in expected state '"
- + expectedStateName
- + "' but in '"
- + token.getNode().getName()
- + "'");
+ throw new JbpmException("token is not in expected state '" + expectedStateName
+ + "' but in '" + token.getNode().getName() + "'");
if (variables != null && variables.size() > 0)
token.getProcessInstance().getContextInstance().addVariables(variables);
@@ -143,15 +135,10 @@
}
public String getAdditionalToStringInformation() {
- return "tokenId="
- + tokenId
- + ";transitionName="
- + transitionName
- + ";processDefinitionName="
- + expectedStateName
- // TODO: not sure how this is
- + ";variables="
- + variables;
+ return "tokenId=" + tokenId + ";transitionName=" + transitionName
+ + ";processDefinitionName=" + expectedStateName
+ // TODO: not sure how this is
+ + ";variables=" + variables;
}
// methods for fluent programming
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/impl/CommandServiceImpl.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/impl/CommandServiceImpl.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/command/impl/CommandServiceImpl.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -41,7 +41,7 @@
private static final long serialVersionUID = 1L;
- protected JbpmConfiguration jbpmConfiguration = null;
+ protected JbpmConfiguration jbpmConfiguration;
/**
* Establish an instance of the command service with a particular jBPM configuration which
@@ -55,16 +55,16 @@
}
/**
- * Executes command based on its current context. Each command contains the appropriate context
- * information such as token, process instance, etc. to insure that the operation is carried out
- * on the proper graph object.
+ * Executes command based on its current context. Each command contains the appropriate
+ * context information such as token, process instance, etc. to insure that the operation is
+ * carried out on the proper graph object.
*
* @param command jBPM engine command to execute
*/
public Object execute(Command command) {
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
- log.debug("executing " + command);
+ if (log.isDebugEnabled()) log.debug("executing " + command);
return command.execute(jbpmContext);
}
catch (RuntimeException e) {
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/JbpmContextInfo.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/JbpmContextInfo.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/JbpmContextInfo.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -52,9 +52,8 @@
// parse the services
serviceFactoryObjectInfos = new HashMap();
- List serviceElements = XmlUtil.elements(jbpmContextElement, "service");
serviceNames = new ArrayList();
- for (Iterator iter = serviceElements.iterator(); iter.hasNext();) {
+ for (Iterator iter = XmlUtil.elementIterator(jbpmContextElement, "service"); iter.hasNext();) {
Element serviceElement = (Element) iter.next();
if (!serviceElement.hasAttribute("name")) {
throw new ConfigurationException("name is required in service element "
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/JbpmTypeObjectInfo.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/JbpmTypeObjectInfo.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/JbpmTypeObjectInfo.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -37,9 +37,9 @@
private static final long serialVersionUID = 1L;
- ObjectInfo typeMatcherObjectInfo = null;
- Converter converter = null;
- Class variableInstanceClass = null;
+ ObjectInfo typeMatcherObjectInfo;
+ Converter converter;
+ Class variableInstanceClass;
public JbpmTypeObjectInfo(Element jbpmTypeElement, ObjectFactoryParser objectFactoryParser) {
super(jbpmTypeElement, objectFactoryParser);
@@ -48,7 +48,7 @@
Element typeMatcherElement = XmlUtil.element(jbpmTypeElement, "matcher");
if (typeMatcherElement == null) {
throw new ConfigurationException("matcher is a required element in a jbpm-type: "
- + XmlUtil.toString(jbpmTypeElement));
+ + XmlUtil.toString(jbpmTypeElement));
}
Element typeMatcherBeanElement = XmlUtil.element(typeMatcherElement);
typeMatcherObjectInfo = objectFactoryParser.parse(typeMatcherBeanElement);
@@ -56,7 +56,8 @@
Element converterElement = XmlUtil.element(jbpmTypeElement, "converter");
if (converterElement != null) {
if (!converterElement.hasAttribute("class")) {
- throw new ConfigurationException("class attribute is required in a converter element: "
+ throw new ConfigurationException(
+ "class attribute is required in a converter element: "
+ XmlUtil.toString(jbpmTypeElement));
}
String converterClassName = converterElement.getAttribute("class");
@@ -66,31 +67,30 @@
Element variableInstanceElement = XmlUtil.element(jbpmTypeElement, "variable-instance");
if (!variableInstanceElement.hasAttribute("class")) {
throw new ConfigurationException(
- "class is a required attribute in element variable-instance: "
- + XmlUtil.toString(jbpmTypeElement));
+ "class is a required attribute in element variable-instance: "
+ + XmlUtil.toString(jbpmTypeElement));
}
String variableInstanceClassName = variableInstanceElement.getAttribute("class");
variableInstanceClass = ClassLoaderUtil.classForName(variableInstanceClassName);
if (!VariableInstance.class.isAssignableFrom(variableInstanceClass)) {
throw new ConfigurationException("variable instance class '"
- + variableInstanceClassName
- + "' is not a VariableInstance");
+ + variableInstanceClassName + "' is not a VariableInstance");
}
}
catch (ConfigurationException e) {
throw e;
}
catch (Exception e) {
- // NOTE that Error's are not caught because that might halt the JVM and mask the original Error.
- // Probably the user doesn't need support for this type and doesn't have a required library in the path.
- // So let's log and ignore
- log.debug("jbpm variables type "
- + XmlUtil.toString(jbpmTypeElement)
- + " couldn't be instantiated properly: "
- + e.toString());
- // now, let's make sure that this JbpmType is ignored by always returning false in the JbpmTypeMatcher
+ // NOTE that Error's are not caught because that might halt the JVM
+ // and mask the original Error
+ // Probably the user does not need support for this type and does not have a required
+ // library in the path. So let's log and ignore
+ if (log.isDebugEnabled()) {
+ log.debug("jbpm variables type " + XmlUtil.toString(jbpmTypeElement)
+ + " could not be instantiated", e);
+ }
+ // make sure this JbpmType is ignored by always returning false in the JbpmTypeMatcher
typeMatcherObjectInfo = new ObjectInfo() {
-
private static final long serialVersionUID = 1L;
public boolean hasName() {
@@ -126,5 +126,5 @@
return new JbpmType(jbpmTypeMatcher, converter, variableInstanceClass);
}
- private static Log log = LogFactory.getLog(JbpmTypeObjectInfo.class);
+ private static final Log log = LogFactory.getLog(JbpmTypeObjectInfo.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/ListInfo.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/ListInfo.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/ListInfo.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -31,14 +31,14 @@
private static final long serialVersionUID = 1L;
- ObjectInfo[] elementInfos = null;
+ private ObjectInfo[] elementInfos;
public ListInfo(Element listElement, ObjectFactoryParser configParser) {
super(listElement, configParser);
List elementElements = XmlUtil.elements(listElement);
elementInfos = new ObjectInfo[elementElements.size()];
- for (int i=0; i<elementElements.size(); i++) {
+ for (int i = 0; i < elementElements.size(); i++) {
Element elementElement = (Element) elementElements.get(i);
elementInfos[i] = configParser.parse(elementElement);
}
@@ -46,8 +46,8 @@
public Object createObject(ObjectFactoryImpl objectFactory) {
List list = new ArrayList();
- if (elementInfos!=null) {
- for (int i=0; i<elementInfos.length; i++) {
+ if (elementInfos != null) {
+ for (int i = 0; i < elementInfos.length; i++) {
Object element = objectFactory.getObject(elementInfos[i]);
list.add(element);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/MapInfo.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/MapInfo.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/MapInfo.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -31,17 +31,17 @@
public class MapInfo extends AbstractObjectInfo {
private static final long serialVersionUID = 1L;
-
- ObjectInfo[] keyInfos = null;
- ObjectInfo[] valueInfos = null;
+ private ObjectInfo[] keyInfos;
+ private ObjectInfo[] valueInfos;
+
public MapInfo(Element mapElement, ObjectFactoryParser configParser) {
super(mapElement, configParser);
List entryElements = XmlUtil.elements(mapElement);
keyInfos = new ObjectInfo[entryElements.size()];
valueInfos = new ObjectInfo[entryElements.size()];
- for (int i=0; i<entryElements.size(); i++) {
+ for (int i = 0; i < entryElements.size(); i++) {
Element entryElement = (Element) entryElements.get(i);
Element keyElement = XmlUtil.element(entryElement, "key");
Element valueElement = XmlUtil.element(entryElement, "value");
@@ -52,8 +52,8 @@
public Object createObject(ObjectFactoryImpl objectFactory) {
Map map = new HashMap();
- if (keyInfos!=null) {
- for (int i=0; i<keyInfos.length; i++) {
+ if (keyInfos != null) {
+ for (int i = 0; i < keyInfos.length; i++) {
Object key = objectFactory.getObject(keyInfos[i]);
Object value = objectFactory.getObject(valueInfos[i]);
map.put(key, value);
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/ObjectFactoryImpl.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/ObjectFactoryImpl.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/ObjectFactoryImpl.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -57,11 +57,9 @@
public void addObjectInfo(ObjectInfo objectInfo) {
if (objectInfo.hasName()) {
- log.debug("adding object info '" + objectInfo.getName() + "'");
+ if (log.isDebugEnabled()) log.debug("adding object info: " + objectInfo.getName());
Object removed = namedObjectInfos.put(objectInfo.getName(), objectInfo);
- if (removed != null) {
- objectInfos.remove(removed);
- }
+ if (removed != null) objectInfos.remove(removed);
}
objectInfos.add(objectInfo);
}
@@ -73,10 +71,9 @@
public synchronized Object createObject(String name) {
ObjectInfo objectInfo = (ObjectInfo) namedObjectInfos.get(name);
if (objectInfo == null) {
- throw new ConfigurationException("name '"
- + name
- + "' is not defined in the configuration. configured names: "
- + namedObjectInfos.keySet());
+ throw new ConfigurationException("name '" + name
+ + "' is not defined in the configuration. configured names: "
+ + namedObjectInfos.keySet());
}
return createObject(objectInfo);
}
@@ -91,11 +88,8 @@
*/
public Object createObject(int index) {
if (index < 0 || index >= objectInfos.size()) {
- throw new ConfigurationException("index '"
- + index
- + "' is not defined in the configuration. range [0.."
- + (objectInfos.size() - 1)
- + "]");
+ throw new ConfigurationException("index '" + index
+ + "' is not defined in the configuration. range [0.." + (objectInfos.size() - 1) + "]");
}
return createObject((ObjectInfo) objectInfos.get(index));
}
@@ -126,10 +120,8 @@
object = getObject(objectInfo);
}
else {
- log.warn("no info for object '"
- + name
- + "'. defined objects: "
- + namedObjectInfos.keySet().toString());
+ log.warn("no info for object '" + name + "'. defined objects: "
+ + namedObjectInfos.keySet().toString());
}
return object;
}
@@ -188,7 +180,7 @@
boolean isInRegistry(Object registryKey) {
return registryKey != null
- && (objects.containsKey(registryKey) || singletons.containsKey(registryKey));
+ && (objects.containsKey(registryKey) || singletons.containsKey(registryKey));
}
void putInRegistry(ObjectInfo objectInfo, Object object, Object registryKey) {
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/ObjectFactoryParser.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/ObjectFactoryParser.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/configuration/ObjectFactoryParser.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -26,6 +26,7 @@
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -36,43 +37,51 @@
public class ObjectFactoryParser implements Serializable {
private static final long serialVersionUID = 1L;
-
- static Map defaultMappings = null;
+
+ private static Map defaultMappings;
+
public static Map getDefaultMappings() {
- if (defaultMappings==null) {
+ if (defaultMappings == null) {
defaultMappings = new HashMap();
- addMapping(defaultMappings, "bean", BeanInfo.class);
- addMapping(defaultMappings, "ref", RefInfo.class);
- addMapping(defaultMappings, "list", ListInfo.class);
- addMapping(defaultMappings, "map", MapInfo.class);
- addMapping(defaultMappings, "string", StringInfo.class);
- addMapping(defaultMappings, "int", IntegerInfo.class);
- addMapping(defaultMappings, "integer", IntegerInfo.class);
- addMapping(defaultMappings, "long", LongInfo.class);
- addMapping(defaultMappings, "float", FloatInfo.class);
- addMapping(defaultMappings, "double", DoubleInfo.class);
- addMapping(defaultMappings, "char", CharacterInfo.class);
- addMapping(defaultMappings, "character", CharacterInfo.class);
- addMapping(defaultMappings, "boolean", BooleanInfo.class);
- addMapping(defaultMappings, "true", BooleanInfo.class);
- addMapping(defaultMappings, "false", BooleanInfo.class);
- addMapping(defaultMappings, "null", NullInfo.class);
+ addMapping(defaultMappings, "bean", BeanInfo.class);
+ addMapping(defaultMappings, "ref", RefInfo.class);
+ addMapping(defaultMappings, "list", ListInfo.class);
+ addMapping(defaultMappings, "map", MapInfo.class);
+ addMapping(defaultMappings, "string", StringInfo.class);
+ addMapping(defaultMappings, "int", IntegerInfo.class);
+ addMapping(defaultMappings, "integer", IntegerInfo.class);
+ addMapping(defaultMappings, "long", LongInfo.class);
+ addMapping(defaultMappings, "float", FloatInfo.class);
+ addMapping(defaultMappings, "double", DoubleInfo.class);
+ addMapping(defaultMappings, "char", CharacterInfo.class);
+ addMapping(defaultMappings, "character", CharacterInfo.class);
+ addMapping(defaultMappings, "boolean", BooleanInfo.class);
+ addMapping(defaultMappings, "true", BooleanInfo.class);
+ addMapping(defaultMappings, "false", BooleanInfo.class);
+ addMapping(defaultMappings, "null", NullInfo.class);
addMapping(defaultMappings, "jbpm-context", JbpmContextInfo.class);
- addMapping(defaultMappings, "jbpm-type", JbpmTypeObjectInfo.class);
+ addMapping(defaultMappings, "jbpm-type", JbpmTypeObjectInfo.class);
}
return defaultMappings;
}
- static final Class[] constructorParameterTypes = new Class[]{Element.class, ObjectFactoryParser.class};
- static void addMapping(Map mappings, String elementTagName, Class objectInfoClass) {
+ private static final Class[] constructorParameterTypes = new Class[] {
+ Element.class, ObjectFactoryParser.class
+ };
+
+ private static void addMapping(Map mappings, String elementTagName, Class objectInfoClass) {
try {
Constructor constructor = objectInfoClass.getDeclaredConstructor(constructorParameterTypes);
mappings.put(elementTagName, constructor);
- } catch (Exception e) {
- throw new JbpmException("couldn't add mapping for element '"+elementTagName+"': constructor("+Element.class.getName()+","+ObjectFactoryParser.class.getName()+") was missing for class '"+objectInfoClass.getName()+"'", e);
}
+ catch (Exception e) {
+ throw new JbpmException("couldn't add mapping for element '" + elementTagName
+ + "': constructor(" + Element.class.getName() + ","
+ + ObjectFactoryParser.class.getName() + ") was missing for class '"
+ + objectInfoClass.getName() + "'", e);
+ }
}
-
+
public static ObjectFactoryImpl parseXmlString(String xml) {
Element rootElement = XmlUtil.parseXmlText(xml).getDocumentElement();
return createObjectFactory(rootElement);
@@ -84,16 +93,15 @@
}
public static ObjectFactoryImpl parseResource(String resource) {
- Element rootElement = XmlUtil.parseXmlResource(resource, true).getDocumentElement();
+ Element rootElement = XmlUtil.parseXmlResource(resource, false).getDocumentElement();
return createObjectFactory(rootElement);
}
-
+
public static ObjectFactoryImpl createObjectFactory(Element rootElement) {
ObjectFactoryParser objectFactoryParser = new ObjectFactoryParser();
List objectInfos = new ArrayList();
- List topLevelElements = XmlUtil.elements(rootElement);
- for (int i = 0; i<topLevelElements.size(); i++) {
- Element topLevelElement = (Element) topLevelElements.get(i);
+ for (Iterator iter = XmlUtil.elementIterator(rootElement); iter.hasNext();) {
+ Element topLevelElement = (Element) iter.next();
ObjectInfo objectInfo = objectFactoryParser.parse(topLevelElement);
objectInfos.add(objectInfo);
}
@@ -101,7 +109,7 @@
}
public void parseElementsFromResource(String resource, ObjectFactoryImpl objectFactoryImpl) {
- Element rootElement = XmlUtil.parseXmlResource(resource, true).getDocumentElement();
+ Element rootElement = XmlUtil.parseXmlResource(resource, false).getDocumentElement();
parseElements(rootElement, objectFactoryImpl);
}
@@ -111,16 +119,15 @@
}
public void parseElements(Element element, ObjectFactoryImpl objectFactoryImpl) {
- List objectInfoElements = XmlUtil.elements(element);
- for (int i = 0; i<objectInfoElements.size(); i++) {
- Element objectInfoElement = (Element) objectInfoElements.get(i);
+ for (Iterator iter = XmlUtil.elementIterator(element); iter.hasNext();) {
+ Element objectInfoElement = (Element) iter.next();
ObjectInfo objectInfo = parse(objectInfoElement);
objectFactoryImpl.addObjectInfo(objectInfo);
}
}
- Map mappings = null;
- Map namedObjectInfos = null;
+ private Map mappings;
+ private Map namedObjectInfos;
public ObjectFactoryParser() {
this(getDefaultMappings());
@@ -132,26 +139,30 @@
}
public ObjectInfo parse(Element element) {
- ObjectInfo objectInfo = null;
- String elementTagName = element.getTagName().toLowerCase();
- Constructor constructor = (Constructor) mappings.get(elementTagName);
- if (constructor==null) {
- throw new JbpmException("no ObjectInfo class specified for element '"+elementTagName+"'");
+ ObjectInfo objectInfo;
+ String tagName = element.getTagName().toLowerCase();
+ Constructor constructor = (Constructor) mappings.get(tagName);
+ if (constructor == null) {
+ throw new JbpmException("no ObjectInfo class specified for element: " + tagName);
}
try {
- objectInfo = (ObjectInfo) constructor.newInstance(new Object[]{element,this});
- } catch (Exception e) {
- throw new JbpmException("couldn't parse '"+elementTagName+"' into a '"+constructor.getDeclaringClass().getName()+"': "+XmlUtil.toString(element), e);
+ objectInfo = (ObjectInfo) constructor.newInstance(new Object[] {
+ element, this
+ });
}
+ catch (Exception e) {
+ throw new JbpmException("couldn't parse '" + tagName + "' into a '"
+ + constructor.getDeclaringClass().getName() + "': " + XmlUtil.toString(element), e);
+ }
return objectInfo;
}
public void addNamedObjectInfo(String name, ObjectInfo objectInfo) {
namedObjectInfos.put(name, objectInfo);
}
-
+
public void addMapping(String elementName, Class objectInfoClass) {
- if (mappings==getDefaultMappings()) {
+ if (mappings == getDefaultMappings()) {
mappings = new HashMap(getDefaultMappings());
}
addMapping(mappings, elementName, objectInfoClass);
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/def/Access.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/def/Access.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/def/Access.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -27,19 +27,14 @@
private static final long serialVersionUID = 1L;
- String access = "read,write";
+ private String access = "read,write";
public Access() {
}
public Access(String access) {
if (access != null) {
- if ("".equals(access)) {
- this.access = " ";
- }
- else {
- this.access = access;
- }
+ this.access = access.toLowerCase();
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/def/VariableAccess.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/def/VariableAccess.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/def/VariableAccess.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -24,21 +24,18 @@
import java.io.Serializable;
/**
- * specifies access to a variable.
- * Variable access is used in 3 situations:
- * 1) process-state
- * 2) script
- * 3) task controllers
+ * specifies access to a variable. Variable access is used in 3 situations: 1) process-state 2)
+ * script 3) task controllers
*/
public class VariableAccess implements Serializable {
private static final long serialVersionUID = 1L;
-
- long id = 0;
- protected String variableName = null;
- protected Access access = null;
- protected String mappedName = null;
+ long id;
+ protected String variableName;
+ protected Access access;
+ protected String mappedName;
+
// constructors /////////////////////////////////////////////////////////////
public VariableAccess() {
@@ -46,7 +43,6 @@
public VariableAccess(String variableName, String access, String mappedName) {
this.variableName = variableName;
- if (access!=null) access = access.toLowerCase();
this.access = new Access(access);
this.mappedName = mappedName;
}
@@ -54,14 +50,11 @@
// getters and setters //////////////////////////////////////////////////////
/**
- * the mapped name. The mappedName defaults to the variableName in case
- * no mapped name is specified.
+ * the mapped name. The mappedName defaults to the variableName in case no mapped name is
+ * specified.
*/
public String getMappedName() {
- if (mappedName==null) {
- return variableName;
- }
- return mappedName;
+ return mappedName != null ? mappedName : variableName;
}
/**
@@ -70,10 +63,11 @@
public Access getAccess() {
return access;
}
+
public String getVariableName() {
return variableName;
}
-
+
public boolean isReadable() {
return access.isReadable();
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/ContextInstance.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/ContextInstance.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/ContextInstance.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -21,6 +21,7 @@
*/
package org.jbpm.context.exe;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -40,17 +41,18 @@
* </pre>
*
* More information on context and process variableInstances can be found in <a
- * href="../../../../../userguide/en/html/reference.html#context">the userguide, section context</a>
+ * href="../../../../../userguide/en/html/reference.html#context">the userguide, section
+ * context</a>
*/
public class ContextInstance extends ModuleInstance {
private static final long serialVersionUID = 1L;
// maps Tokens to TokenVariableMaps
- protected Map tokenVariableMaps = null;
+ protected Map tokenVariableMaps;
// maps variable names (String) to values (Object)
- protected transient Map transientVariables = null;
- protected transient List updatedVariableContainers = null;
+ protected transient Map transientVariables;
+ protected transient List updatedVariableContainers;
public ContextInstance() {
}
@@ -113,8 +115,8 @@
}
/**
- * The method setVariables is the same as the {@link #addVariables(Map, Token)}, but it was added
- * for more consistency.
+ * The method setVariables is the same as the {@link #addVariables(Map, Token)}, but it was
+ * added for more consistency.
*/
public void setVariables(Map variables) {
setVariables(variables, getRootToken());
@@ -129,8 +131,8 @@
}
/**
- * adds all the variableInstances to the scope of the given token. The method setVariables is the
- * same as the {@link #addVariables(Map, Token)}, but it was added for more consistency.
+ * adds all the variableInstances to the scope of the given token. The method setVariables is
+ * the same as the {@link #addVariables(Map, Token)}, but it was added for more consistency.
*/
public void setVariables(Map variables, Token token) {
// [JBPM-1778] Empty map variables on process creation is set as null
@@ -152,8 +154,8 @@
}
/**
- * retrieves a variable in the scope of the token. If the given token does not have a variable for
- * the given name, the variable is searched for up the token hierarchy.
+ * retrieves a variable in the scope of the token. If the given token does not have a variable
+ * for the given name, the variable is searched for up the token hierarchy.
*/
public Object getVariable(String name, Token token) {
Object variable = null;
@@ -174,8 +176,8 @@
}
/**
- * retrieves a variable which is local to the token. this method was added for naming consistency.
- * it is the same as {@link #getLocalVariable(String, Token)}.
+ * retrieves a variable which is local to the token. this method was added for naming
+ * consistency. it is the same as {@link #getLocalVariable(String, Token)}.
*/
public Object getVariableLocally(String name, Token token) {
Object variable = null;
@@ -232,8 +234,8 @@
}
/**
- * deletes a variable from the given token. For safety reasons, this method does not propagate the
- * deletion to parent tokens in case the given token does not contain the variable.
+ * deletes a variable from the given token. For safety reasons, this method does not propagate
+ * the deletion to parent tokens in case the given token does not contain the variable.
*/
public void deleteVariable(String name, Token token) {
TokenVariableMap tokenVariableMap = getTokenVariableMap(token);
@@ -277,7 +279,8 @@
/**
* retrieves all the transient variableInstances map. note that no deep copy is performed,
- * changing the map leads to changes in the transient variableInstances of this context instance.
+ * changing the map leads to changes in the transient variableInstances of this context
+ * instance.
*/
public Map getTransientVariables() {
return transientVariables;
@@ -298,13 +301,13 @@
transientVariables.remove(name);
}
- Token getRootToken() {
+ private Token getRootToken() {
return processInstance.getRootToken();
}
/**
- * searches for the first token-variable-map for the given token and creates it on the root token
- * if it doesn't exist.
+ * searches for the first token-variable-map for the given token and creates it on the root
+ * token if it doesn't exist.
*/
public TokenVariableMap getOrCreateTokenVariableMap(Token token) {
if (token == null) {
@@ -328,7 +331,7 @@
return tokenVariableMap;
}
- TokenVariableMap createTokenVariableMap(Token token) {
+ private TokenVariableMap createTokenVariableMap(Token token) {
if (tokenVariableMaps == null) {
tokenVariableMaps = new HashMap();
}
@@ -368,4 +371,13 @@
public Map getTokenVariableMaps() {
return tokenVariableMaps;
}
+
+ public List getUpdatedVariableContainers() {
+ return updatedVariableContainers;
+ }
+
+ void addUpdatedVariableContainer(VariableContainer variableContainer) {
+ if (updatedVariableContainers == null) updatedVariableContainers = new ArrayList();
+ updatedVariableContainers.add(variableContainer);
+ }
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/VariableContainer.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/VariableContainer.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/VariableContainer.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -1,7 +1,6 @@
package org.jbpm.context.exe;
import java.io.Serializable;
-import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
@@ -19,9 +18,10 @@
public abstract class VariableContainer implements Serializable {
- private static final long serialVersionUID = 520258491083406913L;
protected Map variableInstances;
+ private static final long serialVersionUID = 520258491083406913L;
+
protected abstract VariableContainer getParentVariableContainer();
public abstract Token getToken();
@@ -55,45 +55,34 @@
}
public boolean hasVariable(String name) {
- boolean hasVariable = false;
-
// if the variable is present in the variable instances
- if (hasVariableLocally(name)) {
- hasVariable = true;
- }
- else {
- VariableContainer parent = getParentVariableContainer();
- if (parent != null) {
- hasVariable = parent.hasVariable(name);
- }
- }
+ if (hasVariableLocally(name)) return true;
- return hasVariable;
+ // search in parent variable container
+ VariableContainer parent = getParentVariableContainer();
+ if (parent != null) return parent.hasVariable(name);
+
+ return false;
}
public void deleteVariable(String name) {
- if (name == null) {
- throw new JbpmException("name is null");
- }
- if (hasVariableLocally(name)) {
- deleteVariableLocally(name);
- }
+ if (name == null) throw new JbpmException("variable name is null");
+ if (hasVariableLocally(name)) deleteVariableLocally(name);
}
/**
* adds all the given variables to this variable container. The method
- * {@link #setVariables(Map)} is the same as this method, but it was added for
- * naming consistency.
+ * {@link #setVariables(Map)} is the same as this method, but it was added for naming
+ * consistency.
*/
public void addVariables(Map variables) {
setVariables(variables);
}
/**
- * adds all the given variables to this variable container. It doesn't remove
- * any existing variables unless they are overwritten by the given variables.
- * This method is the same as {@link #addVariables(Map)} and this method was
- * added for naming consistency.
+ * adds all the given variables to this variable container. It doesn't remove any existing
+ * variables unless they are overwritten by the given variables. This method is the same as
+ * {@link #addVariables(Map)} and this method was added for naming consistency.
*/
public void setVariables(Map variables) {
if (variables != null) {
@@ -161,18 +150,24 @@
// and it does not support the new value
if (variableInstance != null && !variableInstance.supports(value)) {
// delete the old variable instance
- log.debug(variableInstance.getToken() + " unsets '" + name + "' due to type change");
+ if (log.isDebugEnabled()) {
+ log.debug(variableInstance.getToken() + " unsets '" + name + "' due to type change");
+ }
deleteVariableInstance(name);
variableInstance = null;
}
if (variableInstance != null) {
- log.debug(variableInstance.getToken() + " sets '" + name + "' to " + value);
+ if (log.isDebugEnabled()) {
+ log.debug(variableInstance.getToken() + " sets '" + name + "' to " + value);
+ }
variableInstance.setValue(value);
}
else {
Token token = getToken();
- log.debug(token + " initializes '" + name + "' to " + value);
+ if (log.isDebugEnabled()) {
+ log.debug(token + " initializes '" + name + "' to " + value);
+ }
addVariableInstance(VariableInstance.create(token, name, value));
}
}
@@ -190,10 +185,10 @@
public void addVariableInstance(VariableInstance variableInstance) {
if (variableInstances == null) variableInstances = new HashMap();
variableInstances.put(variableInstance.getName(), variableInstance);
- // only additions are registered in the updated variable containers
- // because it is only used in the save operation to check whether there
- // are unpersistable variables added
- addUpdatedVariableContainer();
+ // only register additions in the updated variable containers
+ // because the registry is only used to check for non-persistable variables
+ ContextInstance contextInstance = getContextInstance();
+ if (contextInstance != null) contextInstance.addUpdatedVariableContainer(this);
}
public void deleteVariableInstance(String name) {
@@ -201,7 +196,7 @@
VariableInstance variableInstance = (VariableInstance) variableInstances.remove(name);
if (variableInstance != null) {
variableInstance.removeReferences();
- // is engine running in memory only or with logging enabled?
+ // is engine running in memory only or with logging enabled?
JbpmContext jbpmContext = JbpmContext.getCurrentJbpmContext();
if (jbpmContext == null || jbpmContext.getServices().getLoggingService() != null) {
// record variable deletion
@@ -217,28 +212,15 @@
}
}
- void addUpdatedVariableContainer() {
- ContextInstance contextInstance = getContextInstance();
- if (contextInstance != null) {
- if (contextInstance.updatedVariableContainers == null) {
- contextInstance.updatedVariableContainers = new ArrayList();
- }
- contextInstance.updatedVariableContainers.add(this);
- }
- }
-
public ContextInstance getContextInstance() {
Token token = getToken();
- if (token != null) {
- ProcessInstance processInstance = token.getProcessInstance();
- if (processInstance != null) return processInstance.getContextInstance();
- }
- return null;
+ return token != null ? token.getProcessInstance().getContextInstance() : null;
}
+ /** @deprecated call {@link ContextInstance#getUpdatedVariableContainers()} instead */
public static Collection getUpdatedVariableContainers(ProcessInstance processInstance) {
return processInstance.getContextInstance().updatedVariableContainers;
}
- private static Log log = LogFactory.getLog(VariableContainer.class);
+ private static final Log log = LogFactory.getLog(VariableContainer.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/VariableInstance.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/VariableInstance.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/VariableInstance.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -31,10 +31,11 @@
import org.jbpm.context.log.VariableCreateLog;
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.graph.exe.Token;
+import org.jbpm.util.ClassUtil;
/**
- * is a jbpm-internal class that serves as a base class for classes that store
- * variable values in the database.
+ * is a jbpm-internal class that serves as a base class for classes that store variable values
+ * in the database.
*/
public abstract class VariableInstance implements Serializable {
@@ -56,50 +57,32 @@
}
public static VariableInstance create(Token token, String name, Object value) {
+ VariableInstance variableInstance = value != null ? createVariableInstance(value)
+ : new NullInstance();
- VariableInstance variableInstance = null;
- if (value == null) {
- variableInstance = new NullInstance();
- }
- else {
- variableInstance = createVariableInstance(value);
- }
-
- variableInstance.token = token;
variableInstance.name = name;
- variableInstance.processInstance =
- (token != null ? token.getProcessInstance() : null);
if (token != null) {
+ variableInstance.token = token;
+ variableInstance.processInstance = token.getProcessInstance();
token.addLog(new VariableCreateLog(variableInstance));
}
+
variableInstance.setValue(value);
return variableInstance;
}
public static VariableInstance createVariableInstance(Object value) {
- VariableInstance variableInstance = null;
-
- Iterator iter = JbpmType.getJbpmTypes().iterator();
- while ((iter.hasNext()) && (variableInstance == null)) {
+ for (Iterator iter = JbpmType.getJbpmTypes().iterator(); iter.hasNext();) {
JbpmType jbpmType = (JbpmType) iter.next();
-
- if (jbpmType.matches(value)) {
- variableInstance = jbpmType.newVariableInstance();
- }
+ if (jbpmType.matches(value)) return jbpmType.newVariableInstance();
}
-
- if (variableInstance == null) {
- variableInstance = new UnpersistableInstance();
- }
-
- return variableInstance;
+ return new UnpersistableInstance();
}
// abstract methods /////////////////////////////////////////////////////////
/**
- * is true if this variable-instance supports the given value, false
- * otherwise.
+ * is true if this variable-instance supports the given value, false otherwise.
*/
public abstract boolean isStorable(Object value);
@@ -128,34 +111,26 @@
if (converter != null) {
if (!converter.supports(value)) {
- throw new JbpmException("the converter '"
- + converter.getClass().getName() + "' in variable instance '"
- + this.getClass().getName() + "' does not support values of type '"
- + value.getClass().getName()
- + "'. to change the type of a variable, you have to delete it first");
+ throw new JbpmException("converter '" + converter.getClass().getName()
+ + " does not support values of type " + value.getClass().getName());
}
value = converter.convert(value);
}
- if ((value != null) && (!this.isStorable(value))) {
- throw new JbpmException("variable instance '" + this.getClass().getName()
- + "' does not support values of type '" + value.getClass().getName()
- + "'. to change the type of a variable, you have to delete it first");
+ if (value != null && !isStorable(value)) {
+ throw new JbpmException(this + " cannot store values of type "
+ + value.getClass().getName());
}
setObject(value);
}
public Object getValue() {
- if (isValueCached) {
- return valueCache;
- }
+ if (isValueCached) return valueCache;
+
Object value = getObject();
- if ((value != null) && (converter != null)) {
- if (converter instanceof SerializableToByteArrayConverter
- && processInstance != null) {
- SerializableToByteArrayConverter s2bConverter =
- (SerializableToByteArrayConverter) converter;
- value =
- s2bConverter.revert(value, processInstance.getProcessDefinition());
+ if (value != null && converter != null) {
+ if (converter instanceof SerializableToByteArrayConverter && processInstance != null) {
+ SerializableToByteArrayConverter s2bConverter = (SerializableToByteArrayConverter) converter;
+ value = s2bConverter.revert(value, processInstance.getProcessDefinition());
}
else {
value = converter.revert(value);
@@ -175,7 +150,7 @@
// utility methods /////////////////////////////////////////////////////////
public String toString() {
- return "${" + name + "}";
+ return ClassUtil.getSimpleName(getClass()) + '(' + name + ')';
}
// getters and setters //////////////////////////////////////////////////////
@@ -195,6 +170,4 @@
public void setTokenVariableMap(TokenVariableMap tokenVariableMap) {
this.tokenVariableMap = tokenVariableMap;
}
-
- // private static Log log = LogFactory.getLog(VariableInstance.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/matcher/HibernateLongIdMatcher.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/matcher/HibernateLongIdMatcher.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/matcher/HibernateLongIdMatcher.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -21,12 +21,11 @@
*/
package org.jbpm.context.exe.matcher;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.type.LongType;
+
import org.jbpm.JbpmContext;
import org.jbpm.context.exe.JbpmTypeMatcher;
@@ -35,28 +34,20 @@
private static final long serialVersionUID = 1L;
public boolean matches(Object value) {
- boolean matches = false;
JbpmContext jbpmContext = JbpmContext.getCurrentJbpmContext();
- if (jbpmContext!=null) {
-
+ if (jbpmContext != null) {
Class valueClass = value.getClass();
if (value instanceof HibernateProxy) {
valueClass = valueClass.getSuperclass();
}
-
SessionFactory sessionFactory = jbpmContext.getSessionFactory();
- if (sessionFactory!=null) {
+ if (sessionFactory != null) {
ClassMetadata classMetadata = sessionFactory.getClassMetadata(valueClass);
- matches = ( (classMetadata!=null)
- && (classMetadata.getIdentifierType().getClass()==LongType.class)
- );
+ return classMetadata != null
+ && classMetadata.getIdentifierType().getClass() == LongType.class;
}
- } else {
- log.debug("no current context so valueClass cannot be stored as a long-id-ref to a hibernate object");
- matches = false;
}
- return matches;
+ return false;
}
-
- private static Log log = LogFactory.getLog(HibernateLongIdMatcher.class);
+
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/matcher/HibernateStringIdMatcher.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/matcher/HibernateStringIdMatcher.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/matcher/HibernateStringIdMatcher.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -21,12 +21,11 @@
*/
package org.jbpm.context.exe.matcher;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.type.StringType;
+
import org.jbpm.JbpmContext;
import org.jbpm.context.exe.JbpmTypeMatcher;
@@ -35,28 +34,20 @@
private static final long serialVersionUID = 1L;
public boolean matches(Object value) {
- boolean matches = false;
JbpmContext jbpmContext = JbpmContext.getCurrentJbpmContext();
- if (jbpmContext!=null) {
-
+ if (jbpmContext != null) {
Class valueClass = value.getClass();
if (value instanceof HibernateProxy) {
valueClass = valueClass.getSuperclass();
}
-
SessionFactory sessionFactory = jbpmContext.getSessionFactory();
- if (sessionFactory!=null) {
+ if (sessionFactory != null) {
ClassMetadata classMetadata = sessionFactory.getClassMetadata(valueClass);
- matches = ( (classMetadata!=null)
- && (classMetadata.getIdentifierType().getClass()==StringType.class)
- );
+ return classMetadata != null
+ && classMetadata.getIdentifierType().getClass() == StringType.class;
}
- } else {
- log.debug("no current context so valueClass cannot be stored as a string-id-ref to a hibernate object");
- matches = false;
}
- return matches;
+ return false;
}
- private static Log log = LogFactory.getLog(HibernateStringIdMatcher.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/variableinstance/JcrNodeInstance.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/variableinstance/JcrNodeInstance.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/variableinstance/JcrNodeInstance.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -73,14 +73,13 @@
}
/**
- * find the service that matches the stored repository and workspace. The
- * search is done as follows:
+ * find the service that matches the stored repository and workspace. The search is done as
+ * follows:
* <ol>
* <li>a service whose name is <code>jcr</code></li>
* <li>a service whose name equals the repository name</li>
- * <li>a service whose name starts with the repository name and ends with the
- * workspace name matches and takes preference over a service with the
- * repository name</li>
+ * <li>a service whose name starts with the repository name and ends with the workspace name
+ * matches and takes preference over a service with the repository name</li>
* </ol>
*
* @throws JbpmException if no matching service is found
@@ -127,7 +126,7 @@
else {
try {
// node repo and workspace got to correspond with a jbpm service name,
- // as described in findService, unless a global "jcr" service
+ // as described in findService, unless a global "jcr" service
// THE NODE REPOSITORY AND WORKSPACE NAME GOT TO CORRESPOND WITH A JBPM
// SERVICE NAME
Session session = node.getSession();
@@ -135,8 +134,10 @@
workspace = session.getWorkspace().getName();
path = node.getPath();
- log.debug("stored jcr node, repository '" + repository + "', workspace '" + workspace
- + "' and path'" + path + '\'');
+ if (log.isDebugEnabled()) {
+ log.debug("stored jcr node, repository '" + repository + "', workspace '" + workspace
+ + "' and path'" + path + '\'');
+ }
}
catch (RepositoryException e) {
throw new JbpmException("problem storing JCR node '" + node
@@ -145,5 +146,5 @@
}
}
- private static Log log = LogFactory.getLog(JcrNodeInstance.class);
+ private static final Log log = LogFactory.getLog(JcrNodeInstance.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/variableinstance/NullInstance.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/variableinstance/NullInstance.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/exe/variableinstance/NullInstance.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -7,7 +7,7 @@
private static final long serialVersionUID = 1L;
public boolean isStorable(Object value) {
- return (value==null);
+ return value == null;
}
protected Object getObject() {
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/log/VariableCreateLog.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/log/VariableCreateLog.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/log/VariableCreateLog.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -21,7 +21,7 @@
*/
package org.jbpm.context.log;
-import org.jbpm.context.exe.*;
+import org.jbpm.context.exe.VariableInstance;
public class VariableCreateLog extends VariableLog {
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/log/VariableLog.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/log/VariableLog.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/context/log/VariableLog.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -21,14 +21,14 @@
*/
package org.jbpm.context.log;
-import org.jbpm.context.exe.*;
-import org.jbpm.logging.log.*;
+import org.jbpm.context.exe.VariableInstance;
+import org.jbpm.logging.log.ProcessLog;
public abstract class VariableLog extends ProcessLog {
private static final long serialVersionUID = 1L;
- protected VariableInstance variableInstance = null;
+ protected VariableInstance variableInstance;
public VariableLog() {
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/AbstractDbTestCase.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/AbstractDbTestCase.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/AbstractDbTestCase.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -101,8 +101,7 @@
}
private void ensureCleanDatabase() {
- DbPersistenceServiceFactory persistenceServiceFactory =
- (DbPersistenceServiceFactory) getJbpmConfiguration().getServiceFactory("persistence");
+ DbPersistenceServiceFactory persistenceServiceFactory = (DbPersistenceServiceFactory) getJbpmConfiguration().getServiceFactory("persistence");
if (persistenceServiceFactory == null) return;
boolean hasLeftOvers = false;
@@ -114,8 +113,8 @@
Long count = (Long) entry.getValue();
if (count.intValue() != 0) {
hasLeftOvers = true;
- System.err.println("FIXME: " + getClass().getName() + "." + getName()
- + " left " + count + " records in " + entry.getKey());
+ System.err.println("FIXME: " + getClass().getName() + "." + getName() + " left "
+ + count + " records in " + entry.getKey());
}
}
@@ -125,10 +124,8 @@
}
protected String getHibernateDialect() {
- DbPersistenceServiceFactory persistenceServiceFactory =
- (DbPersistenceServiceFactory) jbpmContext.getServiceFactory(Services.SERVICENAME_PERSISTENCE);
- return persistenceServiceFactory.getConfiguration()
- .getProperty(Environment.DIALECT);
+ DbPersistenceServiceFactory persistenceServiceFactory = (DbPersistenceServiceFactory) jbpmContext.getServiceFactory(Services.SERVICENAME_PERSISTENCE);
+ return persistenceServiceFactory.getConfiguration().getProperty(Environment.DIALECT);
}
protected void beginSessionTransaction() {
@@ -155,8 +152,7 @@
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) {
@@ -229,7 +225,7 @@
if (currentCount < previousCount) {
waitPeriod = currentCount * (currentTime - previousTime)
- / (previousCount - currentCount);
+ / (previousCount - currentCount);
if (waitPeriod < 500) waitPeriod = 500;
}
else {
@@ -244,8 +240,9 @@
if (waitPeriod > remainingTime) waitPeriod = remainingTime;
}
- log.debug("waiting " + waitPeriod + " ms for " + currentCount
- + " jobs to execute");
+ if (log.isDebugEnabled()) {
+ log.debug("waiting " + waitPeriod + " ms for " + currentCount + " jobs to execute");
+ }
try {
Thread.sleep(waitPeriod);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/JbpmSessionFactory.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/JbpmSessionFactory.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/JbpmSessionFactory.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -46,73 +46,77 @@
import org.jbpm.util.ClassLoaderUtil;
/**
- * creates JbpmSessions.
- * Obtain a JbpmSessionFactory with
+ * creates JbpmSessions. Obtain a JbpmSessionFactory with
+ *
* <pre>
* static JbpmSessionFactory jbpmSessionFactory = JbpmSessionFactory.buildJbpmSessionFactory();
* </pre>
- * and store it somewhere static. It takes quite some time to create a JbpmSessionFactory,
- * but you only have to do it once. After that, creating JbpmSession's is really fast.
*
+ * and store it somewhere static. It takes quite some time to create a JbpmSessionFactory, but
+ * you only have to do it once. After that, creating JbpmSession's is really fast.
+ *
* @deprecated use {@link org.jbpm.JbpmContext} and {@link org.jbpm.JbpmConfiguration} instead.
*/
public class JbpmSessionFactory implements Serializable {
-
+
private static final long serialVersionUID = 1L;
- static String jndiName = getJndiName();
+ private static String jndiName = getJndiName();
+
private static String getJndiName() {
- String jndiName = null;
if (JbpmConfiguration.Configs.hasObject("jbpm.session.factory.jndi.name")) {
- jndiName = JbpmConfiguration.Configs.getString("jbpm.session.factory.jndi.name");
+ return JbpmConfiguration.Configs.getString("jbpm.session.factory.jndi.name");
}
- return jndiName;
+ return null;
}
- Configuration configuration = null;
- SessionFactory sessionFactory = null;
- Collection hibernatableLongIdClasses = null;
- Collection hibernatableStringIdClasses = null;
- JbpmSchema jbpmSchema = null;
-
- static JbpmSessionFactory instance = null;
+ private Configuration configuration;
+ private SessionFactory sessionFactory;
+ private Collection hibernatableLongIdClasses;
+ private Collection hibernatableStringIdClasses;
+ private JbpmSchema jbpmSchema;
+ private static JbpmSessionFactory instance;
+
/**
* a singleton is kept in JbpmSessionFactory as a convenient central location.
*/
public static JbpmSessionFactory getInstance() {
- if (instance==null) {
-
+ if (instance == null) {
// if there is a JNDI name configured
- if (jndiName!=null) {
+ if (jndiName != null) {
try {
// fetch the JbpmSessionFactory from JNDI
- log.debug("fetching JbpmSessionFactory from '"+jndiName+"'");
+ if (log.isDebugEnabled()) {
+ log.debug("fetching JbpmSessionFactory from " + jndiName);
+ }
InitialContext initialContext = new InitialContext();
Object o = initialContext.lookup(jndiName);
instance = (JbpmSessionFactory) PortableRemoteObject.narrow(o, JbpmSessionFactory.class);
- } catch (Exception e) {
- throw new JbpmException("couldn't fetch JbpmSessionFactory from jndi '"+jndiName+"'");
}
-
- } else { // else there is no JNDI name configured
- // create a new default instance.
- log.debug("building singleton JbpmSessionFactory");
+ catch (Exception e) {
+ throw new JbpmException("couldn't fetch JbpmSessionFactory from " + jndiName);
+ }
+ }
+ // else there is no JNDI name configured
+ else {
+ // create a new default instance
+ if (log.isDebugEnabled()) log.debug("building singleton JbpmSessionFactory");
instance = buildJbpmSessionFactory();
}
}
return instance;
}
-
+
public JbpmSessionFactory(Configuration configuration) {
- this( configuration, buildSessionFactory(configuration) );
+ this(configuration, buildSessionFactory(configuration));
}
public JbpmSessionFactory(Configuration configuration, SessionFactory sessionFactory) {
this.configuration = configuration;
this.sessionFactory = sessionFactory;
}
-
+
public static JbpmSessionFactory buildJbpmSessionFactory() {
return buildJbpmSessionFactory(getConfigResource());
}
@@ -120,7 +124,7 @@
public static JbpmSessionFactory buildJbpmSessionFactory(String configResource) {
return buildJbpmSessionFactory(createConfiguration(configResource));
}
-
+
public static JbpmSessionFactory buildJbpmSessionFactory(Configuration configuration) {
return new JbpmSessionFactory(configuration);
}
@@ -134,76 +138,74 @@
}
public static Configuration createConfiguration(String configResource) {
- Configuration configuration = null;
// create the hibernate configuration
- configuration = new Configuration();
- if (configResource!=null) {
- log.debug("using '"+configResource+"' as hibernate configuration for jbpm");
+ Configuration configuration = new Configuration();
+ if (configResource != null) {
configuration.configure(configResource);
- } else {
- log.debug("using the default hibernate configuration file: hibernate.cfg.xml");
+ }
+ else {
configuration.configure();
}
-
- // check if the properties in the hibernate.cfg.xml need to be overwritten by a separate properties file.
+
+ // check if the properties in the hibernate.cfg.xml need to be overwritten by a separate
+ // properties file.
if (JbpmConfiguration.Configs.hasObject("resource.hibernate.properties")) {
- String hibernatePropertiesResource = JbpmConfiguration.Configs.getString("resource.hibernate.properties");
- Properties hibernateProperties = new Properties();
+ String propertiesResource = JbpmConfiguration.Configs.getString("resource.hibernate.properties");
+ if (log.isDebugEnabled()) {
+ log.debug("loading hibernate properties from resource: " + propertiesResource);
+ }
+ Properties properties = new Properties();
try {
- hibernateProperties.load( ClassLoaderUtil.getStream(hibernatePropertiesResource) );
- } catch (IOException e) {
- throw new JbpmException("couldn't load the hibernate properties from resource '"+hibernatePropertiesResource+"'", e);
+ properties.load(ClassLoaderUtil.getStream(propertiesResource));
}
- log.debug("overriding hibernate properties with "+ hibernateProperties);
- configuration.setProperties(hibernateProperties);
+ catch (IOException e) {
+ throw new JbpmException("could not load hibernate properties from resource: "
+ + propertiesResource, e);
+ }
+ // add the properties to the configuration, replacing any existing values
+ configuration.addProperties(properties);
}
-
+
return configuration;
}
public static SessionFactory buildSessionFactory(Configuration configuration) {
- SessionFactory sessionFactory = null;
- // create the hibernate session factory
- log.debug("building hibernate session factory");
- sessionFactory = configuration.buildSessionFactory();
- return sessionFactory;
+ return configuration.buildSessionFactory();
}
/**
- * obtains a jdbc connection as specified in the hibernate configurations and
- * creates a JbpmSession with it.
+ * obtains a jdbc connection as specified in the hibernate configurations and creates a
+ * JbpmSession with it.
*/
public JbpmSession openJbpmSession() {
- return openJbpmSession((Connection)null);
+ return openJbpmSession((Connection) null);
}
/**
- * creates a JbpmSession around the given connection. Note that you are
- * responsible for closing the connection so closing the JbpmSession will
- * not close the jdbc connection.
+ * creates a JbpmSession around the given connection. Note that you are responsible for
+ * closing the connection so closing the JbpmSession will not close the jdbc connection.
*/
public JbpmSession openJbpmSession(Connection jdbcConnection) {
- JbpmSession dbSession = null;
-
+ JbpmSession dbSession;
try {
- Session session = null;
-
- if ( jdbcConnection == null ) {
- // use the hibernate properties in the nwsp.properties file to
+ Session session;
+ if (jdbcConnection == null) {
+ // use the hibernate properties in the nwsp.properties file to
// create a jdbc connection for the created hibernate session.
session = getSessionFactory().openSession();
- } else {
- // use the client provided jdbc connection in
+ }
+ else {
+ // use the client provided jdbc connection in
// the created hibernate session.
session = getSessionFactory().openSession(jdbcConnection);
}
-
- dbSession = new JbpmSession( this, session );
-
- } catch (HibernateException e) {
- log.error( e );
- throw new JbpmException( "couldn't create a hibernate persistence session", e );
+
+ dbSession = new JbpmSession(this, session);
}
+ catch (HibernateException e) {
+ log.error(e);
+ throw new JbpmException("couldn't create a hibernate persistence session", e);
+ }
return dbSession;
}
@@ -212,26 +214,24 @@
}
public JbpmSession openJbpmSessionAndBeginTransaction() {
- JbpmSession dbSession = openJbpmSession((Connection)null);
+ JbpmSession dbSession = openJbpmSession((Connection) null);
dbSession.beginTransaction();
return dbSession;
}
-
+
public SessionFactory getSessionFactory() {
return sessionFactory;
}
-
+
public Configuration getConfiguration() {
return configuration;
}
-
+
/**
* checks if the given class is persistable with hibernate and has an id of type long.
*/
public boolean isHibernatableWithLongId(Class clazz) {
- if (hibernatableLongIdClasses==null) {
- initHibernatableClasses();
- }
+ if (hibernatableLongIdClasses == null) initHibernatableClasses();
return hibernatableLongIdClasses.contains(clazz);
}
@@ -239,30 +239,26 @@
* checks if the given class is persistable with hibernate and has an id of type string.
*/
public boolean isHibernatableWithStringId(Class clazz) {
- if (hibernatableStringIdClasses==null) {
- initHibernatableClasses();
- }
+ if (hibernatableStringIdClasses == null) initHibernatableClasses();
return hibernatableStringIdClasses.contains(clazz);
}
-
+
public JbpmSchema getJbpmSchema() {
- if (jbpmSchema==null) {
- jbpmSchema = new JbpmSchema(configuration);
- }
+ if (jbpmSchema == null) jbpmSchema = new JbpmSchema(configuration);
return jbpmSchema;
}
- void initHibernatableClasses() {
+ private void initHibernatableClasses() {
hibernatableLongIdClasses = new HashSet();
hibernatableStringIdClasses = new HashSet();
- Iterator iter = configuration.getClassMappings();
- while (iter.hasNext()) {
+ for (Iterator iter = configuration.getClassMappings(); iter.hasNext();) {
PersistentClass persistentClass = (PersistentClass) iter.next();
- if (LongType.class==persistentClass.getIdentifier().getType().getClass()) {
- hibernatableLongIdClasses.add( persistentClass.getMappedClass() );
- } else if (StringType.class==persistentClass.getIdentifier().getType().getClass()) {
- hibernatableStringIdClasses.add( persistentClass.getMappedClass() );
+ if (LongType.class == persistentClass.getIdentifier().getType().getClass()) {
+ hibernatableLongIdClasses.add(persistentClass.getMappedClass());
}
+ else if (StringType.class == persistentClass.getIdentifier().getType().getClass()) {
+ hibernatableStringIdClasses.add(persistentClass.getMappedClass());
+ }
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/LoggingSession.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/LoggingSession.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/LoggingSession.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -26,10 +26,9 @@
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.Session;
+
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.graph.exe.Token;
import org.jbpm.logging.log.ProcessLog;
@@ -53,20 +52,20 @@
}
/**
- * returns a map that maps {@link Token}s to {@link List}s. The lists contain the ordered logs for
- * the given token. The lists are retrieved with {@link #findLogsByToken(long)}.
+ * returns a map that maps {@link Token}s to {@link List}s. The lists contain the ordered logs
+ * for the given token. The lists are retrieved with {@link #findLogsByToken(long)}.
*/
public Map findLogsByProcessInstance(long processInstanceId) {
Map tokenLogs = new HashMap();
try {
ProcessInstance processInstance = (ProcessInstance) session.load(ProcessInstance.class, new Long(
- processInstanceId));
+ processInstanceId));
collectTokenLogs(tokenLogs, processInstance.getRootToken());
}
catch (HibernateException e) {
handle(e);
throw new JbpmPersistenceException("couldn't get logs for process instance "
- + processInstanceId, e);
+ + processInstanceId, e);
}
return tokenLogs;
}
@@ -89,8 +88,8 @@
try {
Token token = (Token) session.load(Token.class, new Long(tokenId));
return session.getNamedQuery("LoggingSession.findLogsByToken")
- .setEntity("token", token)
- .list();
+ .setEntity("token", token)
+ .list();
}
catch (HibernateException e) {
handle(e);
@@ -142,10 +141,7 @@
}
private void handle(HibernateException exception) {
- // exception will be rethrown, no need to log here at a verbose level
- log.debug(exception);
+ // exception will be rethrown, no need to log here
if (jbpmSession != null) jbpmSession.handleException();
}
-
- private static final Log log = LogFactory.getLog(LoggingSession.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/compatibility/JbpmSchemaUpdate.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/compatibility/JbpmSchemaUpdate.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/compatibility/JbpmSchemaUpdate.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -26,205 +26,186 @@
import org.jbpm.db.JbpmSchema;
/**
- * This is a modified version of the hibernate tools schema update.
- * The modification is to support saving of the update script to a file.
- *
+ * This is a modified version of the hibernate tools schema update. The modification is to
+ * support saving of the update script to a file.
+ *
* @author Christoph Sturm
* @author Koen Aers
* @deprecated superseded by {@link JbpmSchema}
*/
public class JbpmSchemaUpdate {
- private static final Log log = LogFactory.getLog(JbpmSchemaUpdate.class);
- private ConnectionProvider connectionProvider;
- private Configuration configuration;
- private Dialect dialect;
- private List exceptions;
+ private static final Log log = LogFactory.getLog(JbpmSchemaUpdate.class);
+ private ConnectionProvider connectionProvider;
+ private Configuration configuration;
+ private Dialect dialect;
+ private List exceptions;
- public JbpmSchemaUpdate(Configuration cfg) throws HibernateException {
- this( cfg, cfg.getProperties() );
- }
+ public JbpmSchemaUpdate(Configuration cfg) throws HibernateException {
+ this(cfg, cfg.getProperties());
+ }
- public JbpmSchemaUpdate(Configuration cfg, Properties connectionProperties) throws HibernateException {
- this.configuration = cfg;
- dialect = Dialect.getDialect(connectionProperties);
- Properties props = new Properties();
- props.putAll( dialect.getDefaultProperties() );
- props.putAll(connectionProperties);
- connectionProvider = ConnectionProviderFactory.newConnectionProvider(props);
- exceptions = new ArrayList();
- }
+ public JbpmSchemaUpdate(Configuration cfg, Properties connectionProperties)
+ throws HibernateException {
+ this.configuration = cfg;
+ dialect = Dialect.getDialect(connectionProperties);
+ Properties props = new Properties();
+ props.putAll(dialect.getDefaultProperties());
+ props.putAll(connectionProperties);
+ connectionProvider = ConnectionProviderFactory.newConnectionProvider(props);
+ exceptions = new ArrayList();
+ }
- public JbpmSchemaUpdate(Configuration cfg, Settings settings) throws HibernateException {
- this.configuration = cfg;
- dialect = settings.getDialect();
- connectionProvider = settings.getConnectionProvider();
- exceptions = new ArrayList();
- }
-
- public static void main(String[] args) {
- try {
- Configuration cfg = new Configuration();
+ public JbpmSchemaUpdate(Configuration cfg, Settings settings) throws HibernateException {
+ this.configuration = cfg;
+ dialect = settings.getDialect();
+ connectionProvider = settings.getConnectionProvider();
+ exceptions = new ArrayList();
+ }
- boolean script = true;
- // If true then execute db updates, otherwise just generate and display updates
- boolean doUpdate = true;
- String propFile = null;
-
- File out = null;
+ public static void main(String[] args) {
+ try {
+ Configuration cfg = new Configuration();
- for ( int i=0; i<args.length; i++ ) {
- if( args[i].startsWith("--") ) {
- if( args[i].equals("--quiet") ) {
- script = false;
- }
- else if( args[i].startsWith("--properties=") ) {
- propFile = args[i].substring(13);
- }
- else if ( args[i].startsWith("--config=") ) {
- cfg.configure( args[i].substring(9) );
- }
- else if ( args[i].startsWith("--text") ) {
- doUpdate = false;
- }
- else if ( args[i].startsWith("--naming=") ) {
- cfg.setNamingStrategy(
- (NamingStrategy) ReflectHelper.classForName( args[i].substring(9) ).newInstance()
- );
- }
- else if (args[i].startsWith("--output=")) {
- out = new File(args[i].substring(9));
- }
- }
- else {
- cfg.addFile(args[i]);
- }
+ boolean script = true;
+ // If true then execute db updates, otherwise just generate and display updates
+ boolean doUpdate = true;
+ String propFile = null;
+ File out = null;
- }
-
- if (propFile!=null) {
- Properties props = new Properties();
- props.putAll( cfg.getProperties() );
- props.load( new FileInputStream(propFile) );
- cfg.setProperties(props);
- }
+ for (int i = 0; i < args.length; i++) {
+ if (args[i].startsWith("--")) {
+ if (args[i].equals("--quiet")) {
+ script = false;
+ }
+ else if (args[i].startsWith("--properties=")) {
+ propFile = args[i].substring(13);
+ }
+ else if (args[i].startsWith("--config=")) {
+ cfg.configure(args[i].substring(9));
+ }
+ else if (args[i].startsWith("--text")) {
+ doUpdate = false;
+ }
+ else if (args[i].startsWith("--naming=")) {
+ cfg.setNamingStrategy((NamingStrategy) ReflectHelper.classForName(args[i].substring(9))
+ .newInstance());
+ }
+ else if (args[i].startsWith("--output=")) {
+ out = new File(args[i].substring(9));
+ }
+ }
+ else {
+ cfg.addFile(args[i]);
+ }
+ }
- new JbpmSchemaUpdate(cfg).execute(script, doUpdate, out);
- }
- catch (Exception e) {
- log.error( "Error running schema update", e );
- }
- }
+ if (propFile != null) {
+ Properties props = new Properties();
+ props.putAll(cfg.getProperties());
+ props.load(new FileInputStream(propFile));
+ cfg.setProperties(props);
+ }
- /**
- * Execute the schema updates
- * @param script print all DDL to the console
- */
- public void execute(boolean script, boolean doUpdate, File out) {
+ new JbpmSchemaUpdate(cfg).execute(script, doUpdate, out);
+ }
+ catch (Exception e) {
+ log.error("Error running schema update", e);
+ }
+ }
- log.info("Running hbm2ddl schema update");
+ /**
+ * Execute the schema updates
+ *
+ * @param script print all DDL to the console
+ */
+ public void execute(boolean script, boolean doUpdate, File out) {
+ log.info("Running hbm2ddl schema update");
- Connection connection=null;
- Statement stmt=null;
- boolean autoCommitWasEnabled = true;
- FileWriter writer = null;
-
- if (script && out != null) {
- try {
- log.info("Creating filewriter to file : " + out.getAbsolutePath());
- writer = new FileWriter(out);
- } catch (IOException e) {
- log.debug("IOException while creating filewriter");
- log.debug(e);
- }
- }
+ Connection connection = null;
+ Statement stmt = null;
+ boolean autoCommitWasEnabled = true;
+ FileWriter writer = null;
- exceptions.clear();
+ if (script && out != null) {
+ try {
+ log.info("opening file for writing: " + out.getAbsolutePath());
+ writer = new FileWriter(out);
+ }
+ catch (IOException e) {
+ log.error("could not open file for writing", e);
+ }
+ }
- try {
+ exceptions.clear();
+ try {
+ DatabaseMetadata meta;
+ try {
+ log.info("fetching database metadata");
+ connection = connectionProvider.getConnection();
+ if (!connection.getAutoCommit()) {
+ connection.commit();
+ connection.setAutoCommit(true);
+ autoCommitWasEnabled = false;
+ }
+ meta = new DatabaseMetadata(connection, dialect);
+ stmt = connection.createStatement();
+ }
+ catch (SQLException sqle) {
+ exceptions.add(sqle);
+ log.error("could not get database metadata", sqle);
+ throw sqle;
+ }
- DatabaseMetadata meta;
- try {
- log.info("fetching database metadata");
- connection = connectionProvider.getConnection();
- if ( !connection.getAutoCommit() ) {
- connection.commit();
- connection.setAutoCommit(true);
- autoCommitWasEnabled = false;
- }
- meta = new DatabaseMetadata(connection, dialect);
- stmt = connection.createStatement();
- }
- catch (SQLException sqle) {
- exceptions.add(sqle);
- log.error("could not get database metadata", sqle);
- throw sqle;
- }
+ log.info("updating schema");
+ boolean debug = log.isDebugEnabled();
+ String[] createSQL = configuration.generateSchemaUpdateScript(dialect, meta);
+ for (int j = 0; j < createSQL.length; j++) {
+ final String sql = createSQL[j];
+ try {
+ if (script) {
+ System.out.println(sql);
+ if (writer != null) writer.write(sql + ";\n");
+ }
+ if (doUpdate) {
+ if (debug) log.debug(sql);
+ stmt.executeUpdate(sql);
+ }
+ }
+ catch (SQLException e) {
+ exceptions.add(e);
+ log.error("Unsuccessful: " + sql);
+ log.error(e.getMessage());
+ }
+ }
- log.info("updating schema");
-
- String[] createSQL = configuration.generateSchemaUpdateScript(dialect, meta);
- for (int j = 0; j < createSQL.length; j++) {
-
- final String sql = createSQL[j];
- try {
- if (script) {
- System.out.println(sql);
- if (writer != null) {
- writer.write(sql + ";\n");
- }
- }
- if (doUpdate) {
- log.debug(sql);
- stmt.executeUpdate(sql);
- }
- }
- catch (SQLException e) {
- exceptions.add(e);
- log.error( "Unsuccessful: " + sql );
- log.error( e.getMessage() );
- }
- }
-
- if (writer != null) {
- writer.close();
- }
-
- log.info("schema update complete");
-
- }
- catch (Exception e) {
- exceptions.add(e);
- log.error("could not complete schema update", e);
- }
- finally {
-
- try {
- if (stmt!=null) stmt.close();
- if (!autoCommitWasEnabled) connection.setAutoCommit(false);
- if (connection!=null) connection.close();
- if (connectionProvider!=null) connectionProvider.close();
- }
- catch (Exception e) {
- exceptions.add(e);
- log.error("Error closing connection", e);
- }
-
- }
- }
-
- /**
- * Returns a List of all Exceptions which occured during the export.
- * @return A List containig the Exceptions occured during the export
- */
- public List getExceptions() {
- return exceptions;
+ if (writer != null) writer.close();
+ log.info("schema update complete");
}
-
-}
+ catch (Exception e) {
+ exceptions.add(e);
+ log.error("could not complete schema update", e);
+ }
+ finally {
+ try {
+ if (stmt != null) stmt.close();
+ if (!autoCommitWasEnabled) connection.setAutoCommit(false);
+ if (connection != null) connection.close();
+ if (connectionProvider != null) connectionProvider.close();
+ }
+ catch (Exception e) {
+ exceptions.add(e);
+ log.error("Error closing connection", e);
+ }
+ }
+ }
-
-
-
-
-
+ /**
+ * Returns a List of all Exceptions which occured during the export.
+ *
+ * @return A List containig the Exceptions occured during the export
+ */
+ public List getExceptions() {
+ return exceptions;
+ }
+}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/hibernate/Converters.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/hibernate/Converters.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/hibernate/Converters.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -40,11 +40,11 @@
*/
public class Converters {
- static final int CONVERTERS_BY_CLASS_NAMES = 0;
- static final int CONVERTERS_BY_DATABASE_ID = 1;
- static final int CONVERTERS_IDS = 2;
+ private static final int CONVERTERS_BY_CLASS_NAMES = 0;
+ private static final int CONVERTERS_BY_DATABASE_ID = 1;
+ private static final int CONVERTERS_IDS = 2;
- static Map converterMapsMap = new HashMap();
+ private static Map converterMapsMap = new HashMap();
private Converters() {
// prevent instantiation
@@ -55,9 +55,8 @@
public static Converter getConverterByClassName(String className) {
Converter converter = (Converter) getConvertersByClassNames().get(className);
if (converter == null) {
- throw new JbpmException("converter '" +
- className +
- "' is not declared in jbpm.converter.properties");
+ throw new JbpmException("converter '" + className
+ + "' is not declared in jbpm.converter.properties");
}
return converter;
}
@@ -71,21 +70,21 @@
}
// maps class names to unique converter objects
- static Map getConvertersByClassNames() {
+ private static Map getConvertersByClassNames() {
return getConverterMaps()[CONVERTERS_BY_CLASS_NAMES];
}
// maps converter database-id-strings to unique converter objects
- static Map getConvertersByDatabaseId() {
+ private static Map getConvertersByDatabaseId() {
return getConverterMaps()[CONVERTERS_BY_DATABASE_ID];
}
// maps unique converter objects to their database-id-string
- static Map getConvertersIds() {
+ private static Map getConvertersIds() {
return getConverterMaps()[CONVERTERS_IDS];
}
- static Map[] getConverterMaps() {
+ private static Map[] getConverterMaps() {
Map[] converterMaps = null;
synchronized (converterMapsMap) {
ObjectFactory objectFactory = JbpmConfiguration.Configs.getObjectFactory();
@@ -98,7 +97,7 @@
return converterMaps;
}
- static Map[] createConverterMaps(ObjectFactory objectFactory) {
+ private static Map[] createConverterMaps(ObjectFactory objectFactory) {
Map[] converterMaps = new Map[3];
converterMaps[CONVERTERS_BY_CLASS_NAMES] = new HashMap();
converterMaps[CONVERTERS_BY_DATABASE_ID] = new HashMap();
@@ -117,31 +116,40 @@
converterProperties = new Properties();
}
- Iterator iter = converterProperties.keySet().iterator();
- while (iter.hasNext()) {
- String converterDatabaseId = (String) iter.next();
- if (converterDatabaseId.length() != 1)
- throw new JbpmException("converter-ids must be of length 1 (to be stored in a char)");
- if (convertersByDatabaseId.containsKey(converterDatabaseId))
- throw new JbpmException("duplicate converter id : '" + converterDatabaseId + "'");
- String converterClassName = converterProperties.getProperty(converterDatabaseId);
+ boolean debug = log.isDebugEnabled();
+ for (Iterator iter = converterProperties.keySet().iterator(); iter.hasNext();) {
+ String converterId = (String) iter.next();
+ if (converterId.length() != 1) {
+ throw new JbpmException("converter-id must be a single char");
+ }
+ if (convertersByDatabaseId.containsKey(converterId)) {
+ throw new JbpmException("duplicate converter-id: " + converterId);
+ }
+
+ String converterClassName = converterProperties.getProperty(converterId);
try {
Class converterClass = ClassLoaderUtil.classForName(converterClassName);
- Converter converter = (Converter) converterClass.newInstance();
- log.debug("adding converter '" + converterDatabaseId + "', '" + converterClassName + "'");
- convertersByClassNames.put(converterClassName, converter);
- convertersByDatabaseId.put(converterDatabaseId, converter);
- convertersIds.put(converter, converterDatabaseId);
+ try {
+ Converter converter = (Converter) converterClass.newInstance();
+ convertersByClassNames.put(converterClassName, converter);
+ convertersByDatabaseId.put(converterId, converter);
+ convertersIds.put(converter, converterId);
+ if (debug) log.debug("registered converter: " + converterClassName);
+ }
+ catch (InstantiationException e) {
+ if (debug) log.debug("failed to instantiate: " + converterClass, e);
+ }
+ catch (IllegalAccessException e) {
+ if (debug) log.debug(Converters.class + " has no access to " + converterClass, e);
+ }
}
- catch (Exception e) {
- // NOTE that Error's are not caught because that might halt the JVM and mask the original
- // Error.
- log.debug("couldn't instantiate converter '" + converterClassName + "': " + e);
+ catch (JbpmException e) {
+ if (debug) log.debug("converter class not found: " + converterClassName, e);
}
}
return converterMaps;
}
- private static Log log = LogFactory.getLog(Converters.class);
+ private static final Log log = LogFactory.getLog(Converters.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/hibernate/HibernateHelper.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/hibernate/HibernateHelper.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/hibernate/HibernateHelper.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -45,7 +45,7 @@
* maps SessionFactory's to Configurations.<br>
* by default, configuration lookup will be enabled
*/
- static Map configurations = new HashMap();
+ private static Map configurations = new HashMap();
public static void clearConfigurationsCache() {
configurations.clear();
@@ -60,18 +60,18 @@
}
public static SessionFactory createSessionFactory(String cfgXmlResource,
- String propertiesResource) {
+ String propertiesResource) {
return createSessionFactory(cfgXmlResource, propertiesResource, true);
}
public static SessionFactory createSessionFactory(String cfgXmlResource,
- String propertiesResource, boolean isConfigLookupEnabled) {
+ String propertiesResource, boolean isConfigLookupEnabled) {
Configuration configuration = createConfiguration(cfgXmlResource, propertiesResource);
return createSessionFactory(configuration, isConfigLookupEnabled);
}
public static SessionFactory createSessionFactory(Configuration configuration,
- boolean isConfigLookupEnabled) {
+ boolean isConfigLookupEnabled) {
SessionFactory sessionFactory = configuration.buildSessionFactory();
if (isConfigLookupEnabled) {
configurations.put(sessionFactory, configuration);
@@ -80,27 +80,27 @@
}
public static Configuration createConfiguration(String cfgXmlResource,
- String propertiesResource) {
+ String propertiesResource) {
Configuration configuration = new Configuration();
// if a special hibernate configuration xml file is specified,
if (cfgXmlResource != null) {
// use the configured file name
- log.debug("using hibernate configuration resource: " + cfgXmlResource);
configuration.configure(cfgXmlResource);
}
else {
- log.debug("using default hibernate configuration resource: hibernate.cfg.xml");
configuration.configure();
}
// if the properties are specified in a separate file
if (propertiesResource != null) {
- log.debug("using hibernate properties resource: " + propertiesResource);
+ if (log.isDebugEnabled()) {
+ log.debug("loading hibernate properties from resource: " + propertiesResource);
+ }
// load the properties
Properties properties = loadPropertiesFromResource(propertiesResource);
if (!properties.isEmpty()) {
- // add (and replace) the properties to the configuration
+ // add the properties to the configuration, replacing any existing values
configuration.addProperties(properties);
}
}
@@ -137,7 +137,7 @@
}
}
- static Properties loadPropertiesFromResource(String resource) {
+ private static Properties loadPropertiesFromResource(String resource) {
Properties properties = new Properties();
InputStream inputStream = ClassLoaderUtil.getStream(resource);
if (inputStream != null) {
@@ -154,5 +154,5 @@
return properties;
}
- private static Log log = LogFactory.getLog(HibernateHelper.class);
+ private static final Log log = LogFactory.getLog(HibernateHelper.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/action/ActionTypes.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/action/ActionTypes.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/action/ActionTypes.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -32,6 +32,7 @@
import org.w3c.dom.Element;
import org.jbpm.JbpmConfiguration;
+import org.jbpm.JbpmException;
import org.jbpm.graph.node.NodeTypes;
import org.jbpm.util.ClassLoaderUtil;
import org.jbpm.util.XmlUtil;
@@ -58,35 +59,32 @@
return actionTypes.containsKey(name);
}
- static final Log log = LogFactory.getLog(ActionTypes.class);
- static Map actionTypes = initialiseActionTypes();
- static Map actionNames = NodeTypes.createInverseMapping(actionTypes);
+ private static final Log log = LogFactory.getLog(ActionTypes.class);
+ private static Map actionTypes = initialiseActionTypes();
+ private static Map actionNames = NodeTypes.createInverseMapping(actionTypes);
- static Map initialiseActionTypes() {
+ private static Map initialiseActionTypes() {
Map types = new HashMap();
String resource = JbpmConfiguration.Configs.getString("resource.action.types");
InputStream actionTypesStream = ClassLoaderUtil.getStream(resource);
Element actionTypesElement = XmlUtil.parseXmlInputStream(actionTypesStream)
- .getDocumentElement();
- Iterator actionTypeIterator = XmlUtil.elementIterator(actionTypesElement, "action-type");
- while (actionTypeIterator.hasNext()) {
- Element actionTypeElement = (Element) actionTypeIterator.next();
+ .getDocumentElement();
+ for (Iterator iter = XmlUtil.elementIterator(actionTypesElement, "action-type"); iter.hasNext();) {
+ Element actionTypeElement = (Element) iter.next();
String elementTag = actionTypeElement.getAttribute("element");
+
String className = actionTypeElement.getAttribute("class");
try {
Class actionClass = ClassLoaderUtil.classForName(className);
types.put(elementTag, actionClass);
-
}
- catch (Exception e) {
- // NOTE that Error's are not caught because that might halt the JVM and mask the original Error.
- log.debug("action '"
- + elementTag
- + "' will not be available. class '"
- + className
- + "' couldn't be loaded");
+ catch (JbpmException e) {
+ if (log.isDebugEnabled()) {
+ log.debug("action '" + elementTag + "' will not be available, class not found: "
+ + className);
+ }
}
}
return types;
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/action/Script.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/action/Script.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/action/Script.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -123,14 +123,18 @@
public Map eval(Map inputMap, Set outputNames) {
try {
// set input variables
- log.debug("script input: " + inputMap);
+ boolean debug = log.isDebugEnabled();
+ if (debug) log.debug("script input: " + inputMap);
+
Interpreter interpreter = new Interpreter();
for (Iterator iter = inputMap.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
interpreter.set((String) entry.getKey(), entry.getValue());
}
+
// evaluate script
interpreter.eval(expression);
+
// get output variables
if (outputNames.isEmpty()) return Collections.EMPTY_MAP;
Map outputMap = new HashMap();
@@ -139,7 +143,7 @@
Object outputValue = interpreter.get(outputName);
outputMap.put(outputName, outputValue);
}
- log.debug("script output: " + outputMap);
+ if (debug) log.debug("script output: " + outputMap);
return outputMap;
}
catch (ParseException e) {
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/def/EventCallback.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/def/EventCallback.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/def/EventCallback.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -90,14 +90,16 @@
public void afterCompletion(int status) {
if (status == Status.STATUS_COMMITTED) {
- log.debug("sending '" + event + "' notification");
+ if (log.isDebugEnabled()) log.debug("sending '" + event + "' notification");
Semaphore eventSemaphore = getEventSemaphore(event);
eventSemaphore.release();
}
}
};
- JbpmContext.getCurrentJbpmContext().getSession().getTransaction().registerSynchronization(
- notification);
+ JbpmContext.getCurrentJbpmContext()
+ .getSession()
+ .getTransaction()
+ .registerSynchronization(notification);
}
public static void waitForEvent(String event) {
@@ -113,15 +115,14 @@
}
public static void waitForEvent(int occurrences, String event, long timeout) {
- log.debug("waiting for " + event);
+ boolean debug = log.isDebugEnabled();
+ if (debug) log.debug("waiting for " + event);
Semaphore eventSemaphore = getEventSemaphore(event);
try {
- if (eventSemaphore.tryAcquire(occurrences, timeout)) {
- log.debug("received '" + event + "' notification");
- }
- else {
+ if (!eventSemaphore.tryAcquire(occurrences, timeout)) {
throw new JbpmException("event '" + event + "' did not occur within " + timeout + " ms");
}
+ if (debug) log.debug("received '" + event + "' notification");
}
catch (InterruptedException e) {
throw new JbpmException("wait for event '" + event + "' was interrupted", e);
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/def/GraphElement.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/def/GraphElement.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/def/GraphElement.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -172,8 +172,7 @@
public void fireEvent(String eventType, ExecutionContext executionContext) {
Token token = executionContext.getToken();
- log.debug("event '" + eventType + "' on " + this + " for " + token + " of "
- + token.getProcessInstance());
+ if (log.isDebugEnabled()) log.debug(token + " fires event '" + eventType + "' on " + this);
GraphElement eventSource = executionContext.getEventSource();
try {
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/def/Transition.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/def/Transition.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/def/Transition.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -49,8 +49,8 @@
};
/**
- * @deprecated arrays are mutable and thus vulnerable to external
- * manipulation. use {@link #getSupportedEventTypes()} instead
+ * @deprecated arrays are mutable and thus vulnerable to external manipulation. use
+ * {@link #getSupportedEventTypes()} instead
*/
public static final String[] supportedEventTypes = (String[]) EVENT_TYPES.clone();
@@ -74,9 +74,8 @@
}
/**
- * sets the from node unidirectionally. use
- * {@link Node#addLeavingTransition(Transition)} to get bidirectional
- * relations mgmt.
+ * sets the from node unidirectionally. use {@link Node#addLeavingTransition(Transition)} to
+ * get bidirectional relations mgmt.
*/
public void setFrom(Node from) {
this.from = from;
@@ -85,9 +84,8 @@
// to ///////////////////////////////////////////////////////////////////////
/**
- * sets the to node unidirectionally. use
- * {@link Node#addArrivingTransition(Transition)} to get bidirectional
- * relations mgmt.
+ * sets the to node unidirectionally. use {@link Node#addArrivingTransition(Transition)} to
+ * get bidirectional relations mgmt.
*/
public void setTo(Node to) {
this.to = to;
@@ -117,8 +115,7 @@
}
/**
- * @deprecated call {@link #setConditionEnforced(boolean)
- * setConditionEnforced(false)} instead
+ * @deprecated call {@link #setConditionEnforced(boolean) setConditionEnforced(false)} instead
*/
public void removeConditionEnforcement() {
isConditionEnforced = false;
@@ -131,17 +128,11 @@
*/
public void take(ExecutionContext executionContext) {
if (condition != null && isConditionEnforced) {
- Object result = JbpmExpressionEvaluator.evaluate(condition, executionContext);
- if (result instanceof Boolean) {
- Boolean go = (Boolean) result;
- if (!go.booleanValue()) {
- throw new JbpmException("condition '" + condition + "' guarding " + this + " not met");
- }
+ Boolean result = (Boolean) JbpmExpressionEvaluator.evaluate(condition, executionContext,
+ Boolean.class);
+ if (!Boolean.TRUE.equals(result)) {
+ throw new JbpmException("condition '" + condition + "' guarding " + this + " not met");
}
- else {
- throw new JbpmException("expected boolean result from condition '" + condition
- + "' guarding " + this + ", but was " + result);
- }
}
// update the runtime context information
@@ -149,8 +140,7 @@
token.setNode(null);
// start the transition log
- TransitionLog transitionLog = new TransitionLog(this,
- executionContext.getTransitionSource());
+ TransitionLog transitionLog = new TransitionLog(this, executionContext.getTransitionSource());
token.startCompositeLog(transitionLog);
try {
// fire leave events for superstates (if any)
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/exe/Token.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/exe/Token.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/exe/Token.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -55,8 +55,8 @@
/**
* represents one path of execution and maintains a pointer to a node in the
- * {@link org.jbpm.graph.def.ProcessDefinition}. Most common way to get a hold
- * of the token objects is with {@link ProcessInstance#getRootToken()} or
+ * {@link org.jbpm.graph.def.ProcessDefinition}. Most common way to get a hold of the token
+ * objects is with {@link ProcessInstance#getRootToken()} or
* {@link org.jbpm.graph.exe.ProcessInstance#findToken(String)}.
*/
public class Token implements Identifiable, Serializable {
@@ -128,8 +128,8 @@
}
/**
- * sends a signal to this token. leaves the current {@link #getNode() node}
- * over the default transition.
+ * sends a signal to this token. leaves the current {@link #getNode() node} over the default
+ * transition.
*/
public void signal() {
if (node == null) {
@@ -143,8 +143,8 @@
}
/**
- * sends a signal to this token. leaves the current {@link #getNode() node}
- * over the transition with the given name.
+ * sends a signal to this token. leaves the current {@link #getNode() node} over the
+ * transition with the given name.
*/
public void signal(String transitionName) {
if (node == null) {
@@ -170,8 +170,8 @@
}
/**
- * sends a signal to this token. leaves the current {@link #getNode() node}
- * over the given transition.
+ * sends a signal to this token. leaves the current {@link #getNode() node} over the given
+ * transition.
*/
public void signal(Transition transition) {
signal(transition, new ExecutionContext(this));
@@ -219,8 +219,8 @@
}
/**
- * a set of all the leaving transitions on the current node for which the
- * condition expression resolves to true.
+ * a set of all the leaving transitions on the current node for which the condition expression
+ * resolves to true.
*/
public Set getAvailableTransitions() {
Set availableTransitions = new HashSet();
@@ -231,8 +231,8 @@
}
/**
- * adds available transitions of that node to the Set and after that calls
- * itself recursively for the SuperSate of the Node if it has a super state
+ * adds available transitions of that node to the Set and after that calls itself recursively
+ * for the SuperSate of the Node if it has a super state
*/
private void addAvailableTransitionsOfNode(Node currentNode, Set availableTransitions) {
List leavingTransitions = currentNode.getLeavingTransitions();
@@ -241,11 +241,9 @@
Transition transition = (Transition) iter.next();
String conditionExpression = transition.getCondition();
if (conditionExpression != null) {
- Object result =
- JbpmExpressionEvaluator.evaluate(conditionExpression, new ExecutionContext(this));
- if ((result instanceof Boolean) && (((Boolean) result).booleanValue())) {
- availableTransitions.add(transition);
- }
+ Boolean result = (Boolean) JbpmExpressionEvaluator.evaluate(conditionExpression,
+ new ExecutionContext(this), Boolean.class);
+ if (Boolean.TRUE.equals(result)) availableTransitions.add(transition);
}
else {
availableTransitions.add(transition);
@@ -258,9 +256,9 @@
}
/**
- * ends this token and all of its children (if any). this is the last active
- * (i.e. not-ended) child of a parent token, the parent token will be ended as
- * well and that verification will continue to propagate.
+ * ends this token and all of its children (if any). this is the last active (i.e. not-ended)
+ * child of a parent token, the parent token will be ended as well and that verification will
+ * continue to propagate.
*/
public void end() {
end(true);
@@ -269,10 +267,10 @@
/**
* ends this token with optional parent ending verification.
*
- * @param verifyParentTermination specifies if the parent token should be
- * checked for termination. if verifyParentTermination is set to true and this
- * is the last non-ended child of a parent token, the parent token will be
- * ended as well and the verification will continue to propagate.
+ * @param verifyParentTermination specifies if the parent token should be checked for
+ * termination. if verifyParentTermination is set to true and this is the last non-ended child
+ * of a parent token, the parent token will be ended as well and the verification will
+ * continue to propagate.
*/
public void end(boolean verifyParentTermination) {
// if already ended, do nothing
@@ -377,8 +375,8 @@
}
/**
- * convenience method for starting a composite log. When you add composite
- * logs, make sure you put the {@link #endCompositeLog()} in a finally block.
+ * convenience method for starting a composite log. When you add composite logs, make sure you
+ * put the {@link #endCompositeLog()} in a finally block.
*/
public void startCompositeLog(CompositeLog compositeLog) {
LoggingInstance loggingInstance = processInstance.getLoggingInstance();
@@ -389,8 +387,7 @@
}
/**
- * convenience method for ending a composite log. Make sure you put this in a
- * finally block.
+ * convenience method for ending a composite log. Make sure you put this in a finally block.
*/
public void endCompositeLog() {
LoggingInstance loggingInstance = processInstance.getLoggingInstance();
@@ -610,8 +607,8 @@
public int hashCode() {
int result = 2080763213 + (name != null ? name.hashCode() : 0);
- result =
- 1076685199 * result + (parent != null ? parent.hashCode() : processInstance.hashCode());
+ result = 1076685199 * result
+ + (parent != null ? parent.hashCode() : processInstance.hashCode());
return result;
}
@@ -631,24 +628,22 @@
}
/**
- * locks a process instance for further execution. A locked token cannot
- * continue execution. This is a non-persistent operation. This is used to
- * prevent tokens being propagated during the execution of actions.
+ * locks a process instance for further execution. A locked token cannot continue execution.
+ * This is a non-persistent operation. This is used to prevent tokens being propagated during
+ * the execution of actions.
*
* @see #unlock(String)
*/
public void lock(String lockOwner) {
- if (lockOwner == null) {
- throw new JbpmException("lock owner is null");
- }
+ if (lockOwner == null) throw new JbpmException("lock owner is null");
if (lock == null) {
lock = lockOwner;
- log.debug('\'' + lockOwner + "' locked " + this);
+ if (log.isDebugEnabled()) log.debug('\'' + lockOwner + "' locked " + this);
}
else if (!lock.equals(lockOwner)) {
- throw new JbpmException('\'' + lockOwner + "' cannot lock " + this + " because '"
- + lock + "' already locked it");
+ throw new JbpmException('\'' + lockOwner + "' cannot lock " + this + " because '" + lock
+ + "' already locked it");
}
}
@@ -661,8 +656,9 @@
throw new JbpmException('\'' + lockOwner + "' cannot unlock " + this + " because '"
+ lock + "' locked it");
}
+
lock = null;
- log.debug('\'' + lockOwner + "' unlocked " + this);
+ if (log.isDebugEnabled()) log.debug('\'' + lockOwner + "' unlocked " + this);
}
else {
log.warn(this + " was already unlocked");
@@ -670,10 +666,9 @@
}
/**
- * force unlocking the token, even if the owner is not known. In some use
- * cases (e.g. in the jbpm esb integration) the lock is persistent, so a state
- * can be reached where the client needs a possibility to force unlock of a
- * token without knowing the owner.
+ * force unlocking the token, even if the owner is not known. In some use cases (e.g. in the
+ * jbpm esb integration) the lock is persistent, so a state can be reached where the client
+ * needs a possibility to force unlock of a token without knowing the owner.
*
* @see <a href="https://jira.jboss.org/jira/browse/JBPM-1888">JBPM-1888</a>
* @deprecated Use {@link #forceUnlock()} instead
@@ -683,17 +678,16 @@
}
/**
- * force unlocking the token, even if the owner is not known. In some use
- * cases (e.g. in the jbpm esb integration) the lock is persistent, so a state
- * can be reached where the client needs a possibility to force unlock of a
- * token without knowing the owner.
+ * force unlocking the token, even if the owner is not known. In some use cases (e.g. in the
+ * jbpm esb integration) the lock is persistent, so a state can be reached where the client
+ * needs a possibility to force unlock of a token without knowing the owner.
*
* @see <a href="https://jira.jboss.org/jira/browse/JBPM-1888">JBPM-1888</a>
*/
public void forceUnlock() {
if (lock != null) {
lock = null;
- log.debug("forcefully unlocked " + this);
+ if (log.isDebugEnabled()) log.debug("forcefully unlocked " + this);
}
else {
log.warn(this + " was unlocked already");
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/Decision.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/Decision.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/Decision.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -85,7 +85,8 @@
try {
// set context class loader correctly for delegation class
// https://jira.jboss.org/jira/browse/JBPM-1448
- ClassLoader processClassLoader = JbpmConfiguration.getProcessClassLoader(executionContext.getProcessDefinition());
+ ClassLoader processClassLoader = JbpmConfiguration.getProcessClassLoader(executionContext
+ .getProcessDefinition());
Thread.currentThread().setContextClassLoader(processClassLoader);
Transition transition = null;
@@ -103,11 +104,8 @@
}
}
else if (decisionExpression != null) {
- Object result = JbpmExpressionEvaluator.evaluate(decisionExpression, executionContext);
- if (result == null) {
- throw new JbpmException("expression evaluated to null: " + decisionExpression);
- }
- String transitionName = result.toString();
+ String transitionName = (String) JbpmExpressionEvaluator
+ .evaluate(decisionExpression, executionContext, String.class);
transition = getLeavingTransition(transitionName);
if (transition == null) {
throw new JbpmException("no such transition: " + transitionName);
@@ -119,7 +117,8 @@
DecisionCondition decisionCondition = (DecisionCondition) iter.next();
// evaluate condition
String expression = decisionCondition.getExpression();
- Object result = JbpmExpressionEvaluator.evaluate(expression, executionContext);
+ Boolean result = (Boolean) JbpmExpressionEvaluator
+ .evaluate(expression, executionContext, Boolean.class);
// if condition was true
if (Boolean.TRUE.equals(result)) {
// fetch name associated to condition
@@ -137,7 +136,8 @@
// evaluate condition if present
String condition = candidate.getCondition();
if (condition != null) {
- Object result = JbpmExpressionEvaluator.evaluate(condition, executionContext);
+ Boolean result = (Boolean) JbpmExpressionEvaluator
+ .evaluate(condition, executionContext, Boolean.class);
// if condition was true
if (Boolean.TRUE.equals(result)) {
// select transition associated to condition
@@ -155,7 +155,9 @@
if (transition == null) throw new JbpmException(this + " has no default transition");
}
- log.debug(executionContext.getToken() + " leaves " + this + " over " + transition);
+ if (log.isDebugEnabled()) {
+ log.debug(executionContext.getToken() + " leaves " + this + " over " + transition);
+ }
executionContext.leaveNode(transition);
}
finally {
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/Join.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/Join.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/Join.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -44,14 +44,14 @@
private static final long serialVersionUID = 1L;
/**
- * specifies what type of hibernate lock should be acquired. null value
- * defaults to LockMode.UPGRADE
+ * specifies what type of hibernate lock should be acquired. null value defaults to
+ * LockMode.UPGRADE
*/
String parentLockMode;
/**
- * specifies if this join is a discriminator. a descriminator reactivates the
- * parent when the first child token enters the join.
+ * specifies if this join is a discriminator. a descriminator reactivates the parent when the
+ * first child token enters the join.
*/
boolean isDiscriminator;
@@ -114,11 +114,13 @@
Session session;
if (jbpmContext != null && (session = jbpmContext.getSession()) != null) {
// obtain update lock by default (LockMode.UPGRADE)
- LockMode lockMode =
- parentLockMode != null ? LockMode.parse(parentLockMode) : LockMode.UPGRADE;
+ LockMode lockMode = parentLockMode != null ? LockMode.parse(parentLockMode)
+ : LockMode.UPGRADE;
// load() hits the database as required, no need to flush() here
parentToken = (Token) session.load(Token.class, new Long(parentToken.getId()), lockMode);
- log.debug(this + " acquires " + lockMode + " lock on " + parentToken);
+ if (log.isDebugEnabled()) {
+ log.debug(this + " acquires " + lockMode + " lock on " + parentToken);
+ }
}
boolean reactivateParent;
@@ -130,8 +132,8 @@
// if a fixed set of tokenNames is specified at design time...
else if (tokenNames != null) {
// check reactivation on the basis of those tokenNames
- reactivateParent =
- !parentToken.hasActiveChildren() && mustParentBeReactivated(parentToken, tokenNames);
+ reactivateParent = !parentToken.hasActiveChildren()
+ && mustParentBeReactivated(parentToken, tokenNames);
}
// if a script is specified
else if (script != null) {
@@ -153,8 +155,8 @@
// check all child tokens and reactivate the parent
// when the last token arrives in the join
Collection tokenNames = parentToken.getChildren().keySet();
- reactivateParent =
- !parentToken.hasActiveChildren() && mustParentBeReactivated(parentToken, tokenNames);
+ reactivateParent = !parentToken.hasActiveChildren()
+ && mustParentBeReactivated(parentToken, tokenNames);
}
// if the parent token is to leave this node
@@ -207,8 +209,10 @@
String childTokenName = (String) childTokenNames.next();
Token childToken = parentToken.getChild(childTokenName);
if (childToken.isAbleToReactivateParent()) {
- log.debug(parentToken + " does not leave " + this + " as " + childToken
- + " is still active");
+ if (log.isDebugEnabled()) {
+ log.debug(parentToken + " does not leave " + this + " as " + childToken
+ + " is still active");
+ }
return false;
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/NodeTypes.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/NodeTypes.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/NodeTypes.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -32,6 +32,7 @@
import org.w3c.dom.Element;
import org.jbpm.JbpmConfiguration;
+import org.jbpm.JbpmException;
import org.jbpm.util.ClassLoaderUtil;
import org.jbpm.util.XmlUtil;
@@ -55,33 +56,30 @@
private static final Log log = LogFactory.getLog(NodeTypes.class);
- static Map nodeTypes = initialiseNodeTypes();
- static Map nodeNames = createInverseMapping(nodeTypes);
+ private static Map nodeTypes = initialiseNodeTypes();
+ private static Map nodeNames = createInverseMapping(nodeTypes);
- static Map initialiseNodeTypes() {
+ private static Map initialiseNodeTypes() {
Map types = new HashMap();
String resource = JbpmConfiguration.Configs.getString("resource.node.types");
- InputStream actionTypesStream = ClassLoaderUtil.getStream(resource);
- Element nodeTypesElement = XmlUtil.parseXmlInputStream(actionTypesStream).getDocumentElement();
- Iterator nodeTypeIterator = XmlUtil.elementIterator(nodeTypesElement, "node-type");
- while (nodeTypeIterator.hasNext()) {
- Element nodeTypeElement = (Element) nodeTypeIterator.next();
+ InputStream nodeTypesStream = ClassLoaderUtil.getStream(resource);
+ Element nodeTypesElement = XmlUtil.parseXmlInputStream(nodeTypesStream)
+ .getDocumentElement();
+ for (Iterator iter = XmlUtil.elementIterator(nodeTypesElement, "node-type"); iter.hasNext();) {
+ Element nodeTypeElement = (Element) iter.next();
String elementTag = nodeTypeElement.getAttribute("element");
+
String className = nodeTypeElement.getAttribute("class");
try {
Class nodeClass = ClassLoaderUtil.classForName(className);
types.put(elementTag, nodeClass);
-
}
- catch (Exception e) {
- if (!"org.jboss.seam.jbpm.Page".equals(className)) {
- log.debug("node '"
- + elementTag
- + "' will not be available. class '"
- + className
- + "' couldn't be loaded");
+ catch (JbpmException e) {
+ if (log.isDebugEnabled()) {
+ log.debug("node '" + elementTag + "' will not be available, class not found: "
+ + className);
}
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/ProcessState.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/ProcessState.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/ProcessState.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -21,17 +21,14 @@
*/
package org.jbpm.graph.node;
-import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
-import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Element;
import org.dom4j.tree.DefaultElement;
-import org.dom4j.tree.FlyweightAttribute;
import org.jbpm.JbpmException;
import org.jbpm.JbpmConfiguration.Configs;
@@ -53,8 +50,9 @@
private static final long serialVersionUID = 1L;
- static SubProcessResolver defaultSubProcessResolver = new DbSubProcessResolver();
+ private static SubProcessResolver defaultSubProcessResolver = new DbSubProcessResolver();
+ /** @deprecated set configuration entry <code>jbpm.sub.process.resolver</code> instead */
public static void setDefaultSubProcessResolver(SubProcessResolver subProcessResolver) {
defaultSubProcessResolver = subProcessResolver;
}
@@ -82,8 +80,8 @@
};
/**
- * @deprecated arrays are mutable and thus vulnerable to external
- * manipulation. use {@link #getSupportedEventTypes()} instead
+ * @deprecated arrays are mutable and thus vulnerable to external manipulation. use
+ * {@link #getSupportedEventTypes()} instead
*/
public static final String[] supportedEventTypes = (String[]) EVENT_TYPES.clone();
@@ -95,51 +93,50 @@
public void read(Element processStateElement, JpdlXmlReader jpdlReader) {
Element subProcessElement = processStateElement.element("sub-process");
-
if (subProcessElement != null) {
String binding = subProcessElement.attributeValue("binding");
if ("late".equalsIgnoreCase(binding)) {
subProcessName = subProcessElement.attributeValue("name");
+ if (log.isDebugEnabled()) {
+ log.debug(this + " will be late bound to process definition: " + subProcessName);
+ }
}
else {
- SubProcessResolver subProcessResolver = getSubProcessResolver();
- try {
- subProcessDefinition = subProcessResolver.findSubProcess(subProcessElement);
- }
- catch (JbpmException e) {
- jpdlReader.addWarning(e.getMessage());
- }
-
- // in case this is a self-recursive process invocation...
- if (subProcessDefinition == null) {
- String subProcessName = subProcessElement.attributeValue("name");
- if (subProcessName.equals(processDefinition.getName())) {
- subProcessDefinition = processDefinition;
- }
- }
+ subProcessDefinition = resolveSubProcess(subProcessElement, jpdlReader);
}
}
- if (subProcessDefinition != null) {
- log.debug("subprocess for process-state '" + name + "' bound to " + subProcessDefinition);
+ variableAccesses = new HashSet(jpdlReader.readVariableAccesses(processStateElement));
+ }
+
+ private ProcessDefinition resolveSubProcess(Element subProcessElement,
+ JpdlXmlReader jpdlReader) {
+ SubProcessResolver subProcessResolver = getSubProcessResolver();
+ try {
+ ProcessDefinition subProcess = subProcessResolver.findSubProcess(subProcessElement);
+ if (subProcess != null) {
+ if (log.isDebugEnabled()) log.debug("bound " + this + " to " + subProcess);
+ return subProcess;
+ }
}
- else if (subProcessName != null) {
- log.debug("subprocess for process-state '" + name + "' will be late bound to "
- + subProcessName);
+ catch (JbpmException e) {
+ jpdlReader.addWarning(e.getMessage());
}
- else {
- log.debug("subprocess for process-state '" + name + "' not yet bound");
- }
- variableAccesses = new HashSet(jpdlReader.readVariableAccesses(processStateElement));
+ // check whether this is a recursive process invocation
+ String subProcessName = subProcessElement.attributeValue("name");
+ if (subProcessName != null && subProcessName.equals(processDefinition.getName())) {
+ if (log.isDebugEnabled()) {
+ log.debug("bound " + this + " to its own " + processDefinition);
+ }
+ return processDefinition;
+ }
+ return null;
}
private SubProcessResolver getSubProcessResolver() {
- SubProcessResolver subProcessResolver = defaultSubProcessResolver;
- if (Configs.hasObject("jbpm.sub.process.resolver")) {
- subProcessResolver = (SubProcessResolver) Configs.getObject("jbpm.sub.process.resolver");
- }
- return subProcessResolver;
+ return Configs.hasObject("jbpm.sub.process.resolver") ? (SubProcessResolver) Configs
+ .getObject("jbpm.sub.process.resolver") : defaultSubProcessResolver;
}
public void execute(ExecutionContext executionContext) {
@@ -148,21 +145,17 @@
ProcessDefinition usedSubProcessDefinition = subProcessDefinition;
// if this process has late binding
if (subProcessDefinition == null && subProcessName != null) {
- SubProcessResolver subProcessResolver = getSubProcessResolver();
- List attributes = new ArrayList();
- String subProcessNameResolved = (String) JbpmExpressionEvaluator.evaluate(subProcessName, executionContext);
- if (log.isDebugEnabled()) {
- log.debug("SubProcessName after eval: " + subProcessNameResolved);
- }
- attributes.add(new FlyweightAttribute("name", subProcessNameResolved));
Element subProcessElement = new DefaultElement("sub-process");
- subProcessElement.setAttributes(attributes);
+ subProcessElement.addAttribute("name", (String) JbpmExpressionEvaluator
+ .evaluate(subProcessName, executionContext, String.class));
+ SubProcessResolver subProcessResolver = getSubProcessResolver();
usedSubProcessDefinition = subProcessResolver.findSubProcess(subProcessElement);
}
// create the subprocess
- ProcessInstance subProcessInstance = superProcessToken.createSubProcessInstance(usedSubProcessDefinition);
+ ProcessInstance subProcessInstance = superProcessToken
+ .createSubProcessInstance(usedSubProcessDefinition);
// fire the subprocess created event
fireEvent(Event.EVENTTYPE_SUBPROCESS_CREATED, executionContext);
@@ -182,10 +175,12 @@
// to the sub process mapped name
String variableName = variableAccess.getVariableName();
Object value = superContextInstance.getVariable(variableName, superProcessToken);
- String mappedName = variableAccess.getMappedName();
- log.debug("copying super process var '" + variableName + "' to sub process var '"
- + mappedName + "': " + value);
if (value != null) {
+ String mappedName = variableAccess.getMappedName();
+ if (log.isDebugEnabled()) {
+ log.debug(superProcessToken + " reads '" + variableName + "' into '" + mappedName
+ + '\'');
+ }
subContextInstance.setVariable(mappedName, value);
}
}
@@ -198,7 +193,6 @@
public void leave(ExecutionContext executionContext, Transition transition) {
ProcessInstance subProcessInstance = executionContext.getSubProcessInstance();
-
Token superProcessToken = subProcessInstance.getSuperProcessToken();
// feed the readable variableInstances
@@ -215,10 +209,12 @@
// to the super process variable name
String mappedName = variableAccess.getMappedName();
Object value = subContextInstance.getVariable(mappedName);
- String variableName = variableAccess.getVariableName();
- log.debug("copying sub process var '" + mappedName + "' to super process var '"
- + variableName + "': " + value);
if (value != null) {
+ String variableName = variableAccess.getVariableName();
+ if (log.isDebugEnabled()) {
+ log.debug(superProcessToken + " writes '" + variableName + "' from '"
+ + mappedName + '\'');
+ }
superContextInstance.setVariable(variableName, value, superProcessToken);
}
}
@@ -234,8 +230,8 @@
// We replaced the normal log generation of super.leave()
// by creating the log here
// and overriding the addNodeLog method with an empty version
- superProcessToken.addLog(new ProcessStateLog(this, superProcessToken.getNodeEnter(),
- Clock.getCurrentTime(), subProcessInstance));
+ superProcessToken.addLog(new ProcessStateLog(this, superProcessToken.getNodeEnter(), Clock
+ .getCurrentTime(), subProcessInstance));
// call the subProcessEndAction
super.leave(executionContext, getDefaultLeavingTransition());
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/TaskNode.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/TaskNode.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/graph/node/TaskNode.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -41,43 +41,39 @@
import org.jbpm.taskmgmt.exe.TaskMgmtInstance;
/**
- * is a node that relates to one or more tasks. Property <code>signal</code>
- * specifies how task completion triggers continuation of execution.
+ * is a node that relates to one or more tasks. Property <code>signal</code> specifies how task
+ * completion triggers continuation of execution.
*/
public class TaskNode extends Node {
private static final long serialVersionUID = 1L;
/**
- * execution always continues, regardless whether tasks are created or still
- * unfinished.
+ * execution always continues, regardless whether tasks are created or still unfinished.
*/
public static final int SIGNAL_UNSYNCHRONIZED = 0;
/**
- * execution never continues, regardless whether tasks are created or still
- * unfinished.
+ * execution never continues, regardless whether tasks are created or still unfinished.
*/
public static final int SIGNAL_NEVER = 1;
/**
- * proceeds execution when the first task instance is completed. when no tasks
- * are created on entrance of this node, execution is continued.
+ * proceeds execution when the first task instance is completed. when no tasks are created on
+ * entrance of this node, execution is continued.
*/
public static final int SIGNAL_FIRST = 2;
/**
- * proceeds execution when the first task instance is completed. when no tasks
- * are created on entrance of this node, execution waits in the task node till
- * tasks are created.
+ * proceeds execution when the first task instance is completed. when no tasks are created on
+ * entrance of this node, execution waits in the task node till tasks are created.
*/
public static final int SIGNAL_FIRST_WAIT = 3;
/**
- * proceeds execution when the last task instance is completed. when no tasks
- * are created on entrance of this node, execution is continued.
+ * proceeds execution when the last task instance is completed. when no tasks are created on
+ * entrance of this node, execution is continued.
*/
public static final int SIGNAL_LAST = 4;
/**
- * proceeds execution when the last task instance is completed. when no tasks
- * are created on entrance of this node, execution waits in the task node till
- * tasks are created.
+ * proceeds execution when the last task instance is completed. when no tasks are created on
+ * entrance of this node, execution waits in the task node till tasks are created.
*/
public static final int SIGNAL_LAST_WAIT = 5;
@@ -155,7 +151,7 @@
// ///////////////////////////////////////////////////////////////////////////
public void execute(ExecutionContext executionContext) {
- TaskMgmtInstance tmi = getTaskMgmtInstance(executionContext.getToken());
+ TaskMgmtInstance tmi = executionContext.getTaskMgmtInstance();
// if this tasknode should create instances
if (createTasks && tasks != null) {
@@ -188,16 +184,18 @@
private boolean evaluateTaskCondition(String condition, ExecutionContext executionContext) {
if (condition == null) return true;
- Object result = JbpmExpressionEvaluator.evaluate(condition, executionContext);
+ Boolean result = (Boolean) JbpmExpressionEvaluator
+ .evaluate(condition, executionContext, Boolean.class);
return Boolean.TRUE.equals(result);
}
public void leave(ExecutionContext executionContext, Transition transition) {
- TaskMgmtInstance tmi = getTaskMgmtInstance(executionContext.getToken());
- if (tmi.hasBlockingTaskInstances(executionContext.getToken())) {
+ TaskMgmtInstance tmi = executionContext.getTaskMgmtInstance();
+ Token token = executionContext.getToken();
+ if (tmi.hasBlockingTaskInstances(token)) {
throw new IllegalStateException(this + " still has blocking tasks");
}
- removeTaskInstanceSynchronization(executionContext.getToken());
+ removeTaskInstanceSynchronization(token);
super.leave(executionContext, transition);
}
@@ -223,7 +221,7 @@
private boolean isLastToComplete(TaskInstance taskInstance) {
Token token = taskInstance.getToken();
- TaskMgmtInstance tmi = getTaskMgmtInstance(token);
+ TaskMgmtInstance tmi = taskInstance.getTaskMgmtInstance();
boolean isLastToComplete = true;
for (Iterator iter = tmi.getTaskInstances().iterator(); iter.hasNext() && isLastToComplete;) {
@@ -238,7 +236,7 @@
}
public void removeTaskInstanceSynchronization(Token token) {
- TaskMgmtInstance tmi = getTaskMgmtInstance(token);
+ TaskMgmtInstance tmi = token.getProcessInstance().getTaskMgmtInstance();
Collection taskInstances = tmi.getTaskInstances();
if (taskInstances != null) {
for (Iterator iter = taskInstances.iterator(); iter.hasNext();) {
@@ -262,16 +260,9 @@
}
}
- private static TaskMgmtInstance getTaskMgmtInstance(Token token) {
- return token.getProcessInstance().getTaskMgmtInstance();
- }
-
- // getters and setters
- // ///////////////////////////////////////////////////////////////////////////
-
/**
- * is a Map with the tasks, keyed by task-name or an empty map in case no
- * tasks are present in this task-node.
+ * is a Map with the tasks, keyed by task-name or an empty map in case no tasks are present in
+ * this task-node.
*/
public Map getTasksMap() {
Map tasksMap = new HashMap();
@@ -285,8 +276,8 @@
}
/**
- * is the task in this task-node with the given name or null if the given task
- * does not exist in this node.
+ * is the task in this task-node with the given name or null if the given task does not exist
+ * in this node.
*/
public Task getTask(String taskName) {
return (Task) getTasksMap().get(taskName);
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jcr/impl/AbstractJcrServiceFactory.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jcr/impl/AbstractJcrServiceFactory.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jcr/impl/AbstractJcrServiceFactory.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -26,8 +26,6 @@
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
import org.jbpm.JbpmException;
import org.jbpm.svc.Service;
import org.jbpm.svc.ServiceFactory;
@@ -35,44 +33,45 @@
public abstract class AbstractJcrServiceFactory implements ServiceFactory {
private static final long serialVersionUID = 1L;
-
- String username = null;
- String password = null;
- String workspace = null;
+ String username;
+ String password;
+ String workspace;
+
public Service openService() {
- Session session = null;
try {
Repository jcrRepository = getRepository();
- log.debug("opening jcr session "+(username!=null ? username : "")+" "+(workspace!=null ? workspace : ""));
- if ( (username==null)
- && (workspace==null)
- ) {
+ Session session;
+ if (username == null && workspace == null) {
session = jcrRepository.login();
- } else if (username==null) {
+ }
+ else if (username == null) {
session = jcrRepository.login(workspace);
- } else if (workspace==null) {
+ }
+ else if (workspace == null) {
session = jcrRepository.login(getCredentials());
- } else {
+ }
+ else {
session = jcrRepository.login(getCredentials(), workspace);
}
- } catch (Exception e) {
- // NOTE that Error's are not caught because that might halt the JVM and mask the original Error.
- throw new JbpmException("couldn't open session to JCR repository, userId("+username+"), workspace("+workspace+")", e);
+ return new JcrServiceImpl(session);
}
- return new JcrServiceImpl(session);
+ catch (Exception e) {
+ // NOTE that Errors are not caught because that might halt the JVM
+ // and mask the original Error
+ throw new JbpmException("could not login to jcr repository as user " + username
+ + " in workspace " + workspace, e);
+ }
}
Credentials getCredentials() {
- char[] pwdChars = (password!=null ? password.toCharArray() : null );
- Credentials credentials = new SimpleCredentials(username, pwdChars);
- return credentials;
+ char[] pwdChars = password != null ? password.toCharArray() : null;
+ return new SimpleCredentials(username, pwdChars);
}
protected abstract Repository getRepository();
-
+
public void close() {
}
-
- private static Log log = LogFactory.getLog(AbstractJcrServiceFactory.class);
+
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jcr/impl/JcrServiceImpl.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jcr/impl/JcrServiceImpl.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jcr/impl/JcrServiceImpl.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -21,11 +21,9 @@
*/
package org.jbpm.jcr.impl;
+import javax.jcr.RepositoryException;
import javax.jcr.Session;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jbpm.JbpmContext;
import org.jbpm.JbpmException;
import org.jbpm.jcr.JcrService;
import org.jbpm.svc.Services;
@@ -34,13 +32,11 @@
public class JcrServiceImpl implements JcrService {
private static final long serialVersionUID = 1L;
-
- protected Session session = null;
- Services services = null;
+ protected Session session;
+
public JcrServiceImpl(Session session) {
this.session = session;
- this.services = JbpmContext.getCurrentJbpmContext().getServices();
}
public Session getSession() {
@@ -48,43 +44,31 @@
}
public void close() {
- log.debug("closing jcr session");
-
- TxService txService = (services!=null ? services.getTxService() : null);
- if (txService!=null) {
- if (txService.isRollbackOnly()) {
- log.debug("refreshing jcr session because tx service is marked with rollback-only");
- try {
- session.refresh(false);
- } catch (Exception e) {
- // NOTE that Error's are not caught because that might halt the JVM and mask the original Error.
- throw new JbpmException("couldn't refresh(rollback) JCR session", e);
- }
- } else {
- log.debug("committing non-JTA JCR session by invoking the session.save()");
- save();
+ TxService txService = getTxService();
+ if (txService != null && txService.isRollbackOnly()) {
+ try {
+ session.refresh(false);
}
- } else {
- save();
+ catch (RepositoryException e) {
+ // NOTE that Errors are not caught because that might halt the JVM
+ // and mask the original Error
+ throw new JbpmException("could not refresh(rollback) jcr session", e);
+ }
}
-
- try {
- session.logout();
- } catch (Exception e) {
- // NOTE that Error's are not caught because that might halt the JVM and mask the original Error.
- throw new JbpmException("couldn't save JCR session", e);
+ else {
+ try {
+ session.save();
+ }
+ catch (RepositoryException e) {
+ // NOTE that Errors are not caught because that might halt the JVM
+ // and mask the original Error
+ throw new JbpmException("could not save jcr session", e);
+ }
}
+ session.logout();
}
- private void save() {
- log.debug("saving jcr session");
- try {
- session.save();
- } catch (Exception e) {
- // NOTE that Error's are not caught because that might halt the JVM and mask the original Error.
- throw new JbpmException("couldn't save jackrabbit jcr session", e);
- }
+ private static TxService getTxService() {
+ return (TxService) Services.getCurrentService(Services.SERVICENAME_TX);
}
-
- private static Log log = LogFactory.getLog(JcrServiceImpl.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/job/Timer.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/job/Timer.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/job/Timer.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -50,7 +50,6 @@
// then execute the action if there is one
if (action != null) {
- log.debug("executing " + this);
if (graphElement != null) {
graphElement.executeAction(action, executionContext);
}
@@ -85,7 +84,9 @@
repeatDate = businessCalendar.add(repeatDate, interval);
} while (repeatDate.getTime() <= currentTime);
- log.debug("scheduling " + this + " for repeat on " + dueDate);
+ if (log.isDebugEnabled()) {
+ log.debug("scheduling " + this + " for repeat on " + repeatDate);
+ }
dueDate = repeatDate;
// unlock timer so that:
@@ -110,9 +111,6 @@
text.append(id);
}
- // due date
- text.append(',').append(dueDate);
-
return text.append(')').toString();
}
@@ -156,5 +154,5 @@
this.action = action;
}
- private static Log log = LogFactory.getLog(Timer.class);
+ private static final Log log = LogFactory.getLog(Timer.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/job/executor/JobExecutor.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/job/executor/JobExecutor.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/job/executor/JobExecutor.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -50,7 +50,7 @@
public synchronized void start() {
if (!isStarted) {
- log.debug("starting " + name);
+ log.info("starting " + name);
// create thread group
threadGroup = new ThreadGroup(name) {
@@ -73,27 +73,26 @@
startLockMonitorThread();
isStarted = true;
}
- else {
+ else if (log.isDebugEnabled()) {
log.debug("ignoring start: " + name + " already started'");
}
}
/**
- * signals to all threads in this job executor to stop. Threads may be in the
- * middle of processing a job and they will finish that first. Use
- * {@link #stopAndJoin()} in case you want a method that blocks until all the
- * threads are actually finished.
+ * signals to all threads in this job executor to stop. Threads may be in the middle of
+ * processing a job and they will finish that first. Use {@link #stopAndJoin()} in case you
+ * want a method that blocks until all the threads are actually finished.
*
- * @return a list of the stopped threads. In case no threads were stopped an
- * empty list will be returned.
+ * @return a list of the stopped threads. In case no threads were stopped an empty list will
+ * be returned.
*/
public synchronized List stop() {
if (!isStarted) {
- log.debug("ignoring stop, " + name + " not started");
+ if (log.isDebugEnabled()) log.debug("ignoring stop, " + name + " not started");
return Collections.EMPTY_LIST;
}
- log.debug("stopping " + name);
+ log.info("stopping " + name);
isStarted = false;
Thread[] activeThreads = new Thread[threadGroup.activeCount()];
@@ -147,7 +146,7 @@
protected void startThread(String threadName) {
Thread thread = createThread(threadName);
- log.debug("starting " + threadName);
+ if (log.isDebugEnabled()) log.debug("starting " + threadName);
thread.start();
}
@@ -166,7 +165,7 @@
/** @deprecated */
protected synchronized Thread stopThread() {
String threadName = getLastThreadName();
- log.debug("stopping " + threadName);
+ if (log.isDebugEnabled()) log.debug("stopping " + threadName);
Thread thread = (Thread) threads.remove(threadName);
stopThread(thread);
@@ -192,7 +191,7 @@
String threadName = getLockMonitorThreadName();
Thread lockMonitorThread = new LockMonitorThread(threadName, this);
- log.debug("starting " + threadName);
+ if (log.isDebugEnabled()) log.debug("starting " + threadName);
lockMonitorThread.start();
}
@@ -225,8 +224,7 @@
* Method has no effect.
*
* @deprecated call {@link #addMonitoredJobId(String, long)} or
- * {@link #removeMonitoredJobId(String)} to manipulate the set of monitored
- * jobs
+ * {@link #removeMonitoredJobId(String)} to manipulate the set of monitored jobs
*/
public void setMonitoredJobIds(Map monitoredJobIds) {
}
@@ -259,8 +257,7 @@
/**
* This method has no effect.
*
- * @deprecated call {@link #start()} or {@link #stop()} to control this job
- * executor.
+ * @deprecated call {@link #start()} or {@link #stop()} to control this job executor.
*/
public void setStarted(boolean isStarted) {
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/job/executor/JobExecutorThread.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/job/executor/JobExecutorThread.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/job/executor/JobExecutorThread.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -105,22 +105,28 @@
synchronized (jobExecutor) {
JbpmContext jbpmContext = jobExecutor.getJbpmConfiguration().createJbpmContext();
try {
+ // search for acquirable job
String lockOwner = getName();
JobSession jobSession = jbpmContext.getJobSession();
Job firstJob = jobSession.getFirstAcquirableJob(lockOwner);
+ // is there a job?
if (firstJob != null) {
+ // is job exclusive?
if (firstJob.isExclusive()) {
+ // find other exclusive jobs
ProcessInstance processInstance = firstJob.getProcessInstance();
jobs = jobSession.findExclusiveJobs(lockOwner, processInstance);
- if (debug) log.debug("acquiring " + jobs + " for " + processInstance);
+ if (debug) log.debug("acquiring exclusive " + jobs + " for " + processInstance);
}
else {
jobs = Collections.singletonList(firstJob);
if (debug) log.debug("acquiring " + firstJob);
}
+ // acquire jobs
Date lockTime = new Date();
for (Iterator i = jobs.iterator(); i.hasNext();) {
+ // lock job
Job job = (Job) i.next();
job.setLockOwner(lockOwner);
job.setLockTime(lockTime);
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/el/impl/BeanMethod.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/el/impl/BeanMethod.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/el/impl/BeanMethod.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -8,16 +8,16 @@
public class BeanMethod {
- Method method;
-
+ private Method method;
+
public BeanMethod(Method method) {
this.method = method;
}
- public Object invoke(Object object) throws InvocationTargetException, IllegalArgumentException, IllegalAccessException {
- log.debug("invoking expression method '"+method.getName()+"'");
+ public Object invoke(Object object) throws IllegalAccessException, InvocationTargetException {
+ if (log.isDebugEnabled()) log.debug("invoking " + method);
return method.invoke(object, (Object[]) null);
}
-
- private static Log log = LogFactory.getLog(BeanMethod.class);
+
+ private static final Log log = LogFactory.getLog(BeanMethod.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/el/impl/JbpmExpressionEvaluator.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/el/impl/JbpmExpressionEvaluator.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/el/impl/JbpmExpressionEvaluator.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -18,8 +18,7 @@
}
/**
- * @deprecated set configuration entry <code>jbpm.expression.evaluator</code>
- * instead
+ * @deprecated set configuration entry <code>jbpm.expression.evaluator</code> instead
*/
public static void setExpressionEvaluator(ExpressionEvaluator expressionEvaluator) {
JbpmExpressionEvaluator.expressionEvaluator = expressionEvaluator;
@@ -28,8 +27,7 @@
private static VariableResolver variableResolver;
/**
- * @deprecated set configuration entry <code>jbpm.variable.resolver</code>
- * instead
+ * @deprecated set configuration entry <code>jbpm.variable.resolver</code> instead
*/
public static void setVariableResolver(VariableResolver variableResolver) {
JbpmExpressionEvaluator.variableResolver = variableResolver;
@@ -38,24 +36,34 @@
private static FunctionMapper functionMapper;
/**
- * @deprecated set configuration entry <code>jbpm.function.mapper</code>
- * instead
+ * @deprecated set configuration entry <code>jbpm.function.mapper</code> instead
*/
public static void setFunctionMapper(FunctionMapper functionMapper) {
JbpmExpressionEvaluator.functionMapper = functionMapper;
}
public static Object evaluate(String expression, ExecutionContext executionContext) {
- return evaluate(expression, executionContext, getVariableResolver(), getFunctionMapper());
+ return evaluate(expression, executionContext, Object.class);
}
public static Object evaluate(String expression, ExecutionContext executionContext,
+ Class expectedType) {
+ return evaluate(expression, executionContext, expectedType, getVariableResolver(),
+ getFunctionMapper());
+ }
+
+ public static Object evaluate(String expression, ExecutionContext executionContext,
VariableResolver variableResolver, FunctionMapper functionMapper) {
+ return evaluate(expression, executionContext, Object.class, variableResolver,
+ functionMapper);
+ }
+
+ public static Object evaluate(String expression, ExecutionContext executionContext,
+ Class expectedType, VariableResolver variableResolver, FunctionMapper functionMapper) {
ExecutionContext.pushCurrentContext(executionContext);
try {
- String dollarExpression = translateExpressionToDollars(expression);
- return getExpressionEvaluator().evaluate(dollarExpression, Object.class,
- variableResolver, functionMapper);
+ return getExpressionEvaluator().evaluate(translateExpressionToDollars(expression),
+ expectedType, variableResolver, functionMapper);
}
finally {
ExecutionContext.popCurrentContext(executionContext);
@@ -85,7 +93,7 @@
public static FunctionMapper getFunctionMapper() {
return functionMapper != null ? functionMapper
- : Configs.hasObject("jbpm.function.mapper") ?
- (FunctionMapper) Configs.getObject("jbpm.function.mapper") : null;
+ : Configs.hasObject("jbpm.function.mapper") ? (FunctionMapper) Configs.getObject("jbpm.function.mapper")
+ : null;
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/el/impl/JbpmVariableResolver.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/el/impl/JbpmVariableResolver.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/el/impl/JbpmVariableResolver.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -1,6 +1,5 @@
package org.jbpm.jpdl.el.impl;
-
import org.jbpm.JbpmConfiguration;
import org.jbpm.context.exe.ContextInstance;
import org.jbpm.graph.exe.ExecutionContext;
@@ -8,64 +7,50 @@
import org.jbpm.jpdl.el.ELException;
import org.jbpm.jpdl.el.VariableResolver;
import org.jbpm.taskmgmt.exe.SwimlaneInstance;
+import org.jbpm.taskmgmt.exe.TaskInstance;
import org.jbpm.taskmgmt.exe.TaskMgmtInstance;
public class JbpmVariableResolver implements VariableResolver {
+ public JbpmVariableResolver() {
+ }
+
public Object resolveVariable(String name) throws ELException {
ExecutionContext executionContext = ExecutionContext.currentExecutionContext();
- Object value = null;
-
- if ("taskInstance".equals(name)) {
- value = executionContext.getTaskInstance();
- } else if ("processInstance".equals(name)) {
- value = executionContext.getProcessInstance();
+ if ("taskInstance".equals(name)) return executionContext.getTaskInstance();
+ if ("processInstance".equals(name)) return executionContext.getProcessInstance();
+ if ("processDefinition".equals(name)) return executionContext.getProcessDefinition();
+ if ("token".equals(name)) return executionContext.getToken();
+ if ("taskMgmtInstance".equals(name)) return executionContext.getTaskMgmtInstance();
+ if ("contextInstance".equals(name)) return executionContext.getContextInstance();
- } else if ("processDefinition".equals(name)) {
- value = executionContext.getProcessDefinition();
+ TaskInstance taskInstance = executionContext.getTaskInstance();
+ if (taskInstance != null && taskInstance.hasVariableLocally(name)) {
+ return taskInstance.getVariable(name);
+ }
- } else if ("token".equals(name)) {
- value = executionContext.getToken();
-
- } else if ("taskMgmtInstance".equals(name)) {
- value = executionContext.getTaskMgmtInstance();
-
- } else if ("contextInstance".equals(name)) {
- value = executionContext.getContextInstance();
-
- } else if ( (executionContext.getTaskInstance()!=null)
- && (executionContext.getTaskInstance().hasVariableLocally(name))
- ) {
- value = executionContext.getTaskInstance().getVariable(name);
-
- } else {
- ContextInstance contextInstance = executionContext.getContextInstance();
- TaskMgmtInstance taskMgmtInstance = executionContext.getTaskMgmtInstance();
+ ContextInstance contextInstance = executionContext.getContextInstance();
+ if (contextInstance != null) {
Token token = executionContext.getToken();
-
- if ( (contextInstance!=null)
- && (contextInstance.hasVariable(name, token))
- ) {
- value = contextInstance.getVariable(name, token);
-
- } else if ( (contextInstance!=null)
- && (contextInstance.hasTransientVariable(name))
- ) {
- value = contextInstance.getTransientVariable(name);
-
- } else if ( (taskMgmtInstance!=null)
- && (taskMgmtInstance.getSwimlaneInstances()!=null)
- && (taskMgmtInstance.getSwimlaneInstances().containsKey(name))
- ) {
- SwimlaneInstance swimlaneInstance = taskMgmtInstance.getSwimlaneInstance(name);
- value = (swimlaneInstance!=null ? swimlaneInstance.getActorId() : null);
-
- } else if (JbpmConfiguration.Configs.hasObject(name)) {
- value = JbpmConfiguration.Configs.getObject(name);
+ if (contextInstance.hasVariable(name, token)) {
+ return contextInstance.getVariable(name);
}
+ if (contextInstance.hasTransientVariable(name)) {
+ return contextInstance.getTransientVariable(name);
+ }
}
- return value;
+ TaskMgmtInstance taskMgmtInstance = executionContext.getTaskMgmtInstance();
+ if (taskMgmtInstance != null) {
+ SwimlaneInstance swimlaneInstance = taskMgmtInstance.getSwimlaneInstance(name);
+ if (swimlaneInstance != null) return swimlaneInstance.getActorId();
+ }
+
+ if (JbpmConfiguration.Configs.hasObject(name)) {
+ return JbpmConfiguration.Configs.getObject(name);
+ }
+
+ return null;
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/xml/JpdlParser.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/xml/JpdlParser.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/jpdl/xml/JpdlParser.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -47,9 +47,8 @@
import org.jbpm.util.ClassLoaderUtil;
/**
- * Validate an XML document using JAXP techniques and an XML Schema. This helper
- * class wraps the processing of a schema to aid in schema validation throughout
- * the product.
+ * Validate an XML document using JAXP techniques and an XML Schema. This helper class wraps the
+ * processing of a schema to aid in schema validation throughout the product.
*
* @author Tom Baeyens
* @author Jim Rigsbee
@@ -62,8 +61,12 @@
private static Set schemaResources = getDefaultSchemaResources();
private static Object schemaSource;
- public static Document parse(InputSource inputSource,
- ProblemListener problemListener) throws DocumentException {
+ private JpdlParser() {
+ // hide default constructor to prevent instantiation
+ }
+
+ public static Document parse(InputSource inputSource, ProblemListener problemListener)
+ throws DocumentException {
try {
SAXReader saxReader = createSaxReader(problemListener);
return saxReader.read(inputSource);
@@ -73,8 +76,7 @@
}
}
- public static SAXReader createSaxReader(ProblemListener problemListener)
- throws SAXException {
+ public static SAXReader createSaxReader(ProblemListener problemListener) throws SAXException {
XMLReader xmlReader = createXmlReader();
SAXReader saxReader = new SAXReader(xmlReader);
saxReader.setErrorHandler(new JpdlErrorHandler(problemListener));
@@ -87,13 +89,12 @@
saxParser = saxParserFactory.newSAXParser();
}
catch (ParserConfigurationException e) {
- // validating, namespace-aware sax parsr should be available
+ // validating, namespace-aware sax parser should be available
throw new AssertionError(e);
}
try {
- saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
- "http://www.w3.org/2001/XMLSchema");
+ saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
}
catch (SAXException e) {
log.warn("failed to set schema language to xml schema", e);
@@ -101,8 +102,7 @@
Object schemaSource = getSchemaSource();
try {
- saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
- schemaSource);
+ saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaSource);
}
catch (SAXException e) {
log.warn("failed to set schema source to " + schemaSource, e);
@@ -110,8 +110,7 @@
XMLReader xmlReader = saxParser.getXMLReader();
try {
- xmlReader.setFeature("http://apache.org/xml/features/validation/dynamic",
- true);
+ xmlReader.setFeature("http://apache.org/xml/features/validation/dynamic", true);
}
catch (SAXException e) {
log.warn("failed to enable dynamic validation", e);
@@ -128,19 +127,18 @@
URL schemaURL = classLoader.getResource(schemaResource);
if (schemaURL != null) {
String schemaLocation = schemaURL.toString();
- log.debug("found schema resource " + schemaResource);
+ if (log.isDebugEnabled()) log.debug("located schema resource " + schemaResource);
schemaLocations.add(schemaLocation);
}
}
- schemaSource =
- schemaLocations.toArray(new String[schemaLocations.size()]);
+ schemaSource = schemaLocations.toArray(new String[schemaLocations.size()]);
}
return schemaSource;
}
static class JpdlErrorHandler implements ErrorHandler, Serializable {
- private ProblemListener problemListener = null;
+ private ProblemListener problemListener;
private static final long serialVersionUID = 1L;
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/logging/exe/LoggingInstance.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/logging/exe/LoggingInstance.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/logging/exe/LoggingInstance.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -21,118 +21,104 @@
*/
package org.jbpm.logging.exe;
-import java.util.*;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
-import org.apache.commons.logging.*;
-import org.jbpm.graph.log.*;
-import org.jbpm.logging.log.*;
-import org.jbpm.module.exe.*;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.jbpm.logging.log.CompositeLog;
+import org.jbpm.logging.log.ProcessLog;
+import org.jbpm.module.exe.ModuleInstance;
import org.jbpm.util.Clock;
/**
- * non persisted class that collects {@link org.jbpm.logging.log.ProcessLog}s
- * during process execution. When the process instance gets saved, the
- * process logs will be saved by the {@link org.jbpm.db.LoggingSession}.
+ * non persisted class that collects {@link org.jbpm.logging.log.ProcessLog}s during process
+ * execution. When the process instance gets saved, the process logs will be saved by the
+ * {@link org.jbpm.db.LoggingSession}.
*/
public class LoggingInstance extends ModuleInstance {
private static final long serialVersionUID = 1L;
-
- List logs = new ArrayList();
- transient LinkedList compositeLogStack = new LinkedList();
-
+
+ private List logs = new ArrayList();
+ private transient List compositeLogStack = new ArrayList();
+
public LoggingInstance() {
}
-
+
public void startCompositeLog(CompositeLog compositeLog) {
addLog(compositeLog);
- compositeLogStack.addFirst(compositeLog);
+ compositeLogStack.add(compositeLog);
}
-
+
public void endCompositeLog() {
- compositeLogStack.removeFirst();
+ compositeLogStack.remove(compositeLogStack.size() - 1);
}
public void addLog(ProcessLog processLog) {
if (!compositeLogStack.isEmpty()) {
- CompositeLog currentCompositeLog = (CompositeLog) compositeLogStack.getFirst();
- processLog.setParent(currentCompositeLog);
- currentCompositeLog.addChild(processLog);
+ CompositeLog compositeLog = (CompositeLog) compositeLogStack.get(compositeLogStack.size() - 1);
+ compositeLog.addChild(processLog);
+ processLog.setParent(compositeLog);
}
processLog.setDate(Clock.getCurrentTime());
-
logs.add(processLog);
}
-
+
public List getLogs() {
return logs;
}
/**
- * get logs, filetered by log type.
+ * get logs, filtered by log type.
*/
public List getLogs(Class filterClass) {
return getLogs(logs, filterClass);
}
-
+
public static List getLogs(Collection logs, Class filterClass) {
List filteredLogs = new ArrayList();
- if (logs!=null) {
- Iterator iter = logs.iterator();
- while (iter.hasNext()) {
+ if (logs != null) {
+ for (Iterator iter = logs.iterator(); iter.hasNext();) {
Object log = iter.next();
- if (filterClass.isAssignableFrom(log.getClass())) {
- filteredLogs.add(log);
- }
+ if (filterClass.isAssignableFrom(log.getClass())) filteredLogs.add(log);
}
}
return filteredLogs;
}
- LinkedList getCompositeLogStack() {
+ List getCompositeLogStack() {
return compositeLogStack;
}
- List getCurrentOperationReversedActionLogs() {
- List actionLogs = new ArrayList();
- ProcessLog operationLog = (ProcessLog) compositeLogStack.getFirst();
- ListIterator listIterator = logs.listIterator(logs.size());
- ProcessLog processLog = (ProcessLog) listIterator.previous();
- while ( (listIterator.hasNext())
- && (processLog!=operationLog) ) {
- if (processLog instanceof ActionLog) {
- actionLogs.add(0, processLog);
- }
- }
- return actionLogs;
- }
-
public void logLogs() {
- Iterator iter = logs.iterator();
- while (iter.hasNext()) {
+ for (Iterator iter = logs.iterator(); iter.hasNext();) {
ProcessLog processLog = (ProcessLog) iter.next();
- if (processLog.getParent()==null) {
- logLog("+-", processLog);
- }
+ if (processLog.getParent() == null) logLog("+-", processLog);
}
}
- void logLog(String indentation, ProcessLog processLog) {
- log.debug(processLog.getToken()+"["+processLog.getIndex()+"] "+processLog+" on "+processLog.getToken());
+ private void logLog(String indentation, ProcessLog processLog) {
+ log.debug(processLog.getToken() + "[" + processLog.getIndex() + "] " + processLog + " on "
+ + processLog.getToken());
if (processLog instanceof CompositeLog) {
CompositeLog compositeLog = (CompositeLog) processLog;
- if (compositeLog.getChildren()!=null) {
- Iterator iter = compositeLog.getChildren().iterator();
- while (iter.hasNext()) {
- logLog("| "+indentation, (ProcessLog) iter.next());
+ if (compositeLog.getChildren() != null) {
+ for (Iterator iter = compositeLog.getChildren().iterator(); iter.hasNext();) {
+ logLog("| " + indentation, (ProcessLog) iter.next());
}
}
}
}
-
- Object readResolve() {
- compositeLogStack = new LinkedList();
- return this;
+
+ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
+ in.defaultReadObject();
+ compositeLogStack = new ArrayList();
}
private static final Log log = LogFactory.getLog(LoggingInstance.class);
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/logging/log/CompositeLog.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/logging/log/CompositeLog.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/logging/log/CompositeLog.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -25,10 +25,10 @@
import java.util.List;
public class CompositeLog extends ProcessLog {
-
+
private static final long serialVersionUID = 1L;
- List children = null;
+ List children;
public CompositeLog() {
}
@@ -36,6 +36,7 @@
public List getChildren() {
return children;
}
+
public void setChildren(List children) {
this.children = children;
}
@@ -45,7 +46,7 @@
}
public void addChild(ProcessLog processLog) {
- if (children==null) children = new ArrayList();
+ if (children == null) children = new ArrayList();
children.add(processLog);
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/logging/log/ProcessLog.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/logging/log/ProcessLog.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/logging/log/ProcessLog.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -21,38 +21,36 @@
*/
package org.jbpm.logging.log;
-import java.io.*;
-import java.util.*;
-import org.jbpm.graph.exe.*;
+import java.io.Serializable;
+import java.util.Date;
+import java.util.List;
+import org.jbpm.graph.exe.Token;
+
public abstract class ProcessLog implements Serializable {
-
+
private static final long serialVersionUID = 1L;
- long id = 0;
+ long id;
protected int index = -1;
- protected Date date = null;
- protected Token token = null;
- protected CompositeLog parent = null;
-
+ protected Date date;
+ protected Token token;
+ protected CompositeLog parent;
+
public ProcessLog() {
}
-
+
/**
- * provides a text description for this update
- * which can be used e.g. in the admin web console.
+ * provides a text description for this update which can be used e.g. in the admin web
+ * console.
*/
public abstract String toString();
-
+
public String getActorId() {
- String actorId = null;
- if (parent!=null) {
- // AuthenticationLog overriddes the getActorId
- actorId = parent.getActorId();
- }
- return actorId;
+ // AuthenticationLog overrides this method
+ return parent != null ? parent.getActorId() : null;
}
-
+
public void setToken(Token token) {
this.token = token;
}
@@ -60,27 +58,35 @@
public void setParent(CompositeLog parent) {
this.parent = parent;
}
+
public long getId() {
return id;
}
+
public Date getDate() {
return date;
}
+
public void setDate(Date date) {
this.date = date;
}
+
public CompositeLog getParent() {
return parent;
}
+
public Token getToken() {
return token;
}
+
public void setIndex(int index) {
this.index = index;
}
+
public int getIndex() {
return index;
}
+
public List getChildren() {
return null;
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/mail/Mail.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/mail/Mail.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/mail/Mail.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -1,11 +1,11 @@
package org.jbpm.mail;
+import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
-import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -21,6 +21,8 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.w3c.dom.Element;
+
import org.jbpm.JbpmConfiguration;
import org.jbpm.JbpmException;
import org.jbpm.graph.def.ActionHandler;
@@ -33,15 +35,15 @@
public class Mail implements ActionHandler {
- String template;
- String actors;
- String to;
- String bcc;
- String bccActors;
- String subject;
- String text;
+ private String template;
+ private String actors;
+ private String to;
+ private String bcc;
+ private String bccActors;
+ private String subject;
+ private String text;
- ExecutionContext executionContext;
+ private ExecutionContext executionContext;
private static final long serialVersionUID = 1L;
@@ -74,47 +76,98 @@
public List getRecipients() {
List recipients = new ArrayList();
- if (actors != null) {
- String evaluatedActors = evaluate(actors);
- List tokenizedActors = tokenize(evaluatedActors);
- if (tokenizedActors != null) {
- recipients.addAll(resolveAddresses(tokenizedActors));
- }
- }
- if (to != null) {
- String resolvedTo = evaluate(to);
- recipients.addAll(tokenize(resolvedTo));
- }
+ if (actors != null) recipients.addAll(evaluateActors(actors));
+ if (to != null) recipients.addAll(evaluateAddresses(to));
return recipients;
}
public List getBccRecipients() {
List recipients = new ArrayList();
- if (bccActors != null) {
- String evaluatedActors = evaluate(bccActors);
- List tokenizedActors = tokenize(evaluatedActors);
- if (tokenizedActors != null) {
- recipients.addAll(resolveAddresses(tokenizedActors));
- }
- }
- if (bcc != null) {
- String resolvedTo = evaluate(bcc);
- recipients.addAll(tokenize(resolvedTo));
- }
+ if (bccActors != null) recipients.addAll(evaluateActors(bccActors));
+ if (bcc != null) recipients.addAll(evaluateAddresses(bcc));
if (JbpmConfiguration.Configs.hasObject("jbpm.mail.bcc.address")) {
recipients.addAll(tokenize(JbpmConfiguration.Configs.getString("jbpm.mail.bcc.address")));
}
return recipients;
}
+ private Collection evaluateActors(String expression) {
+ Object value = evaluate(expression, Object.class);
+ List actors;
+ if (value instanceof String) {
+ actors = tokenize((String) value);
+ }
+ else if (value instanceof String[]) {
+ actors = Arrays.asList((String[]) value);
+ }
+ else if (value instanceof List) {
+ actors = (List) value;
+ }
+ else if (value instanceof Collection) {
+ actors = new ArrayList((Collection) value);
+ }
+ else {
+ throw new JbpmException("could not resolve actors from expression: " + expression);
+ }
+ return resolveAddresses(actors);
+ }
+
+ protected Collection resolveAddresses(List actorIds) {
+ AddressResolver addressResolver = (AddressResolver) JbpmConfiguration.Configs
+ .getObject("jbpm.mail.address.resolver");
+
+ List addresses = new ArrayList();
+ for (Iterator iter = actorIds.iterator(); iter.hasNext();) {
+ String actorId = (String) iter.next();
+ Object result = addressResolver.resolveAddress(actorId);
+
+ if (result instanceof String) {
+ addresses.add(result);
+ }
+ else if (result instanceof Collection) {
+ addresses.addAll((Collection) result);
+ }
+ else if (result instanceof String[]) {
+ addresses.addAll(Arrays.asList((String[]) result));
+ }
+ else if (result == null) {
+ // no such actor or actor has no address
+ }
+ else {
+ throw new JbpmException(addressResolver + " returned " + result
+ + " instead of single string, string array or collection");
+ }
+ }
+ return addresses;
+ }
+
+ private Collection evaluateAddresses(String expression) {
+ Object value = evaluate(expression, Object.class);
+ if (value instanceof String) return tokenize((String) value);
+ if (value instanceof String[]) return Arrays.asList((String[]) value);
+ if (value instanceof Collection) return (Collection) value;
+ throw new JbpmException(expression + " returned " + value
+ + " instead of comma-separated string, string array or collection");
+ }
+
+ protected List tokenize(String text) {
+ return text != null ? Arrays.asList(text.split("[;:]+")) : null;
+ }
+
+ private Object evaluate(String expression, Class expectedType) {
+ VariableResolver variableResolver = new MailVariableResolver(templateVariables, JbpmExpressionEvaluator
+ .getVariableResolver());
+ return JbpmExpressionEvaluator
+ .evaluate(expression, executionContext, expectedType, variableResolver, JbpmExpressionEvaluator
+ .getFunctionMapper());
+ }
+
public String getSubject() {
- if (subject == null) return null;
- return evaluate(subject);
+ return subject != null ? (String) evaluate(subject, String.class) : null;
}
public String getText() {
- if (text == null) return null;
- return evaluate(text);
+ return text != null ? (String) evaluate(text, String.class) : null;
}
public String getFromAddress() {
@@ -127,24 +180,13 @@
public void send() {
if (template != null) {
Properties properties = getMailTemplateProperties(template);
- if (actors == null) {
- actors = properties.getProperty("actors");
- }
- if (to == null) {
- to = properties.getProperty("to");
- }
- if (subject == null) {
- subject = properties.getProperty("subject");
- }
- if (text == null) {
- text = properties.getProperty("text");
- }
- if (bcc == null) {
- bcc = properties.getProperty("bcc");
- }
- if (bccActors == null) {
- bccActors = properties.getProperty("bccActors");
- }
+
+ if (actors == null) actors = properties.getProperty("actors");
+ if (to == null) to = properties.getProperty("to");
+ if (subject == null) subject = properties.getProperty("subject");
+ if (text == null) text = properties.getProperty("text");
+ if (bcc == null) bcc = properties.getProperty("bcc");
+ if (bccActors == null) bccActors = properties.getProperty("bccActors");
}
send(getMailServerProperties(), getFromAddress(), getRecipients(), getBccRecipients(), getSubject(), getText());
@@ -157,28 +199,26 @@
public static void send(Properties mailServerProperties, String fromAddress, List recipients,
List bccRecipients, String subject, String text) {
+ // if there are no recipients, skip mail sending
if ((recipients == null || recipients.isEmpty())
- && (bccRecipients == null || bccRecipients.isEmpty())) {
- log.debug("skipping mail because there are no recipients");
- return;
- }
+ && (bccRecipients == null || bccRecipients.isEmpty())) return;
- for (int retries = 5;; retries--) {
+ for (int retries = 5; retries >= 0; retries--) {
try {
sendMailInternal(mailServerProperties, fromAddress, recipients, bccRecipients, subject, text);
break;
}
- catch (MessagingException msgex) {
- if (retries == 0) throw new JbpmException("cannot send email", msgex);
+ catch (MessagingException me) {
+ if (retries == 0) throw new JbpmException("cannot send email", me);
- log.error("cannot send mail (" + retries + " retries left): " + msgex.getMessage());
+ log.warn("cannot send mail (" + retries + " retries left): " + me.getMessage());
try {
Thread.sleep(1000);
}
- catch (InterruptedException e) {
+ catch (InterruptedException ie) {
// reassert interruption
Thread.currentThread().interrupt();
- throw new JbpmException("cannot send email", msgex);
+ throw new JbpmException("cannot send email", me);
}
}
}
@@ -186,83 +226,52 @@
private static void sendMailInternal(Properties mailServerProperties, String fromAddress,
List recipients, List bccRecipients, String subject, String text) throws MessagingException {
- log.debug("sending email to '" + recipients + "' "
- + (bccRecipients != null ? "and in bcc to '" + bccRecipients + "' " : "") + "about '"
- + subject + "'");
+ if (log.isDebugEnabled()) {
+ StringBuffer message = new StringBuffer("sending email ");
+ if (recipients != null) message.append(recipients);
+ if (bccRecipients != null) message.append(" bcc ").append(bccRecipients);
+ if (fromAddress != null) message.append(" from '").append(fromAddress).append(')');
+ if (subject != null) message.append(" about '").append(subject).append(')');
+ log.debug(message.toString());
+ }
+
Session session = Session.getDefaultInstance(mailServerProperties, null);
MimeMessage message = new MimeMessage(session);
- if (fromAddress != null) {
- message.setFrom(new InternetAddress(fromAddress));
- }
- Iterator iter = recipients.iterator();
- while (iter.hasNext()) {
+ // from
+ if (fromAddress != null) message.setFrom(new InternetAddress(fromAddress));
+ // to
+ for (Iterator iter = recipients.iterator(); iter.hasNext();) {
InternetAddress recipient = new InternetAddress((String) iter.next());
message.addRecipient(Message.RecipientType.TO, recipient);
}
+ // bcc
if (bccRecipients != null) {
- iter = bccRecipients.iterator();
- while (iter.hasNext()) {
+ for (Iterator iter = bccRecipients.iterator(); iter.hasNext();) {
InternetAddress recipient = new InternetAddress((String) iter.next());
message.addRecipient(Message.RecipientType.BCC, recipient);
}
}
- if (subject != null) {
- message.setSubject(subject);
- }
- if (text != null) {
- message.setText(text);
- }
- message.setSentDate(new Date());
+ // subject
+ if (subject != null) message.setSubject(subject);
+ // text
+ if (text != null) message.setText(text);
Transport.send(message);
}
- protected List tokenize(String text) {
- if (text == null) return null;
-
- String[] tokens = text.split("[;:]+");
- return Arrays.asList(tokens);
- }
-
- protected Collection resolveAddresses(List actorIds) {
- List emailAddresses = new ArrayList();
- for (Iterator iter = actorIds.iterator(); iter.hasNext();) {
- String actorId = (String) iter.next();
- AddressResolver addressResolver = (AddressResolver) JbpmConfiguration.Configs.getObject("jbpm.mail.address.resolver");
- Object resolvedAddresses = addressResolver.resolveAddress(actorId);
- if (resolvedAddresses != null) {
- if (resolvedAddresses instanceof String) {
- emailAddresses.add(resolvedAddresses);
- }
- else if (resolvedAddresses instanceof Collection) {
- emailAddresses.addAll((Collection) resolvedAddresses);
- }
- else if (resolvedAddresses instanceof String[]) {
- emailAddresses.addAll(Arrays.asList((String[]) resolvedAddresses));
- }
- else {
- throw new JbpmException("Address resolver '" + addressResolver + "' returned '"
- + resolvedAddresses.getClass().getName()
- + "' instead of a String, Collection or String-array: " + resolvedAddresses);
- }
- }
- }
- return emailAddresses;
- }
-
- Properties getMailServerProperties() {
+ private Properties getMailServerProperties() {
Properties mailServerProperties = new Properties();
if (JbpmConfiguration.Configs.hasObject("resource.mail.properties")) {
- String mailServerPropertiesResource = JbpmConfiguration.Configs.getString("resource.mail.properties");
+ String mailServerPropertiesResource = JbpmConfiguration.Configs
+ .getString("resource.mail.properties");
try {
InputStream mailServerStream = ClassLoaderUtil.getStream(mailServerPropertiesResource);
mailServerProperties.load(mailServerStream);
}
- catch (Exception e) {
- throw new JbpmException(
- "could not get configuration properties for jbpm mail server from resource '"
- + mailServerPropertiesResource + "'", e);
+ catch (IOException e) {
+ throw new JbpmException("could not load mail server properties from resource: "
+ + mailServerPropertiesResource, e);
}
}
else if (JbpmConfiguration.Configs.hasObject("jbpm.mail.smtp.host")) {
@@ -270,24 +279,27 @@
mailServerProperties.put("mail.smtp.host", smtpServer);
}
else {
- log.error("couldn't get mail properties");
+ log.error("could not get mail properties");
}
return mailServerProperties;
}
- static Map templates = null;
- static Map templateVariables = null;
+ private static Map templates;
+ private static Map templateVariables;
- synchronized Properties getMailTemplateProperties(String templateName) {
+ private synchronized Properties getMailTemplateProperties(String templateName) {
if (templates == null) {
templates = new HashMap();
- String mailTemplatesResource = JbpmConfiguration.Configs.getString("resource.mail.templates");
- org.w3c.dom.Element mailTemplatesElement = XmlUtil.parseXmlResource(mailTemplatesResource, false)
+ String mailTemplatesResource = JbpmConfiguration.Configs
+ .getString("resource.mail.templates");
+
+ Element mailTemplatesElement = XmlUtil
+ .parseXmlResource(mailTemplatesResource, true)
.getDocumentElement();
- List mailTemplateElements = XmlUtil.elements(mailTemplatesElement, "mail-template");
- for (Iterator iter = mailTemplateElements.iterator(); iter.hasNext();) {
- org.w3c.dom.Element mailTemplateElement = (org.w3c.dom.Element) iter.next();
+ for (Iterator iter = XmlUtil.elementIterator(mailTemplatesElement, "mail-template"); iter
+ .hasNext();) {
+ Element mailTemplateElement = (Element) iter.next();
Properties templateProperties = new Properties();
addTemplateProperty(mailTemplateElement, "actors", templateProperties);
@@ -301,38 +313,30 @@
}
templateVariables = new HashMap();
- List variableElements = XmlUtil.elements(mailTemplatesElement, "variable");
- for (Iterator iter = variableElements.iterator(); iter.hasNext();) {
- org.w3c.dom.Element variableElement = (org.w3c.dom.Element) iter.next();
- templateVariables.put(variableElement.getAttribute("name"), variableElement.getAttribute("value"));
+ for (Iterator iter = XmlUtil.elementIterator(mailTemplatesElement, "variable"); iter
+ .hasNext();) {
+ Element variableElement = (Element) iter.next();
+ templateVariables.put(variableElement.getAttribute("name"), variableElement
+ .getAttribute("value"));
}
}
return (Properties) templates.get(templateName);
}
- void addTemplateProperty(org.w3c.dom.Element mailTemplateElement, String property,
+ private void addTemplateProperty(Element mailTemplateElement, String property,
Properties templateProperties) {
- org.w3c.dom.Element element = XmlUtil.element(mailTemplateElement, property);
+ Element element = XmlUtil.element(mailTemplateElement, property);
if (element != null) {
templateProperties.put(property, XmlUtil.getContentText(element));
}
}
- String evaluate(String expression) {
- if (expression == null) {
- return null;
- }
- VariableResolver variableResolver = JbpmExpressionEvaluator.getVariableResolver();
- if (variableResolver != null) {
- variableResolver = new MailVariableResolver(templateVariables, variableResolver);
- }
- return (String) JbpmExpressionEvaluator.evaluate(expression, executionContext, variableResolver, JbpmExpressionEvaluator.getFunctionMapper());
- }
+ private static class MailVariableResolver implements VariableResolver, Serializable {
- class MailVariableResolver implements VariableResolver, Serializable {
+ private Map templateVariables;
+ private VariableResolver variableResolver;
+
private static final long serialVersionUID = 1L;
- Map templateVariables = null;
- VariableResolver variableResolver = null;
public MailVariableResolver(Map templateVariables, VariableResolver variableResolver) {
this.templateVariables = templateVariables;
@@ -343,7 +347,7 @@
if (templateVariables != null && templateVariables.containsKey(pName)) {
return templateVariables.get(pName);
}
- return variableResolver.resolveVariable(pName);
+ return variableResolver != null ? variableResolver.resolveVariable(pName) : null;
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/msg/db/DbMessageService.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/msg/db/DbMessageService.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/msg/db/DbMessageService.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -32,9 +32,9 @@
private static final long serialVersionUID = 1L;
- final JobSession jobSession;
- final JobExecutor jobExecutor;
- boolean hasProducedJobs;
+ private final JobSession jobSession;
+ private final JobExecutor jobExecutor;
+ private boolean hasProducedJobs;
public DbMessageService() {
JbpmContext jbpmContext = JbpmContext.getCurrentJbpmContext();
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/db/DbPersistenceService.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/db/DbPersistenceService.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/db/DbPersistenceService.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -100,20 +100,20 @@
Connection connection = getConnection(false);
if (isCurrentSessionEnabled) {
session = getSessionFactory().getCurrentSession();
+ mustSessionBeFlushed = false;
mustSessionBeClosed = false;
- mustSessionBeFlushed = false;
mustConnectionBeClosed = false;
}
else if (connection != null) {
session = getSessionFactory().openSession(connection);
+ mustSessionBeFlushed = true;
mustSessionBeClosed = true;
- mustSessionBeFlushed = true;
mustConnectionBeClosed = false;
}
else {
session = getSessionFactory().openSession();
+ mustSessionBeFlushed = true;
mustSessionBeClosed = true;
- mustSessionBeFlushed = true;
mustConnectionBeClosed = false;
}
@@ -124,17 +124,10 @@
public void beginTransaction() {
transaction = session.beginTransaction();
+ mustSessionBeFlushed = false;
}
public void endTransaction() {
- if (isTransactionManagedExternally()) {
- if (session != null && getTxService().isRollbackOnly()) {
- throw new JbpmException(
- "cannot honor rollback request under an external transaction manager");
- }
- return;
- }
-
if (!isTransactionRollbackOnly()) {
Exception commitException = commit();
if (commitException != null) {
@@ -207,16 +200,15 @@
}
protected boolean isTransactionManagedExternally() {
- return !isTransactionEnabled || transaction == null;
+ return !isTransactionEnabled;
}
protected boolean isTransactionRollbackOnly() {
- return getTxService().isRollbackOnly();
+ TxService txService = getTxService();
+ return txService != null ? txService.isRollbackOnly() : false;
}
public void close() {
- endTransaction();
-
Exception flushException = flushSession();
if (flushException != null) {
// JBPM-1465: here the transaction is already committed or rolled back
@@ -227,43 +219,48 @@
throw new JbpmPersistenceException("hibernate flush session failed", flushException);
}
+ endTransaction();
+
Exception closeSessionException = closeSession();
if (closeSessionException != null) {
closeConnection();
- throw new JbpmPersistenceException("hibernate close session failed",
- closeSessionException);
+ throw new JbpmPersistenceException("hibernate close session failed", closeSessionException);
}
Exception closeConnectionException = closeConnection();
if (closeConnectionException != null) {
- throw new JbpmPersistenceException("hibernate close connection failed",
- closeConnectionException);
+ throw new JbpmPersistenceException("hibernate close connection failed", closeConnectionException);
}
}
protected Exception commit() {
- mustSessionBeFlushed = false; // commit does a flush anyway
- try {
- transaction.commit();
- return null;
+ if (!isTransactionManagedExternally() && transaction != null) {
+ try {
+ transaction.commit();
+ }
+ catch (HibernateException e) {
+ // avoid log and throw antipattern
+ return e;
+ }
}
- catch (HibernateException e) {
- // avoid log and throw antipattern
- return e;
- }
+ return null;
}
protected Exception rollback() {
- // flushing updates that will be rolled back is not very clever :-)
- mustSessionBeFlushed = false;
- try {
- transaction.rollback();
- return null;
+ // if there is an external transaction manager, throw an exception at it
+ if (isTransactionManagedExternally()) {
+ throw new JbpmPersistenceException("cannot honor rollback request under external transaction manager");
}
- catch (HibernateException e) {
- // avoid log and throw antipattern
- return e;
+ if (transaction != null) {
+ try {
+ transaction.rollback();
+ }
+ catch (HibernateException e) {
+ // avoid log and throw antipattern
+ return e;
+ }
}
+ return null;
}
private Exception flushSession() {
@@ -322,7 +319,7 @@
catch (HibernateException e) {
// NOTE that Errors are not caught because that might halt the JVM
// and mask the original Error.
- throw new JbpmPersistenceException("couldn't assign id to " + object, e);
+ throw new JbpmPersistenceException("could not assign id to " + object, e);
}
}
@@ -377,9 +374,13 @@
if (customSession != null) return customSession;
}
try {
- Constructor constructor = sessionClass.getConstructor(new Class[] { Session.class });
+ Constructor constructor = sessionClass.getConstructor(new Class[] {
+ Session.class
+ });
try {
- Object customSession = constructor.newInstance(new Object[] { session });
+ Object customSession = constructor.newInstance(new Object[] {
+ session
+ });
customSessions.put(sessionClass, customSession);
return customSession;
}
@@ -394,8 +395,11 @@
}
}
catch (NoSuchMethodException e) {
- throw new JbpmException("constructor not found: " + sessionClass.getName() + '('
- + Session.class.getName() + ')', e);
+ throw new JbpmException("constructor not found: "
+ + sessionClass.getName()
+ + '('
+ + Session.class.getName()
+ + ')', e);
}
}
@@ -407,14 +411,15 @@
* @deprecated use {@link TxService#isRollbackOnly()} instead
*/
public boolean isRollbackOnly() {
- return getTxService().isRollbackOnly();
+ return isTransactionRollbackOnly();
}
/**
* @deprecated use {@link TxService#setRollbackOnly()} instead
*/
public void setRollbackOnly() {
- getTxService().setRollbackOnly();
+ TxService txService = getTxService();
+ if (txService != null) txService.setRollbackOnly();
}
/**
@@ -428,8 +433,8 @@
setRollbackOnly();
}
- private TxService getTxService() {
- return (TxService) Services.getCurrentService(Services.SERVICENAME_TX);
+ private static TxService getTxService() {
+ return (TxService) Services.getCurrentService(Services.SERVICENAME_TX, false);
}
/**
@@ -537,8 +542,9 @@
public static boolean isLockingException(Exception exception) {
for (Throwable t = exception; t != null; t = t.getCause()) {
- if (t instanceof StaleStateException || t instanceof LockAcquisitionException)
+ if (t instanceof StaleStateException || t instanceof LockAcquisitionException) {
return true;
+ }
}
return false;
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/db/StaleObjectLogConfigurer.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/db/StaleObjectLogConfigurer.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/db/StaleObjectLogConfigurer.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -21,18 +21,13 @@
*/
package org.jbpm.persistence.db;
-import java.io.Serializable;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class StaleObjectLogConfigurer {
- private static final Log log =
- LogFactory.getLog(StaleObjectLogConfigurer.class);
- private static Log staleObjectExceptionsLog =
- LogFactory.getLog(StaleObjectLogConfigurer.class.getName()
- + ".staleObjectExceptions");
+ private static Log staleObjectExceptionsLog = LogFactory
+ .getLog(StaleObjectLogConfigurer.class.getName() + ".staleObjectExceptions");
private StaleObjectLogConfigurer() {
// hide default constructor to prevent instantiation
@@ -43,19 +38,24 @@
}
public static void hideStaleObjectExceptions() {
+ Log log = LogFactory.getLog(StaleObjectLogConfigurer.class);
+
+ // check whether stale state exceptions are already hidden
if (staleObjectExceptionsLog instanceof LogWrapper) {
- log.debug("stale object exceptions already hidden from logging");
+ if (log.isDebugEnabled()) {
+ log.debug("stale object exceptions already hidden from logging");
+ }
return;
}
- log.info("stale object exceptions will be hidden from logging");
+ log.info("stale object exceptions will not be logged");
staleObjectExceptionsLog = new LogWrapper(staleObjectExceptionsLog);
}
- static class LogWrapper implements Log, Serializable {
- Log delegate;
- private static final long serialVersionUID = 1L;
+ private static class LogWrapper implements Log {
+ private final Log delegate;
+
LogWrapper(Log delegate) {
this.delegate = delegate;
}
@@ -99,7 +99,7 @@
}
public boolean isDebugEnabled() {
- return delegate.isDebugEnabled();
+ return false;
}
public boolean isErrorEnabled() {
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/jta/JtaDbPersistenceService.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/jta/JtaDbPersistenceService.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/jta/JtaDbPersistenceService.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -27,6 +27,7 @@
import javax.transaction.RollbackException;
import javax.transaction.Status;
import javax.transaction.SystemException;
+import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import org.apache.commons.logging.Log;
@@ -35,6 +36,7 @@
import org.hibernate.util.JTAHelper;
import org.jbpm.JbpmException;
+import org.jbpm.persistence.JbpmPersistenceException;
import org.jbpm.persistence.db.DbPersistenceService;
public class JtaDbPersistenceService extends DbPersistenceService {
@@ -42,15 +44,11 @@
private UserTransaction transaction;
private static final long serialVersionUID = 1L;
+ private static final Log log = LogFactory.getLog(JtaDbPersistenceService.class);
- private static Log log = LogFactory.getLog(JtaDbPersistenceService.class);
-
public JtaDbPersistenceService(JtaDbPersistenceServiceFactory persistenceServiceFactory) {
super(persistenceServiceFactory);
-
- if (!isTransactionActive()) {
- beginTransaction();
- }
+ if (!isTransactionActive()) beginTransaction();
}
public boolean isTransactionActive() {
@@ -63,15 +61,14 @@
}
protected boolean isTransactionRollbackOnly() {
- return super.isTransactionRollbackOnly() ||
- JTAHelper.isMarkedForRollback(getTransactionStatus());
+ return super.isTransactionRollbackOnly()
+ || JTAHelper.isMarkedForRollback(getTransactionStatus());
}
public void beginTransaction() {
try {
JtaDbPersistenceServiceFactory jtaFactory = (JtaDbPersistenceServiceFactory) persistenceServiceFactory;
transaction = jtaFactory.getUserTransaction();
- log.debug("beginning " + transaction);
transaction.begin();
}
catch (NotSupportedException e) {
@@ -84,45 +81,65 @@
private int getTransactionStatus() {
try {
- return transaction.getStatus();
+ if (transaction != null) {
+ return transaction.getStatus();
+ }
+ else {
+ SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) getSessionFactory();
+ TransactionManager transactionManager = sessionFactory.getTransactionManager();
+ if (transactionManager != null) return transactionManager.getStatus();
+ }
}
catch (SystemException e) {
log.error("could not get transaction status", e);
- return Status.STATUS_UNKNOWN;
}
+ return Status.STATUS_UNKNOWN;
}
protected Exception commit() {
- log.debug("committing " + transaction);
- try {
- transaction.commit();
- return null;
+ if (transaction != null) {
+ try {
+ transaction.commit();
+ }
+ catch (RollbackException e) {
+ return e;
+ }
+ catch (HeuristicMixedException e) {
+ return e;
+ }
+ catch (HeuristicRollbackException e) {
+ return e;
+ }
+ catch (SystemException e) {
+ return e;
+ }
}
- // avoid log and throw antipattern
- catch (RollbackException e) {
- return e;
- }
- catch (HeuristicMixedException e) {
- return e;
- }
- catch (HeuristicRollbackException e) {
- return e;
- }
- catch (SystemException e) {
- return e;
- }
+ return null;
}
protected Exception rollback() {
- log.debug("rolling back " + transaction);
- try {
- transaction.rollback();
- return null;
+ if (transaction != null) {
+ try {
+ transaction.rollback();
+ }
+ catch (SystemException e) {
+ return e;
+ }
}
- catch (SystemException e) {
- // avoid log and throw antipattern
- return e;
+ else {
+ SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) getSessionFactory();
+ TransactionManager transactionManager = sessionFactory.getTransactionManager();
+ if (transactionManager == null) {
+ throw new JbpmPersistenceException("cannot honor rollback request under external transaction manager");
+ }
+ try {
+ transactionManager.getTransaction().setRollbackOnly();
+ }
+ catch (SystemException e) {
+ return e;
+ }
}
+ return null;
}
public boolean isJtaTxCreated() {
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/scheduler/db/DbSchedulerService.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/scheduler/db/DbSchedulerService.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/scheduler/db/DbSchedulerService.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -21,8 +21,6 @@
*/
package org.jbpm.scheduler.db;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
import org.jbpm.JbpmContext;
import org.jbpm.JbpmException;
import org.jbpm.db.JobSession;
@@ -36,12 +34,10 @@
private static final long serialVersionUID = 1L;
- private static final Log log = LogFactory.getLog(DbSchedulerService.class);
+ private final JobSession jobSession;
+ private final JobExecutor jobExecutor;
+ private boolean hasProducedJobs;
- final JobSession jobSession;
- final JobExecutor jobExecutor;
- boolean hasProducedJobs;
-
public DbSchedulerService() {
JbpmContext jbpmContext = JbpmContext.getCurrentJbpmContext();
if (jbpmContext == null) throw new JbpmException("no active jbpm context");
@@ -68,8 +64,9 @@
}
public void close() {
+ // if timers were produced
if (hasProducedJobs && jobExecutor != null) {
- log.debug("timers were produced, job executor will be notified");
+ // notify job executor
synchronized (jobExecutor) {
jobExecutor.notify();
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/scheduler/def/CreateTimerAction.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/scheduler/def/CreateTimerAction.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/scheduler/def/CreateTimerAction.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -43,7 +43,6 @@
public class CreateTimerAction extends Action {
private static final long serialVersionUID = 1L;
- private static final BusinessCalendar businessCalendar = new BusinessCalendar();
private String timerName;
private String dueDate;
@@ -80,9 +79,7 @@
throw new JbpmException("jbpm context unavailable");
}
// retrieve scheduler service
- SchedulerService schedulerService = jbpmContext
- .getServices()
- .getSchedulerService();
+ SchedulerService schedulerService = jbpmContext.getServices().getSchedulerService();
if (schedulerService == null) {
throw new JbpmException("scheduler service unavailable");
}
@@ -100,16 +97,19 @@
timer.setName(timerName);
timer.setRepeat(repeat);
+ // calculate due date
if (dueDate != null) {
Date dueDateDate;
- if (dueDate.startsWith("#{")) {
- int braceIndex = dueDate.indexOf("}");
+
+ // evaluate base date expression
+ if (dueDate.startsWith("#{") || dueDate.startsWith("${")) {
+ int braceIndex = dueDate.indexOf('}');
if (braceIndex == -1) {
throw new JbpmException("invalid due date, closing brace missing: " + dueDate);
}
- String baseDateEL = dueDate.substring(0, braceIndex + 1);
- Object result = JbpmExpressionEvaluator.evaluate(baseDateEL, executionContext);
+ String baseDateExpression = dueDate.substring(0, braceIndex + 1);
+ Object result = JbpmExpressionEvaluator.evaluate(baseDateExpression, executionContext);
Date baseDate;
if (result instanceof Date) {
@@ -119,27 +119,30 @@
baseDate = ((Calendar) result).getTime();
}
else {
- throw new JbpmException("invalid base date type: " + result.getClass().getName());
+ throw new JbpmException(baseDateExpression + " returned " + result
+ + " instead of date or calendar");
}
String durationString = dueDate.substring(braceIndex + 1).trim();
if (durationString.length() > 0) {
char durationSeparator = durationString.charAt(0);
if (durationSeparator != '+' && durationSeparator != '-') {
- throw new JbpmException("invalid due date, + or - missing: " + dueDate);
+ throw new JbpmException("invalid due date, '+' or '-' missing after expression: "
+ + dueDate);
}
- durationString = dueDate.substring(braceIndex + 1).trim();
- dueDateDate = businessCalendar.add(baseDate, new Duration(durationString));
+ dueDateDate = new BusinessCalendar().add(baseDate, new Duration(durationString));
}
else {
dueDateDate = baseDate;
}
}
+ // take current time as base date
else {
- dueDateDate = businessCalendar.add(Clock.getCurrentTime(), new Duration(dueDate));
+ dueDateDate = new BusinessCalendar().add(Clock.getCurrentTime(), new Duration(dueDate));
}
timer.setDueDate(dueDateDate);
}
+
timer.setAction(timerAction);
timer.setTransitionName(transitionName);
timer.setGraphElement(executionContext.getEventSource());
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/svc/save/CascadeSaveOperation.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/svc/save/CascadeSaveOperation.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/svc/save/CascadeSaveOperation.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -54,7 +54,7 @@
private void saveCascadeInstance(ProcessInstance cascadeInstance, JbpmContext jbpmContext,
Set cascadedProcessInstances) {
if (!cascadedProcessInstances.contains(cascadeInstance)) {
- log.debug("cascading save to " + cascadeInstance);
+ if (log.isDebugEnabled()) log.debug("cascading save to " + cascadeInstance);
jbpmContext.save(cascadeInstance);
cascadedProcessInstances.add(cascadeInstance);
@@ -63,5 +63,5 @@
}
}
- private Log log = LogFactory.getLog(CascadeSaveOperation.class);
+ private static final Log log = LogFactory.getLog(CascadeSaveOperation.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/svc/save/HibernateSaveOperation.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/svc/save/HibernateSaveOperation.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/svc/save/HibernateSaveOperation.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -34,13 +34,10 @@
public void save(ProcessInstance processInstance, JbpmContext jbpmContext) {
Session session = jbpmContext.getSession();
if (session != null) {
- log.debug("saving " + processInstance);
+ if (log.isDebugEnabled()) log.debug("saving " + processInstance);
session.save(processInstance);
}
- else {
- log.debug("ignoring hibernate save, no session available");
- }
}
- private static Log log = LogFactory.getLog(HibernateSaveOperation.class);
+ private static final Log log = LogFactory.getLog(HibernateSaveOperation.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/svc/save/SaveLogsOperation.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/svc/save/SaveLogsOperation.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/svc/save/SaveLogsOperation.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -38,27 +38,22 @@
public void save(ProcessInstance processInstance, JbpmContext jbpmContext) {
LoggingService loggingService = jbpmContext.getServices().getLoggingService();
+ if (loggingService == null) return;
- if (loggingService != null) {
- List logs = processInstance.getLoggingInstance().getLogs();
- if (!logs.isEmpty()) {
- log.debug("pushing " + logs.size() + " logs to logging service");
+ List logs = processInstance.getLoggingInstance().getLogs();
+ if (logs.isEmpty()) return;
- for (Iterator iter = logs.iterator(); iter.hasNext();) {
- ProcessLog processLog = (ProcessLog) iter.next();
- Token token = processLog.getToken();
- if (token != null) {
- int index = token.nextLogIndex();
- processLog.setIndex(index);
- }
- loggingService.log(processLog);
- }
+ if (log.isDebugEnabled()) log.debug("flushing " + logs.size() + " logs");
+ for (Iterator iter = logs.iterator(); iter.hasNext();) {
+ ProcessLog processLog = (ProcessLog) iter.next();
+ Token token = processLog.getToken();
+ if (token != null) {
+ int index = token.nextLogIndex();
+ processLog.setIndex(index);
}
+ loggingService.log(processLog);
}
- else {
- log.debug("ignoring logs, no logging service available");
- }
}
- private Log log = LogFactory.getLog(SaveLogsOperation.class);
+ private static final Log log = LogFactory.getLog(SaveLogsOperation.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/taskmgmt/def/TaskController.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/taskmgmt/def/TaskController.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/taskmgmt/def/TaskController.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -22,11 +22,13 @@
package org.jbpm.taskmgmt.def;
import java.io.Serializable;
+import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.jbpm.JbpmConfiguration;
import org.jbpm.context.def.VariableAccess;
import org.jbpm.context.exe.ContextInstance;
@@ -40,63 +42,58 @@
/**
* is a controller for one task. this object either delegates to a custom
* {@link org.jbpm.taskmgmt.def.TaskControllerHandler} or it is configured with
- * {@link org.jbpm.context.def.VariableAccess}s to perform the default behaviour
- * of the controller functionality for a task.
+ * {@link org.jbpm.context.def.VariableAccess}s to perform the default behaviour of the
+ * controller functionality for a task.
*/
public class TaskController implements Serializable {
private static final long serialVersionUID = 1L;
- long id = 0;
+ long id;
/**
- * allows the user to specify a custom task controller handler. if this is
- * specified, the other member variableInstances are ignored. so either a
- * taskControllerDelegation is specified or the variable- and signalMappings
- * are specified, but not both.
+ * allows the user to specify a custom task controller handler. if this is specified, the
+ * other member variableInstances are ignored. so either a taskControllerDelegation is
+ * specified or the variable- and signalMappings are specified, but not both.
*/
- Delegation taskControllerDelegation = null;
+ private Delegation taskControllerDelegation;
/**
* maps process variable names (java.lang.String) to VariableAccess objects.
*/
- List variableAccesses = null;
+ private List variableAccesses;
public TaskController() {
}
/**
- * extract the list of information from the process variables and make them
- * available locally. Note that if no task instance variables are specified,
- * the full process variables scope will be visible (that means that the user
- * did not specify a special task instance scope).
+ * extract the list of information from the process variables and make them available locally.
+ * Note that if no task instance variables are specified, the full process variables scope
+ * will be visible (that means that the user did not specify a special task instance scope).
*/
public void initializeVariables(TaskInstance taskInstance) {
- ClassLoader surroundingClassLoader = Thread.currentThread()
- .getContextClassLoader();
+ ClassLoader surroundingClassLoader = Thread.currentThread().getContextClassLoader();
try {
// set context class loader correctly for delegation class
// https://jira.jboss.org/jira/browse/JBPM-1448
ClassLoader classLoader = JbpmConfiguration.getProcessClassLoader(taskInstance.getTask()
- .getProcessDefinition());
+ .getProcessDefinition());
Thread.currentThread().setContextClassLoader(classLoader);
if (taskControllerDelegation != null) {
TaskControllerHandler taskControllerHandler = (TaskControllerHandler) taskControllerDelegation.instantiate();
ProcessInstance processInstance = taskInstance.getTaskMgmtInstance()
- .getProcessInstance();
+ .getProcessInstance();
ContextInstance contextInstance = (processInstance != null ? processInstance.getContextInstance()
- : null);
+ : null);
Token token = taskInstance.getToken();
UserCodeInterceptor userCodeInterceptor = UserCodeInterceptorConfig.getUserCodeInterceptor();
if (userCodeInterceptor != null) {
- userCodeInterceptor.executeTaskControllerInitialization(
- taskControllerHandler, taskInstance, contextInstance, token);
+ userCodeInterceptor.executeTaskControllerInitialization(taskControllerHandler, taskInstance, contextInstance, token);
}
else {
- taskControllerHandler.initializeTaskVariables(taskInstance,
- contextInstance, token);
+ taskControllerHandler.initializeTaskVariables(taskInstance, contextInstance, token);
}
}
else {
@@ -105,21 +102,21 @@
ContextInstance contextInstance = processInstance.getContextInstance();
if (variableAccesses != null) {
- Iterator iter = variableAccesses.iterator();
- while (iter.hasNext()) {
+ boolean debug = log.isDebugEnabled();
+ for (Iterator iter = variableAccesses.iterator(); iter.hasNext();) {
VariableAccess variableAccess = (VariableAccess) iter.next();
String mappedName = variableAccess.getMappedName();
if (variableAccess.isReadable()) {
String variableName = variableAccess.getVariableName();
Object value = contextInstance.getVariable(variableName, token);
- log.debug("creating task instance variable '" + mappedName
- + "' from process variable '" + variableName + "', value '"
- + value + "'");
+ if (debug) {
+ log.debug(taskInstance + " reads '" + variableName + "' into '" + mappedName
+ + '\'');
+ }
taskInstance.setVariableLocally(mappedName, value);
}
else {
- log.debug("creating task instance local variable '" + mappedName
- + "'. initializing with null value.");
+ if (debug) log.debug(token + " initializes '" + mappedName + " to null");
taskInstance.setVariableLocally(mappedName, null);
}
}
@@ -135,81 +132,69 @@
* update the process variables from the the task-instance variables.
*/
public void submitParameters(TaskInstance taskInstance) {
- ClassLoader surroundingClassLoader = Thread.currentThread()
- .getContextClassLoader();
- try {
- // set context class loader correctly for delegation class
- // https://jira.jboss.org/jira/browse/JBPM-1448
- ClassLoader classLoader = JbpmConfiguration.getProcessClassLoader(taskInstance.getTask()
+ if (taskControllerDelegation != null) {
+ ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+ try {
+ // set context class loader correctly for delegation class
+ // https://jira.jboss.org/jira/browse/JBPM-1448
+ ClassLoader processClassLoader = JbpmConfiguration.getProcessClassLoader(taskInstance.getTask()
.getProcessDefinition());
- Thread.currentThread().setContextClassLoader(classLoader);
+ Thread.currentThread().setContextClassLoader(processClassLoader);
- if (taskControllerDelegation != null) {
TaskControllerHandler taskControllerHandler = (TaskControllerHandler) taskControllerDelegation.instantiate();
- ProcessInstance processInstance = taskInstance.getTaskMgmtInstance()
- .getProcessInstance();
- ContextInstance contextInstance = processInstance != null ? processInstance.getContextInstance()
- : null;
Token token = taskInstance.getToken();
+ ContextInstance contextInstance = token != null ? token.getProcessInstance()
+ .getContextInstance() : null;
UserCodeInterceptor userCodeInterceptor = UserCodeInterceptorConfig.getUserCodeInterceptor();
if (userCodeInterceptor != null) {
- userCodeInterceptor.executeTaskControllerSubmission(
- taskControllerHandler, taskInstance, contextInstance, token);
+ userCodeInterceptor.executeTaskControllerSubmission(taskControllerHandler, taskInstance, contextInstance, token);
}
else {
- taskControllerHandler.submitTaskVariables(taskInstance,
- contextInstance, token);
+ taskControllerHandler.submitTaskVariables(taskInstance, contextInstance, token);
}
}
- else {
- Token token = taskInstance.getToken();
- ProcessInstance processInstance = token.getProcessInstance();
- ContextInstance contextInstance = processInstance.getContextInstance();
+ finally {
+ Thread.currentThread().setContextClassLoader(contextClassLoader);
+ }
+ }
+ else if (variableAccesses != null) {
+ List missingTaskVariables = null;
+ for (Iterator iter = variableAccesses.iterator(); iter.hasNext();) {
+ VariableAccess variableAccess = (VariableAccess) iter.next();
+ String mappedName = variableAccess.getMappedName();
+ // first check if the required variableInstances are present
+ if (variableAccess.isRequired() && !taskInstance.hasVariableLocally(mappedName)) {
+ if (missingTaskVariables == null) missingTaskVariables = new ArrayList();
+ missingTaskVariables.add(mappedName);
+ }
+ }
- if (variableAccesses != null) {
- String missingTaskVariables = null;
- for (Iterator iter = variableAccesses.iterator(); iter.hasNext();) {
- VariableAccess variableAccess = (VariableAccess) iter.next();
- String mappedName = variableAccess.getMappedName();
- // first check if the required variableInstances are present
- if (variableAccess.isRequired()
- && !taskInstance.hasVariableLocally(mappedName)) {
- if (missingTaskVariables == null) {
- missingTaskVariables = mappedName;
- }
- else {
- missingTaskVariables += ", " + mappedName;
- }
- }
- }
+ // if there are missing, required parameters, puke
+ if (missingTaskVariables != null) {
+ throw new IllegalArgumentException("missing task variables: " + missingTaskVariables);
+ }
- // if there are missing, required parameters, puke
- if (missingTaskVariables != null) {
- throw new IllegalArgumentException("missing task variables: "
- + missingTaskVariables);
- }
+ Token token = taskInstance.getToken();
+ ContextInstance contextInstance = token.getProcessInstance().getContextInstance();
+ boolean debug = log.isDebugEnabled();
- for (Iterator iter = variableAccesses.iterator(); iter.hasNext();) {
- VariableAccess variableAccess = (VariableAccess) iter.next();
- String mappedName = variableAccess.getMappedName();
+ for (Iterator iter = variableAccesses.iterator(); iter.hasNext();) {
+ VariableAccess variableAccess = (VariableAccess) iter.next();
+ if (variableAccess.isWritable()) {
+ String mappedName = variableAccess.getMappedName();
+ Object value = taskInstance.getVariable(mappedName);
+ if (value != null) {
String variableName = variableAccess.getVariableName();
- if (variableAccess.isWritable()) {
- Object value = taskInstance.getVariable(mappedName);
- if (value != null) {
- log.debug("submitting task variable '" + mappedName
- + "' to process variable '" + variableName + "', value '"
- + value + "'");
- contextInstance.setVariable(variableName, value, token);
- }
+ if (debug) {
+ log.debug(taskInstance + " writes '" + variableName + "' from '" + mappedName
+ + '\'');
}
+ contextInstance.setVariable(variableName, value, token);
}
}
}
}
- finally {
- Thread.currentThread().setContextClassLoader(surroundingClassLoader);
- }
}
// equals ///////////////////////////////////////////////////////////////////
@@ -245,5 +230,5 @@
this.variableAccesses = variableAccesses;
}
- private static Log log = LogFactory.getLog(TaskController.class);
+ private static final Log log = LogFactory.getLog(TaskController.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/taskmgmt/exe/TaskInstance.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/taskmgmt/exe/TaskInstance.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/taskmgmt/exe/TaskInstance.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -36,6 +36,7 @@
import org.jbpm.context.exe.VariableContainer;
import org.jbpm.context.exe.VariableInstance;
import org.jbpm.graph.def.Event;
+import org.jbpm.graph.def.GraphElement;
import org.jbpm.graph.def.Identifiable;
import org.jbpm.graph.def.Node;
import org.jbpm.graph.def.Transition;
@@ -54,9 +55,8 @@
import org.jbpm.util.Clock;
/**
- * is one task instance that can be assigned to an actor (read: put in someone's
- * task list) and that can trigger the continuation of execution of the token
- * upon completion.
+ * is one task instance that can be assigned to an actor (read: put in someone's task list) and
+ * that can trigger the continuation of execution of the token upon completion.
*/
public class TaskInstance extends VariableContainer implements Identifiable, Assignable {
@@ -109,26 +109,23 @@
this.isSignalling = task.isSignalling();
}
- void submitVariables() {
- TaskController taskController = task != null ? task.getTaskController() : null;
+ private void submitVariables() {
+ TaskController taskController;
// if a task controller is present,
- if (taskController != null) {
+ if (task != null && (taskController = task.getTaskController()) != null) {
// the task controller copies variables back into the process
taskController.submitParameters(this);
}
- // in absence of a task controller,
- else if (token != null && token.getProcessInstance() != null) {
- // all task-local variables are flushed to the process
- if (variableInstances != null) {
- ContextInstance contextInstance = token.getProcessInstance().getContextInstance();
- for (Iterator iter = variableInstances.values().iterator(); iter.hasNext();) {
- VariableInstance variableInstance = (VariableInstance) iter.next();
- String variableName = variableInstance.getName();
- log.debug("submitting variable '" + variableName + "' from task '" + name
- + "' to process variables");
- // simple way to clone the variable instance; might be optimized
- contextInstance.setVariable(variableName, variableInstance.getValue(), token);
- }
+ // otherwise, all task-local variables are flushed to the process
+ else if (token != null && variableInstances != null) {
+ ContextInstance contextInstance = token.getProcessInstance().getContextInstance();
+ boolean debug = log.isDebugEnabled();
+
+ for (Iterator iter = variableInstances.values().iterator(); iter.hasNext();) {
+ VariableInstance variableInstance = (VariableInstance) iter.next();
+ String variableName = variableInstance.getName();
+ if (debug) log.debug(this + " writes '" + variableName + '\'');
+ contextInstance.setVariable(variableName, variableInstance.getValue(), token);
}
}
}
@@ -152,20 +149,17 @@
// if this task instance is associated with a task...
if (task != null && executionContext != null) {
- // the TASK_CREATE event is fired
+ // fire task create event
+ // WARNING: The events create and assign are fired in the right order,
+ // yet the logs are still not ordered properly
executionContext.setTaskInstance(this);
executionContext.setTask(task);
task.fireEvent(Event.EVENTTYPE_TASK_CREATE, executionContext);
}
-
- // WARNING: The events create and assign are fired in the right order,
- // yet the logs are still not ordered properly.
- // See also: TaskMgmtInstance.createTaskInstance
}
public void assign(ExecutionContext executionContext) {
TaskMgmtInstance taskMgmtInstance = executionContext.getTaskMgmtInstance();
-
Swimlane swimlane = task.getSwimlane();
// if this task is in a swimlane
if (swimlane != null) {
@@ -177,19 +171,16 @@
// with the current authenticated actor
swimlaneInstance.setActorId(SecurityHelper.getAuthenticatedActorId());
}
- else { // lazily initialize the swimlane...
+ // lazily initialize the swimlane...
+ else {
// get the swimlane instance (if there is any)
- swimlaneInstance = taskMgmtInstance.getInitializedSwimlaneInstance(executionContext,
- swimlane);
-
+ swimlaneInstance = taskMgmtInstance.getInitializedSwimlaneInstance(executionContext, swimlane);
// copy the swimlaneInstance assignment into the taskInstance assignment
copySwimlaneInstanceAssignment(swimlaneInstance);
}
}
else { // this task is not in a swimlane
- taskMgmtInstance.performAssignment(task.getAssignmentDelegation(),
- task.getActorIdExpression(), task.getPooledActorsExpression(), this,
- executionContext);
+ taskMgmtInstance.performAssignment(task.getAssignmentDelegation(), task.getActorIdExpression(), task.getPooledActorsExpression(), this, executionContext);
}
updatePooledActorsReferences(swimlaneInstance);
@@ -206,7 +197,7 @@
return false;
}
- void updatePooledActorsReferences(SwimlaneInstance swimlaneInstance) {
+ private void updatePooledActorsReferences(SwimlaneInstance swimlaneInstance) {
if (pooledActors != null) {
for (Iterator iter = pooledActors.iterator(); iter.hasNext();) {
PooledActor pooledActor = (PooledActor) iter.next();
@@ -217,8 +208,8 @@
}
/**
- * copies the assignment (that includes both the swimlaneActorId and the set
- * of pooledActors) of the given swimlane into this taskInstance.
+ * copies the assignment (that includes both the swimlaneActorId and the set of pooledActors)
+ * of the given swimlane into this taskInstance.
*/
public void copySwimlaneInstanceAssignment(SwimlaneInstance swimlaneInstance) {
setSwimlaneInstance(swimlaneInstance);
@@ -227,9 +218,8 @@
}
/**
- * gets the pool of actors for this task instance. If this task has a
- * simlaneInstance and no pooled actors, the pooled actors of the swimlane
- * instance are returned.
+ * gets the pool of actors for this task instance. If this task has a simlaneInstance and no
+ * pooled actors, the pooled actors of the swimlane instance are returned.
*/
public Set getPooledActors() {
if (swimlaneInstance != null && (pooledActors == null || pooledActors.isEmpty())) {
@@ -239,8 +229,8 @@
}
/**
- * (re)assign this task to the given actor. If this task is related to a
- * swimlane instance, that swimlane instance will be updated as well.
+ * (re)assign this task to the given actor. If this task is related to a swimlane instance,
+ * that swimlane instance will be updated as well.
*/
public void setActorId(String actorId) {
setActorId(actorId, true);
@@ -250,34 +240,31 @@
* (re)assign this task to the given actor.
*
* @param actorId is reference to the person that is assigned to this task.
- * @param overwriteSwimlane specifies if the related swimlane should be
- * overwritten with the given swimlaneActorId.
+ * @param overwriteSwimlane specifies if the related swimlane should be overwritten with the
+ * given swimlaneActorId.
*/
public void setActorId(String actorId, boolean overwriteSwimlane) {
// do the actual assignment
this.previousActorId = this.actorId;
this.actorId = actorId;
if (swimlaneInstance != null && overwriteSwimlane) {
- log.debug("assigning task '" + name + "' to '" + actorId + "'");
+ if (log.isDebugEnabled()) log.debug("assigning " + this + " to '" + actorId + '\'');
swimlaneInstance.setActorId(actorId);
}
- // fire the event
- if (task != null && token != null) {
- ExecutionContext executionContext = new ExecutionContext(token);
- executionContext.setTask(task);
- executionContext.setTaskInstance(this);
-
- // WARNING: The events create and assign are fired in the right order, but
- // the logs are still not ordered properly.
- // See also: TaskMgmtInstance.createTaskInstance
- task.fireEvent(Event.EVENTTYPE_TASK_ASSIGN, executionContext);
- }
-
- // add the log
if (token != null) {
// log this assignment
token.addLog(new TaskAssignLog(this, previousActorId, actorId));
+
+ if (task != null) {
+ // fire task assign event
+ // WARNING: The events create and assign are fired in the right order,
+ // but the logs are still not ordered properly
+ ExecutionContext executionContext = new ExecutionContext(token);
+ executionContext.setTask(task);
+ executionContext.setTaskInstance(this);
+ task.fireEvent(Event.EVENTTYPE_TASK_ASSIGN, executionContext);
+ }
}
}
@@ -287,16 +274,17 @@
}
/**
- * can optionally be used to indicate that the actor is starting to work on
- * this task instance.
+ * can optionally be used to indicate that the actor is starting to work on this task
+ * instance.
*/
public void start() {
if (start != null) {
throw new IllegalStateException(this + " is already started");
}
-
start = Clock.getCurrentTime();
- if ((task != null) && (token != null)) {
+
+ // fire task start event
+ if (token != null && task != null) {
ExecutionContext executionContext = new ExecutionContext(token);
executionContext.setTask(task);
executionContext.setTaskInstance(this);
@@ -305,16 +293,15 @@
}
/**
- * convenience method that combines a {@link #setActorId(String)} and a
- * {@link #start()}.
+ * convenience method that combines a {@link #setActorId(String)} and a {@link #start()}.
*/
public void start(String actorId) {
start(actorId, true);
}
/**
- * convenience method that combines a {@link #setActorId(String,boolean)} and
- * a {@link #start()}.
+ * convenience method that combines a {@link #setActorId(String,boolean)} and a
+ * {@link #start()}.
*/
public void start(String actorId, boolean overwriteSwimlane) {
setActorId(actorId, overwriteSwimlane);
@@ -334,9 +321,8 @@
}
/**
- * cancels this task. This task instance will be marked as cancelled and as
- * ended. But cancellation doesn't influence signalling and continuation of
- * process execution.
+ * cancels this task. This task instance will be marked as cancelled and as ended. But
+ * cancellation doesn't influence signalling and continuation of process execution.
*/
public void cancel() {
markAsCancelled();
@@ -344,9 +330,9 @@
}
/**
- * cancels this task, takes the specified transition. This task intance will
- * be marked as cancelled and as ended. But cancellation doesn't influence
- * singalling and continuation of process execution.
+ * cancels this task, takes the specified transition. This task intance will be marked as
+ * cancelled and as ended. But cancellation doesn't influence singalling and continuation of
+ * process execution.
*/
public void cancel(Transition transition) {
markAsCancelled();
@@ -354,9 +340,9 @@
}
/**
- * cancels this task, takes the specified transition. This task intance will
- * be marked as cancelled and as ended. But cancellation doesn't influence
- * singalling and continuation of process execution.
+ * cancels this task, takes the specified transition. This task intance will be marked as
+ * cancelled and as ended. But cancellation doesn't influence singalling and continuation of
+ * process execution.
*/
public void cancel(String transitionName) {
markAsCancelled();
@@ -364,8 +350,8 @@
}
/**
- * marks this task as done. If this task is related to a task node this might
- * trigger a signal on the token.
+ * marks this task as done. If this task is related to a task node this might trigger a signal
+ * on the token.
*
* @see #end(Transition)
*/
@@ -374,11 +360,11 @@
}
/**
- * marks this task as done and specifies the name of a transition leaving the
- * task-node for the case that the completion of this task instances triggers
- * a signal on the token. If this task leads to a signal on the token, the
- * given transition name will be used in the signal. If this task completion
- * does not trigger execution to move on, the transitionName is ignored.
+ * marks this task as done and specifies the name of a transition leaving the task-node for
+ * the case that the completion of this task instances triggers a signal on the token. If this
+ * task leads to a signal on the token, the given transition name will be used in the signal.
+ * If this task completion does not trigger execution to move on, the transitionName is
+ * ignored.
*/
public void end(String transitionName) {
if (task == null) {
@@ -387,10 +373,11 @@
Node node = task.getTaskNode();
if (node == null) {
- node = (Node) task.getParent();
- if (node == null) {
+ GraphElement parent = task.getParent();
+ if (!(parent instanceof Node)) {
throw new JbpmException(this + " has no enclosing node");
}
+ node = (Node) parent;
}
Transition leavingTransition = node.getLeavingTransition(transitionName);
@@ -401,11 +388,10 @@
}
/**
- * marks this task as done and specifies a transition leaving the task-node
- * for the case that the completion of this task instances triggers a signal
- * on the token. If this task leads to a signal on the token, the given
- * transition name will be used in the signal. If this task completion does
- * not trigger execution to move on, the transition is ignored.
+ * marks this task as done and specifies a transition leaving the task-node for the case that
+ * the completion of this task instances triggers a signal on the token. If this task leads to
+ * a signal on the token, the given transition name will be used in the signal. If this task
+ * completion does not trigger execution to move on, the transition is ignored.
*/
public void end(Transition transition) {
if (end != null) {
@@ -415,48 +401,53 @@
throw new JbpmException(this + " is suspended");
}
- // mark the end of this task instance
+ // record the end time
this.end = Clock.getCurrentTime();
this.isOpen = false;
// fire the task instance end event
- if (task != null && token != null) {
- ExecutionContext executionContext = new ExecutionContext(token);
- executionContext.setTask(task);
- executionContext.setTaskInstance(this);
- task.fireEvent(Event.EVENTTYPE_TASK_END, executionContext);
- }
-
- // log this assignment
if (token != null) {
+ // submit the variables
+ submitVariables();
+
+ // log task completion
token.addLog(new TaskEndLog(this));
- }
- // submit the variables
- submitVariables();
+ if (task != null) {
+ // fire task end event
+ ExecutionContext executionContext = new ExecutionContext(token);
+ executionContext.setTask(task);
+ executionContext.setTaskInstance(this);
+ task.fireEvent(Event.EVENTTYPE_TASK_END, executionContext);
- // check whether completing this task causes execution to proceed
- if (isSignalling) {
- isSignalling = false;
+ // check whether completion triggers token signal
+ if (isSignalling) {
+ isSignalling = false;
- TaskNode taskNode;
- if (isStartTaskInstance() // ending start task leads to signal
- || (task != null && token != null && (taskNode = task.getTaskNode()) != null && taskNode.completionTriggersSignal(this))) {
-
- if (transition == null) {
- log.debug("taking default transition after completing " + task);
- token.signal();
+ TaskNode taskNode = task.getTaskNode();
+ if (isStartTaskInstance() // ending start task leads to signal
+ || (taskNode != null && taskNode.completionTriggersSignal(this))) {
+ boolean debug = log.isDebugEnabled();
+ if (transition == null) {
+ if (debug) {
+ log.debug("taking default transition after completing " + task);
+ }
+ token.signal();
+ }
+ else {
+ if (debug) {
+ log.debug("taking" + transition + " after completing " + task);
+ }
+ token.signal(transition);
+ }
+ }
}
- else {
- log.debug("taking" + transition + " after completing " + task);
- token.signal(transition);
- }
}
}
}
public boolean hasEnded() {
- return (end != null);
+ return end != null;
}
/**
@@ -509,8 +500,8 @@
}
/**
- * is the list of transitions that can be used in the end method and it is
- * null in case this is not the last task instance.
+ * is the list of transitions that can be used in the end method and it is null in case this
+ * is not the last task instance.
*/
public List getAvailableTransitions() {
List transitions = null;
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/taskmgmt/exe/TaskMgmtInstance.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/taskmgmt/exe/TaskMgmtInstance.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/taskmgmt/exe/TaskMgmtInstance.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -103,33 +103,40 @@
* creates an instance of the given task, in the given execution context.
*/
public TaskInstance createTaskInstance(Task task, ExecutionContext executionContext) {
- // instantiate the new task instance
+ // create new task instance
TaskInstance taskInstance = instantiateNewTaskInstance(executionContext);
-
- // initialize the task instance
+ // assign database identifier
+ Services.assignId(taskInstance);
+ // set task definition
if (task != null) taskInstance.setTask(task);
-
- // bind the task instance to the TaskMgmtInstance
+ // bind task instance to this task management instance
addTaskInstance(taskInstance);
- // assign an id to the task instance
- Services.assignId(taskInstance);
-
if (executionContext != null) {
+ // set token
Token token = executionContext.getToken();
taskInstance.setToken(token);
taskInstance.setProcessInstance(token.getProcessInstance());
-
+ // initialize variables
taskInstance.initializeVariables();
- if (task != null && task.getDueDate() != null) {
- Date baseDate;
- String dueDateString = task.getDueDate();
- String durationString = null;
+ // calculate due date
+ String dueDateString;
+ if (task != null && (dueDateString = task.getDueDate()) != null) {
+ Date dueDate;
- if (dueDateString.startsWith("#")) {
- String baseDateEL = dueDateString.substring(0, dueDateString.indexOf("}") + 1);
- Object result = JbpmExpressionEvaluator.evaluate(baseDateEL, executionContext);
+ // evaluate base date expression
+ if (dueDateString.startsWith("#{") || dueDateString.startsWith("${")) {
+ int braceIndex = dueDateString.indexOf('}');
+ if (braceIndex == -1) {
+ throw new JbpmException("invalid due date, closing brace missing: " + dueDateString);
+ }
+
+ String baseDateExpression = dueDateString.substring(0, braceIndex + 1);
+ Object result = JbpmExpressionEvaluator
+ .evaluate(baseDateExpression, executionContext);
+
+ Date baseDate;
if (result instanceof Date) {
baseDate = (Date) result;
}
@@ -137,29 +144,28 @@
baseDate = ((Calendar) result).getTime();
}
else {
- throw new JbpmException("base date is neither Date nor Calendar");
+ throw new JbpmException(baseDateExpression + " returned " + result
+ + " instead of date or calendar");
}
- int endOfELIndex = dueDateString.indexOf("}");
- if (endOfELIndex < (dueDateString.length() - 1)) {
- char durationSeparator = dueDateString.substring(endOfELIndex + 1).trim().charAt(0);
+
+ String durationString = dueDateString.substring(braceIndex + 1).trim();
+ if (durationString.length() > 0) {
+ char durationSeparator = durationString.charAt(0);
if (durationSeparator != '+' && durationSeparator != '-') {
- throw new JbpmException("'+' or '-' missing after expression");
+ throw new JbpmException("invalid due date, '+' or '-' missing after expression: "
+ + dueDateString);
}
- durationString = dueDateString.substring(endOfELIndex + 1).trim();
+ dueDate = new BusinessCalendar().add(baseDate, new Duration(durationString));
}
+ else {
+ dueDate = baseDate;
+ }
}
+ // take current time as base date
else {
- baseDate = Clock.getCurrentTime();
- durationString = dueDateString;
+ dueDate = new BusinessCalendar()
+ .add(Clock.getCurrentTime(), new Duration(dueDateString));
}
- Date dueDate;
- if (durationString == null || durationString.length() == 0) {
- dueDate = baseDate;
- }
- else {
- BusinessCalendar businessCalendar = new BusinessCalendar();
- dueDate = businessCalendar.add(baseDate, new Duration(durationString));
- }
taskInstance.setDueDate(dueDate);
}
@@ -183,10 +189,8 @@
// create the task instance
taskInstance.create(executionContext);
- // if this task instance is created for a task, perform assignment
- if (task != null) {
- taskInstance.assign(executionContext);
- }
+ // if task definition is present, perform assignment
+ if (task != null) taskInstance.assign(executionContext);
}
finally {
// clean the executionContext
@@ -210,12 +214,14 @@
Swimlane swimlane) {
// initialize the swimlane
if (swimlaneInstances == null) swimlaneInstances = new HashMap();
- SwimlaneInstance swimlaneInstance = (SwimlaneInstance) swimlaneInstances.get(swimlane.getName());
+ SwimlaneInstance swimlaneInstance = (SwimlaneInstance) swimlaneInstances.get(swimlane
+ .getName());
if (swimlaneInstance == null) {
swimlaneInstance = new SwimlaneInstance(swimlane);
addSwimlaneInstance(swimlaneInstance);
// assign the swimlaneInstance
- performAssignment(swimlane.getAssignmentDelegation(), swimlane.getActorIdExpression(), swimlane.getPooledActorsExpression(), swimlaneInstance, executionContext);
+ performAssignment(swimlane.getAssignmentDelegation(), swimlane.getActorIdExpression(), swimlane
+ .getPooledActorsExpression(), swimlaneInstance, executionContext);
}
return swimlaneInstance;
@@ -230,8 +236,8 @@
catch (Exception e) {
GraphElement graphElement = executionContext.getEventSource();
if (graphElement == null) {
- throw e instanceof JbpmException ? (JbpmException) e : new DelegationException(e,
- executionContext);
+ throw e instanceof JbpmException ? (JbpmException) e
+ : new DelegationException(e, executionContext);
}
graphElement.raiseException(e, executionContext);
}
@@ -246,19 +252,22 @@
}
}
- void performAssignmentDelegation(Delegation assignmentDelegation, Assignable assignable,
- ExecutionContext executionContext) throws Exception {
+ private void performAssignmentDelegation(Delegation assignmentDelegation,
+ Assignable assignable, ExecutionContext executionContext) throws Exception {
ClassLoader surroundingClassLoader = Thread.currentThread().getContextClassLoader();
try {
// set context class loader correctly for delegation class
// https://jira.jboss.org/jira/browse/JBPM-1448
- ClassLoader processClassLoader = JbpmConfiguration.getProcessClassLoader(executionContext.getProcessDefinition());
+ ClassLoader processClassLoader = JbpmConfiguration.getProcessClassLoader(executionContext
+ .getProcessDefinition());
Thread.currentThread().setContextClassLoader(processClassLoader);
// instantiate the assignment handler
- AssignmentHandler assignmentHandler = (AssignmentHandler) assignmentDelegation.instantiate();
+ AssignmentHandler assignmentHandler = (AssignmentHandler) assignmentDelegation
+ .instantiate();
// invoke the assignment handler
- UserCodeInterceptor userCodeInterceptor = UserCodeInterceptorConfig.getUserCodeInterceptor();
+ UserCodeInterceptor userCodeInterceptor = UserCodeInterceptorConfig
+ .getUserCodeInterceptor();
if (userCodeInterceptor != null) {
userCodeInterceptor.executeAssignment(assignmentHandler, assignable, executionContext);
}
@@ -271,49 +280,39 @@
}
}
- void performAssignmentActorIdExpr(String actorIdExpression, Assignable assignable,
+ private void performAssignmentActorIdExpr(String actorIdExpression, Assignable assignable,
ExecutionContext executionContext) {
- Object result = JbpmExpressionEvaluator.evaluate(actorIdExpression, executionContext);
- if (result == null) {
- throw new JbpmException("actor-id expression '" + actorIdExpression + "' returned null");
+ String actorId = (String) JbpmExpressionEvaluator
+ .evaluate(actorIdExpression, executionContext, String.class);
+ if (actorId == null) {
+ throw new JbpmException(actorIdExpression + " returned null");
}
- if (result instanceof String) {
- assignable.setActorId((String) result);
- }
- else {
- throw new JbpmException("actor-id expression '" + actorIdExpression
- + "' did not evaluate to string: '" + result);
- }
+ assignable.setActorId(actorId);
}
- void performAssignmentPooledActorsExpr(String pooledActorsExpression, Assignable assignable,
- ExecutionContext executionContext) {
- String[] pooledActors = null;
+ private void performAssignmentPooledActorsExpr(String pooledActorsExpression,
+ Assignable assignable, ExecutionContext executionContext) {
Object result = JbpmExpressionEvaluator.evaluate(pooledActorsExpression, executionContext);
- if (result == null) {
- throw new JbpmException("pooled-actors expression '" + pooledActorsExpression
- + "' returned null");
+
+ String[] pooledActors;
+ if (result instanceof String) {
+ String csv = (String) result;
+ pooledActors = csv.split(",");
+ for (int i = 0; i < pooledActors.length; i++) {
+ pooledActors[i] = pooledActors[i].trim();
+ }
}
-
- if (result instanceof String[]) {
+ else if (result instanceof String[]) {
pooledActors = (String[]) result;
}
else if (result instanceof Collection) {
Collection collection = (Collection) result;
pooledActors = (String[]) collection.toArray(new String[collection.size()]);
}
- else if (result instanceof String) {
- String csv = (String) result;
- pooledActors = csv.split(",");
- for (int i = 0; i < pooledActors.length; i++) {
- pooledActors[i] = pooledActors[i].trim();
- }
- }
else {
- throw new JbpmException("pooled-actors expression '" + pooledActorsExpression
- + "' did not evaluate to comma-separated string, collection or string array: " + result);
+ throw new JbpmException(pooledActorsExpression + " returned " + result
+ + " instead of comma-separated string, collection or string array");
}
-
assignable.setPooledActors(pooledActors);
}
@@ -333,9 +332,10 @@
return taskInstance;
}
- TaskInstance instantiateNewTaskInstance(ExecutionContext executionContext) {
+ private TaskInstance instantiateNewTaskInstance(ExecutionContext executionContext) {
if (Configs.hasObject("jbpm.task.instance.factory")) {
- TaskInstanceFactory factory = (TaskInstanceFactory) Configs.getObject("jbpm.task.instance.factory");
+ TaskInstanceFactory factory = (TaskInstanceFactory) Configs
+ .getObject("jbpm.task.instance.factory");
return factory.createTaskInstance(executionContext);
}
return new TaskInstance();
@@ -445,8 +445,8 @@
}
public SwimlaneInstance createSwimlaneInstance(String swimlaneName) {
- Swimlane swimlane = taskMgmtDefinition != null ? taskMgmtDefinition.getSwimlane(swimlaneName)
- : null;
+ Swimlane swimlane = taskMgmtDefinition != null ? taskMgmtDefinition
+ .getSwimlane(swimlaneName) : null;
if (swimlane == null) {
throw new JbpmException("swimlane does not exist: " + swimlaneName);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/ClassLoaderUtil.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/ClassLoaderUtil.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/ClassLoaderUtil.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -25,7 +25,6 @@
import java.io.InputStream;
import java.util.Properties;
-import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.JbpmConfiguration;
@@ -129,19 +128,26 @@
}
/**
- * Load classpath resource as stream. This method first loads the resource from the context
- * class loader, if not found it tries the current class loader. If no resource is found the
- * call returns <code>null</code>. This is a special method because the class loader used for
- * loading the jBPM configuration cannot be configured in the configuration file itself.
+ * Loads resource as stream. If <code>useConfiguredLoader</code> is <code>true</code>, this
+ * method searches for the resource in the context class loader, if not found it searches in
+ * the class loader of this class.
+ * <p>
+ * This method helps bootstrap jBPM because the class loader used for locating the
+ * configuration resource cannot be configured in the configuration itself.
+ * </p>
+ *
+ * @return a stream for reading the resource, or <code>null</code> if the resource was not
+ * found
*/
public static InputStream getStream(String resource, boolean useConfiguredLoader) {
if (useConfiguredLoader) return getStream(resource);
- // try context class loader first, so that applications can override provided classes
- InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(
- resource);
+ // try context class loader first, allowing applications to hide the provided resources
+ InputStream stream = Thread.currentThread()
+ .getContextClassLoader()
+ .getResourceAsStream(resource);
if (stream == null) {
- // try the class loader of the current class
+ // try class loader of the current class
stream = ClassLoaderUtil.class.getClassLoader().getResourceAsStream(resource);
}
return stream;
@@ -163,8 +169,8 @@
inStream.close();
}
catch (IOException e) {
- Log log = LogFactory.getLog(ClassLoaderUtil.class);
- log.warn("failed to close resource: " + resource, e);
+ LogFactory.getLog(ClassLoaderUtil.class)
+ .warn("failed to close resource: " + resource, e);
}
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/JndiUtil.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/JndiUtil.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/JndiUtil.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -22,11 +22,9 @@
package org.jbpm.util;
import javax.naming.InitialContext;
+import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
public class JndiUtil {
private JndiUtil() {
@@ -34,18 +32,13 @@
}
public static Object lookup(String jndiName, Class type) {
- Object object = null;
try {
InitialContext initialContext = new InitialContext();
- object = initialContext.lookup(jndiName);
- object = PortableRemoteObject.narrow(object, type);
- // fetch from JNDI
- log.debug("fetched '"+object+"' from JNDI location '"+jndiName+"'");
- } catch (Exception e) {
- throw new JndiLookupException("couldn't fetch '"+jndiName+"' from jndi", e);
+ Object object = initialContext.lookup(jndiName);
+ return PortableRemoteObject.narrow(object, type);
}
- return object;
+ catch (NamingException e) {
+ throw new JndiLookupException("could not retrieve: " + jndiName, e);
+ }
}
-
- private static Log log = LogFactory.getLog(JndiUtil.class);
}
Added: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/NodeIterator.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/NodeIterator.java (rev 0)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/NodeIterator.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -0,0 +1,45 @@
+package org.jbpm.util;
+
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+import org.w3c.dom.Node;
+
+/**
+ * An iterator over the children of a DOM node.
+ *
+ * @author Alejandro Guizar
+ * @version $Revision$ $Date: 2006/08/21 01:05:59 $
+ */
+class NodeIterator implements Iterator {
+
+ private Node currentNode;
+ private Node lastReturned;
+
+ /**
+ * Creates an iterator over the children of the given node.
+ *
+ * @param parentNode the node to iterate
+ */
+ public NodeIterator(Node parentNode) {
+ currentNode = parentNode.getFirstChild();
+ }
+
+ public boolean hasNext() {
+ return currentNode != null;
+ }
+
+ public Object next() {
+ if (currentNode == null) throw new NoSuchElementException();
+ lastReturned = currentNode;
+ currentNode = lastReturned.getNextSibling();
+ return lastReturned;
+ }
+
+ public void remove() {
+ if (lastReturned == null) throw new IllegalStateException();
+ Node parentNode = lastReturned.getParentNode();
+ if (parentNode != null) parentNode.removeChild(lastReturned);
+ lastReturned = null;
+ }
+}
\ No newline at end of file
Property changes on: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/NodeIterator.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ native
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/XmlUtil.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/XmlUtil.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/XmlUtil.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -23,7 +23,6 @@
import java.io.ByteArrayInputStream;
import java.io.InputStream;
-import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
@@ -36,15 +35,17 @@
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
-import org.w3c.dom.CharacterData;
+import org.apache.commons.collections.IteratorUtils;
+import org.apache.commons.collections.Predicate;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
import org.xml.sax.InputSource;
public class XmlUtil {
@@ -59,20 +60,15 @@
}
/**
- * @param isJbpmConfiguration specifies if the resource should be loaded with the "limited"
- * bootstrap class loader for jbpm config.
+ * @param useConfiguredLoader specifies if the resource should be loaded with the "limited"
+ * bootstrap class loader for jbpm config.
*/
- public static Document parseXmlResource(String resource, boolean isJbpmConfiguration) {
- // decide which class loading mechanism to use for loading the jbpm
- // configuration (see https://jira.jboss.org/jira/browse/JBPM-1148)
- InputStream inputStream = null;
- if (isJbpmConfiguration)
- inputStream = ClassLoaderUtil.getStream(resource, false);
- else
- inputStream = ClassLoaderUtil.getStream(resource);
-
- if (inputStream == null)
+ public static Document parseXmlResource(String resource, boolean useConfiguredLoader) {
+ // see https://jira.jboss.org/jira/browse/JBPM-1148
+ InputStream inputStream = ClassLoaderUtil.getStream(resource, useConfiguredLoader);
+ if (inputStream == null) {
throw new IllegalArgumentException("Cannot load resource: " + resource);
+ }
InputSource inputSource = new InputSource(inputStream);
return parseXmlInputSource(inputSource);
}
@@ -100,92 +96,86 @@
}
public static DocumentBuilder getDocumentBuilder() throws FactoryConfigurationError,
- ParserConfigurationException {
+ ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
return factory.newDocumentBuilder();
}
- public static Iterator elementIterator(Element element, String tagName) {
- return elements(element, tagName).iterator();
+ public static Iterator elementIterator(Element element, final String tagName) {
+ return IteratorUtils.filteredIterator(new NodeIterator(element), new Predicate() {
+ public boolean evaluate(Object arg) {
+ Node node = (Node) arg;
+ return tagName.equals(node.getNodeName());
+ }
+ });
}
public static List elements(Element element, String tagName) {
- NodeList nodeList = element.getElementsByTagName(tagName);
- List elements = new ArrayList(nodeList.getLength());
- for (int i = 0; i < nodeList.getLength(); i++) {
- Node child = nodeList.item(i);
- if (child.getParentNode() == element) {
+ ArrayList elements = new ArrayList();
+ for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
+ if (child instanceof Element && tagName.equals(child.getNodeName())) {
elements.add(child);
}
}
return elements;
}
- public static Element element(Element element, String name) {
- Element childElement = null;
- NodeList nodeList = element.getElementsByTagName(name);
- if (nodeList.getLength() > 0) {
- childElement = (Element) nodeList.item(0);
+ public static Element element(Element element, String tagName) {
+ for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
+ if (child instanceof Element && tagName.equals(child.getNodeName())) {
+ return (Element) child;
+ }
}
- return childElement;
+ return null;
}
public static Iterator elementIterator(Element element) {
- return elements(element).iterator();
+ return IteratorUtils.filteredIterator(new NodeIterator(element), ElementPredicate.INSTANCE);
}
+ private static class ElementPredicate implements Predicate {
+ static final Predicate INSTANCE = new ElementPredicate();
+
+ public boolean evaluate(Object arg) {
+ return ((Node) arg).getNodeType() == Node.ELEMENT_NODE;
+ }
+ }
+
public static List elements(Element element) {
- List elements = new ArrayList();
- NodeList nodeList = element.getChildNodes();
- for (int i = 0; i < nodeList.getLength(); i++) {
- Node node = nodeList.item(i);
- if ((node instanceof Element) && (element == node.getParentNode())) {
- elements.add(node);
- }
+ ArrayList elements = new ArrayList();
+ for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
+ if (child instanceof Element) elements.add(child);
}
return elements;
}
public static Element element(Element element) {
- Element onlyChild = null;
- List elements = elements(element);
- if (!elements.isEmpty()) {
- onlyChild = (Element) elements.get(0);
+ for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
+ if (child instanceof Element) return (Element) child;
}
- return onlyChild;
+ return null;
}
public static String toString(Element element) {
if (element == null) return "null";
-
Source source = new DOMSource(element);
StringWriter stringWriter = new StringWriter();
- PrintWriter printWriter = new PrintWriter(stringWriter);
- Result result = new StreamResult(printWriter);
-
+ Result result = new StreamResult(stringWriter);
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(source, result);
}
- catch (Exception e) {
- throw new XmlException("couldn't write element '" + element.getTagName() + "' to string", e);
+ catch (TransformerException e) {
+ throw new XmlException("could not transform to string: " + element, e);
}
-
- printWriter.close();
-
return stringWriter.toString();
}
public static String getContentText(Element element) {
StringBuffer buffer = new StringBuffer();
- NodeList nodeList = element.getChildNodes();
- for (int i = 0; i < nodeList.getLength(); i++) {
- Node node = nodeList.item(i);
- if (node instanceof CharacterData) {
- CharacterData characterData = (CharacterData) node;
- buffer.append(characterData.getData());
- }
+ for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
+ if (child instanceof Text) buffer.append(child.getNodeValue());
}
return buffer.toString();
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/SerializabilityTest.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/SerializabilityTest.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/SerializabilityTest.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -52,7 +52,6 @@
"org.jbpm.db.hibernate.SybaseRowLockDialect",
"org.jbpm.graph.action.ActionTypes",
"org.jbpm.graph.exe.ExecutionContext",
- "org.jbpm.graph.node.Fork$ForkedToken",
"org.jbpm.graph.node.InterleaveStart$DefaultInterleaver",
"org.jbpm.graph.node.NodeTypes",
"org.jbpm.graph.node.ProcessFactory",
@@ -72,8 +71,11 @@
"org.jbpm.jpdl.par.JpdlArchiveParser",
"org.jbpm.jpdl.xml.JpdlXmlReader",
"org.jbpm.jpdl.xml.JpdlXmlWriter",
+ "org.jbpm.persistence.db.StaleObjectLogConfigurer$LogWrapper",
"org.jbpm.util.Clock$DefaultDateGenerator",
"org.jbpm.util.CustomLoaderObjectInputStream",
+ "org.jbpm.util.NodeIterator",
+ "org.jbpm.util.XmlUtil$ElementPredicate",
"org.jbpm.web.JobExecutorLauncher",
"org.jbpm.web.JbpmConfigurationCloser"
};
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/graph/node/CustomSubProcessResolverTest.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/graph/node/CustomSubProcessResolverTest.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/graph/node/CustomSubProcessResolverTest.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -5,70 +5,69 @@
import org.dom4j.Element;
import org.jbpm.AbstractJbpmTestCase;
+import org.jbpm.JbpmConfiguration;
+import org.jbpm.JbpmContext;
import org.jbpm.graph.def.ProcessDefinition;
-public class CustomSubProcessResolverTest extends AbstractJbpmTestCase
-{
-
- MapBasedProcessRepository mapBasedProcessRepository = new MapBasedProcessRepository();
+public class CustomSubProcessResolverTest extends AbstractJbpmTestCase {
- SubProcessResolver originalSubProcessResolver = ProcessState.defaultSubProcessResolver;
+ private JbpmContext jbpmContext;
- protected void setUp() throws Exception
- {
+ protected void setUp() throws Exception {
super.setUp();
- ProcessState.setDefaultSubProcessResolver(mapBasedProcessRepository);
+ JbpmConfiguration jbpmConfiguration = JbpmConfiguration.parseXmlString("<jbpm-configuration>"
+ + " <bean name='jbpm.sub.process.resolver' class='"
+ + MapBasedProcessRepository.class.getName()
+ + "' singleton='true' />"
+ + "</jbpm-configuration>");
+ jbpmContext = jbpmConfiguration.createJbpmContext();
}
- protected void tearDown() throws Exception
- {
- ProcessState.setDefaultSubProcessResolver(originalSubProcessResolver);
+ protected void tearDown() throws Exception {
+ jbpmContext.close();
+ jbpmContext.getJbpmConfiguration().close();
super.tearDown();
}
- public static class MapBasedProcessRepository implements SubProcessResolver
- {
+ public static class MapBasedProcessRepository implements SubProcessResolver {
private static final long serialVersionUID = 1L;
- Map processes = new HashMap();
+ private Map processes = new HashMap();
- public void add(ProcessDefinition processDefinition)
- {
+ public void add(ProcessDefinition processDefinition) {
processes.put(processDefinition.getName(), processDefinition);
}
- public ProcessDefinition findSubProcess(Element subProcessElement)
- {
+ public ProcessDefinition findSubProcess(Element subProcessElement) {
String processName = subProcessElement.attributeValue("name");
- return (ProcessDefinition)processes.get(processName);
+ return (ProcessDefinition) processes.get(processName);
}
}
-
+
public void testMapBasedProcessResolving() {
- ProcessDefinition subDefinition = ProcessDefinition.parseXmlString(
- "<process-definition name='sub'>" +
- " <start-state>" +
- " <transition to='end' />" +
- " </start-state>" +
- " <end-state name='end' />" +
- "</process-definition>"
- );
- mapBasedProcessRepository.add(subDefinition);
+ ProcessDefinition subDefinition = ProcessDefinition.parseXmlString("<process-definition name='sub'>"
+ + " <start-state>"
+ + " <transition to='end' />"
+ + " </start-state>"
+ + " <end-state name='end' />"
+ + "</process-definition>");
+ MapBasedProcessRepository processRepository = (MapBasedProcessRepository) jbpmContext
+ .getObjectFactory()
+ .createObject("jbpm.sub.process.resolver");
+ processRepository.add(subDefinition);
- ProcessDefinition superDefinition = ProcessDefinition.parseXmlString(
- "<process-definition name='super'>" +
- " <start-state>" +
- " <transition to='p' />" +
- " </start-state>" +
- " <process-state name='p'>" +
- " <sub-process name='sub' />" +
- " <transition to='end' />" +
- " </process-state>" +
- " <end-state name='end' />" +
- "</process-definition>"
- );
+ ProcessDefinition superDefinition = ProcessDefinition.parseXmlString("<process-definition name='super'>"
+ + " <start-state>"
+ + " <transition to='p' />"
+ + " </start-state>"
+ + " <process-state name='p'>"
+ + " <sub-process name='sub' />"
+ + " <transition to='end' />"
+ + " </process-state>"
+ + " <end-state name='end' />"
+ + "</process-definition>");
ProcessState processState = (ProcessState) superDefinition.getNode("p");
- assertEquals(subDefinition, processState.getSubProcessDefinition());
+ assertSame(subDefinition, processState.getSubProcessDefinition());
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/jbpm983/JBPM983Test.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/jbpm983/JBPM983Test.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/jbpm983/JBPM983Test.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -1,8 +1,5 @@
package org.jbpm.jbpm983;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
import org.jbpm.db.AbstractDbTestCase;
import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.def.ProcessDefinition;
@@ -121,20 +118,7 @@
private static final long serialVersionUID = 1L;
public void execute(ExecutionContext executionContext) throws Exception {
- Log log = LogFactory.getLog(JBPM983Test.class);
- String line = executionContext.getProcessInstance()
- + " | "
- + executionContext.getNode()
- + " | "
- + executionContext.getToken();
- log.info("BEGIN " + line);
-
- for (int i = 0; i < 5; i++) {
- log.info("PROGRESS " + line);
- Thread.sleep(100);
- }
-
- log.info("END " + line);
+ Thread.sleep(200);
executionContext.leaveNode();
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/jpdl/el/DecisionExpressionTest.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/jpdl/el/DecisionExpressionTest.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/jpdl/el/DecisionExpressionTest.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -82,7 +82,7 @@
fail("expected exception");
}
catch (JbpmException e) {
- assert e.getMessage().indexOf("null") != -1 : e;
+ assert e.getMessage().indexOf("transition") != -1 : e;
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/jpdl/par/ProcessClassLoaderTest.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/jpdl/par/ProcessClassLoaderTest.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/jpdl/par/ProcessClassLoaderTest.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -47,7 +47,6 @@
// verify that the default uses the jbpm-lib-classloader
assertSame(ClassLoaderUtil.class.getClassLoader(), contextClassLoader.getParent());
-
contextLoadedActionInvocations++;
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/logging/log/ProcessLogDbTest.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/logging/log/ProcessLogDbTest.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/logging/log/ProcessLogDbTest.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -28,32 +28,29 @@
import org.jbpm.graph.exe.Token;
import org.jbpm.util.DateDbTestUtil;
-public class ProcessLogDbTest extends AbstractDbTestCase
-{
+public class ProcessLogDbTest extends AbstractDbTestCase {
- public void testMessageLogMessage()
- {
+ public void testMessageLogMessage() {
MessageLog messageLog = new MessageLog("piece of cake");
- messageLog = (MessageLog)saveAndReload(messageLog);
+ messageLog = (MessageLog) saveAndReload(messageLog);
assertEquals("piece of cake", messageLog.getMessage());
session.delete(messageLog);
}
- public void testProcessLogDate()
- {
+ public void testProcessLogDate() {
Date now = new Date();
ProcessLog processLog = new MessageLog();
processLog.setDate(now);
processLog = saveAndReload(processLog);
// assertEquals(now, processLog.getDate());
// assertEquals(now.getTime(), processLog.getDate().getTime());
- assertEquals(DateDbTestUtil.getInstance().convertDateToSeconds(now), DateDbTestUtil.getInstance().convertDateToSeconds(processLog.getDate()));
+ assertEquals(DateDbTestUtil.getInstance().convertDateToSeconds(now), DateDbTestUtil.getInstance()
+ .convertDateToSeconds(processLog.getDate()));
session.delete(processLog);
}
- public void testProcessLogToken()
- {
+ public void testProcessLogToken() {
Token token = new Token();
session.save(token);
ProcessLog processLog = new MessageLog();
@@ -65,29 +62,28 @@
session.delete(token);
}
- public void testParentChildRelation()
- {
+ public void testParentChildRelation() {
CompositeLog compositeLog = new CompositeLog();
ProcessLog procLog = new MessageLog("one");
- session.save(procLog);
compositeLog.addChild(procLog);
- procLog = new MessageLog("two");
session.save(procLog);
+
+ procLog = new MessageLog("two");
compositeLog.addChild(procLog);
- procLog = new MessageLog("three");
session.save(procLog);
+
+ procLog = new MessageLog("three");
compositeLog.addChild(procLog);
+ session.save(procLog);
- compositeLog = (CompositeLog)saveAndReload(compositeLog);
+ compositeLog = (CompositeLog) saveAndReload(compositeLog);
assertEquals(3, compositeLog.getChildren().size());
- Iterator iter = compositeLog.getChildren().iterator();
- while (iter.hasNext())
- {
- ProcessLog childLog = (ProcessLog)iter.next();
+ for (Iterator iter = compositeLog.getChildren().iterator(); iter.hasNext();) {
+ ProcessLog childLog = (ProcessLog) iter.next();
assertSame(compositeLog, childLog.getParent());
}
-
+
session.delete(compositeLog);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/persistence/db/PersistenceConfigurationDbTest.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/persistence/db/PersistenceConfigurationDbTest.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/persistence/db/PersistenceConfigurationDbTest.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -35,7 +35,10 @@
+ " <bean class='org.jbpm.persistence.db.DbPersistenceServiceFactory'>"
+ " <field name='isTransactionEnabled'><false /></field>"
+ " </bean>"
- + " </factory>" + " </service>" + " </jbpm-context>" + "</jbpm-configuration>");
+ + " </factory>"
+ + " </service>"
+ + " </jbpm-context>"
+ + "</jbpm-configuration>");
DbPersistenceServiceFactory dbPersistenceServiceFactory = (DbPersistenceServiceFactory) jbpmConfiguration.getServiceFactory("persistence");
assertFalse(dbPersistenceServiceFactory.isTransactionEnabled());
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/persistence/db/PersistenceServiceDbTest.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/persistence/db/PersistenceServiceDbTest.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/persistence/db/PersistenceServiceDbTest.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -241,7 +241,6 @@
public void testUserSuppliedSessionWithRollback() throws Exception {
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
-
try {
DbPersistenceServiceFactory persistenceServiceFactory = (DbPersistenceServiceFactory) jbpmContext.getServiceFactory(Services.SERVICENAME_PERSISTENCE);
SessionFactory sessionFactory = persistenceServiceFactory.getSessionFactory();
@@ -252,7 +251,6 @@
jbpmContext.setSession(session);
jbpmContext.setRollbackOnly();
-
}
finally {
try {
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/scheduler/exe/SchedulerTest.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/scheduler/exe/SchedulerTest.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/scheduler/exe/SchedulerTest.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -79,31 +79,30 @@
}
}
- static JbpmConfiguration jbpmConfiguration = JbpmConfiguration.parseXmlString("<jbpm-configuration>"
- + " <jbpm-context>"
- + " <service name='scheduler' factory='org.jbpm.scheduler.exe.SchedulerTest$TestSchedulerServiceFactory' />"
- + " </jbpm-context>"
- + " <bean name='jbpm.task.instance.factory' class='org.jbpm.taskmgmt.impl.DefaultTaskInstanceFactoryImpl' singleton='true' />"
- + "</jbpm-configuration>");
+ private static JbpmConfiguration jbpmConfiguration = JbpmConfiguration.parseXmlString("<jbpm-configuration>"
+ + " <jbpm-context>"
+ + " <service name='scheduler' factory='" + TestSchedulerServiceFactory.class.getName() + "' />"
+ + " </jbpm-context>"
+ + "</jbpm-configuration>");
public void testTimerCreation() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='catch crooks' />"
- + " </start-state>"
- + " <state name='catch crooks'>"
- + " <timer name='reminder' "
- + " duedate='3 business hours' "
- + " transition='time-out-transition' >"
- + " <action class='the-remainder-action-class-name' />"
- + " </timer>"
- + " </state>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='catch crooks' />"
+ + " </start-state>"
+ + " <state name='catch crooks'>"
+ + " <timer name='reminder' "
+ + " duedate='3 business hours' "
+ + " transition='time-out-transition' >"
+ + " <action class='the-remainder-action-class-name' />"
+ + " </timer>"
+ + " </state>"
+ + "</process-definition>");
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
TestSchedulerService testSchedulerService = (TestSchedulerService) jbpmContext.getServices()
- .getSchedulerService();
+ .getSchedulerService();
ProcessInstance processInstance = new ProcessInstance(processDefinition);
processInstance.signal();
@@ -115,8 +114,8 @@
// System.out.println("due date: "+scheduledTimer.getDueDate());
assertNotNull(scheduledTimer.getDueDate());
assertEquals("the-remainder-action-class-name", scheduledTimer.getAction()
- .getActionDelegation()
- .getClassName());
+ .getActionDelegation()
+ .getClassName());
assertSame(processInstance.getRootToken(), scheduledTimer.getToken());
assertEquals("time-out-transition", scheduledTimer.getTransitionName());
}
@@ -127,22 +126,22 @@
public void testTimerCreationRepeat() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='catch crooks' />"
- + " </start-state>"
- + " <state name='catch crooks'>"
- + " <timer name='reminder' "
- + " duedate='3 business hours' "
- + " repeat='10 business minutes' >"
- + " <action class='the-remainder-action-class-name' />"
- + " </timer>"
- + " </state>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='catch crooks' />"
+ + " </start-state>"
+ + " <state name='catch crooks'>"
+ + " <timer name='reminder' "
+ + " duedate='3 business hours' "
+ + " repeat='10 business minutes' >"
+ + " <action class='the-remainder-action-class-name' />"
+ + " </timer>"
+ + " </state>"
+ + "</process-definition>");
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
TestSchedulerService testSchedulerService = (TestSchedulerService) jbpmContext.getServices()
- .getSchedulerService();
+ .getSchedulerService();
ProcessInstance processInstance = new ProcessInstance(processDefinition);
processInstance.signal();
@@ -155,8 +154,8 @@
assertNotNull(scheduledTimer.getDueDate());
assertEquals("10 business minutes", scheduledTimer.getRepeat());
assertEquals("the-remainder-action-class-name", scheduledTimer.getAction()
- .getActionDelegation()
- .getClassName());
+ .getActionDelegation()
+ .getClassName());
assertSame(processInstance.getRootToken(), scheduledTimer.getToken());
}
finally {
@@ -166,26 +165,26 @@
public void testCreateTimerAction() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='catch crooks' />"
- + " </start-state>"
- + " <state name='catch crooks'>"
- + " <event type='node-enter'>"
- + " <create-timer name='reminder' "
- + " duedate='3 business hours' "
- + " transition='time-out-transition' >"
- + " <action class='the-remainder-action-class-name' />"
- + " </create-timer>"
- + " </event>"
- + " <transition to='end'/>"
- + " </state>"
- + " <end-state name='end'/>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='catch crooks' />"
+ + " </start-state>"
+ + " <state name='catch crooks'>"
+ + " <event type='node-enter'>"
+ + " <create-timer name='reminder' "
+ + " duedate='3 business hours' "
+ + " transition='time-out-transition' >"
+ + " <action class='the-remainder-action-class-name' />"
+ + " </create-timer>"
+ + " </event>"
+ + " <transition to='end'/>"
+ + " </state>"
+ + " <end-state name='end'/>"
+ + "</process-definition>");
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
TestSchedulerService testSchedulerService = (TestSchedulerService) jbpmContext.getServices()
- .getSchedulerService();
+ .getSchedulerService();
ProcessInstance processInstance = new ProcessInstance(processDefinition);
processInstance.signal();
@@ -197,8 +196,8 @@
// System.out.println("due date: "+scheduledTimer.getDueDate());
assertNotNull(scheduledTimer.getDueDate());
assertEquals("the-remainder-action-class-name", scheduledTimer.getAction()
- .getActionDelegation()
- .getClassName());
+ .getActionDelegation()
+ .getClassName());
assertSame(processInstance.getRootToken(), scheduledTimer.getToken());
assertEquals("time-out-transition", scheduledTimer.getTransitionName());
@@ -214,26 +213,26 @@
public void testCreateTimerActionRepeat() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='catch crooks' />"
- + " </start-state>"
- + " <state name='catch crooks'>"
- + " <event type='node-enter'>"
- + " <create-timer name='reminder' "
- + " duedate='3 business hours' "
- + " repeat='10 business minutes'>"
- + " <action class='the-remainder-action-class-name' />"
- + " </create-timer>"
- + " </event>"
- + " <transition to='end'/>"
- + " </state>"
- + " <end-state name='end'/>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='catch crooks' />"
+ + " </start-state>"
+ + " <state name='catch crooks'>"
+ + " <event type='node-enter'>"
+ + " <create-timer name='reminder' "
+ + " duedate='3 business hours' "
+ + " repeat='10 business minutes'>"
+ + " <action class='the-remainder-action-class-name' />"
+ + " </create-timer>"
+ + " </event>"
+ + " <transition to='end'/>"
+ + " </state>"
+ + " <end-state name='end'/>"
+ + "</process-definition>");
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
TestSchedulerService testSchedulerService = (TestSchedulerService) jbpmContext.getServices()
- .getSchedulerService();
+ .getSchedulerService();
ProcessInstance processInstance = new ProcessInstance(processDefinition);
processInstance.signal();
@@ -246,8 +245,8 @@
assertNotNull(scheduledTimer.getDueDate());
assertEquals("10 business minutes", scheduledTimer.getRepeat());
assertEquals("the-remainder-action-class-name", scheduledTimer.getAction()
- .getActionDelegation()
- .getClassName());
+ .getActionDelegation()
+ .getClassName());
assertSame(processInstance.getRootToken(), scheduledTimer.getToken());
// while we are at it, i might as well check if the cancel timer is not executed ;)
@@ -262,25 +261,25 @@
public void testTimerCancelAction() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='catch crooks' />"
- + " </start-state>"
- + " <state name='catch crooks'>"
- + " <timer name='reminder' "
- + " duedate='3 business hours' "
- + " repeat='10 business minutes'"
- + " transition='time-out-transition' >"
- + " <action class='the-remainder-action-class-name' />"
- + " </timer>"
- + " <transition to='end'/>"
- + " </state>"
- + " <end-state name='end'/>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='catch crooks' />"
+ + " </start-state>"
+ + " <state name='catch crooks'>"
+ + " <timer name='reminder' "
+ + " duedate='3 business hours' "
+ + " repeat='10 business minutes'"
+ + " transition='time-out-transition' >"
+ + " <action class='the-remainder-action-class-name' />"
+ + " </timer>"
+ + " <transition to='end'/>"
+ + " </state>"
+ + " <end-state name='end'/>"
+ + "</process-definition>");
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
TestSchedulerService testSchedulerService = (TestSchedulerService) jbpmContext.getServices()
- .getSchedulerService();
+ .getSchedulerService();
ProcessInstance processInstance = new ProcessInstance(processDefinition);
processInstance.signal();
@@ -291,7 +290,6 @@
Object[] cancelledTimer = (Object[]) cancelledTimerNames.get(0);
assertEquals("reminder", cancelledTimer[0]);
assertSame(processInstance.getRootToken(), cancelledTimer[1]);
-
}
finally {
jbpmContext.close();
@@ -300,7 +298,7 @@
public static class TimerCreateAction implements ActionHandler {
private static final long serialVersionUID = 1L;
- static Timer timer = null;
+ static Timer timer;
public void execute(ExecutionContext executionContext) throws Exception {
timer = executionContext.getTimer();
@@ -309,21 +307,21 @@
public void testTimerEvent() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='catch crooks' />"
- + " </start-state>"
- + " <state name='catch crooks'>"
- + " <event type='timer-create'>"
- + " <action class='org.jbpm.scheduler.exe.SchedulerTest$TimerCreateAction' />"
- + " </event>"
- + " <timer name='reminder' "
- + " duedate='2 seconds' >"
- + " <action class='the-timer-create-event-class-name' />"
- + " </timer>"
- + " <transition to='end'/>"
- + " </state>"
- + " <end-state name='end'/>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='catch crooks' />"
+ + " </start-state>"
+ + " <state name='catch crooks'>"
+ + " <event type='timer-create'>"
+ + " <action class='org.jbpm.scheduler.exe.SchedulerTest$TimerCreateAction' />"
+ + " </event>"
+ + " <timer name='reminder' "
+ + " duedate='2 seconds' >"
+ + " <action class='the-timer-create-event-class-name' />"
+ + " </timer>"
+ + " <transition to='end'/>"
+ + " </state>"
+ + " <end-state name='end'/>"
+ + "</process-definition>");
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
@@ -332,9 +330,8 @@
processInstance.signal();
assertNotNull(TimerCreateAction.timer);
assertEquals("the-timer-create-event-class-name", TimerCreateAction.timer.getAction()
- .getActionDelegation()
- .getClassName());
-
+ .getActionDelegation()
+ .getClassName());
}
finally {
jbpmContext.close();
@@ -343,16 +340,15 @@
public void testUnavailableSchedulerService() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='catch crooks' />"
- + " </start-state>"
- + " <state name='catch crooks'>"
- + " <timer name='reminder' "
- + " duedate='2 seconds' >"
- + " <action class='the-timer-create-event-class-name' />"
- + " </timer>"
- + " </state>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='catch crooks' />"
+ + " </start-state>"
+ + " <state name='catch crooks'>"
+ + " <timer name='reminder' "
+ + " duedate='2 seconds' >"
+ + " <action class='the-timer-create-event-class-name' />"
+ + " </timer>"
+ + " </state>" + "</process-definition>");
try {
new ProcessInstance(processDefinition).signal();
@@ -365,22 +361,20 @@
public void testTaskTimerExecution() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='timed task' />"
- + " </start-state>"
- + " <task-node name='timed task'>"
- + " <task name='find the hole in the market'>"
- + " <timer duedate='23 business seconds'>"
- + " <action class='geftem-eu-shuppe-oender-ze-konte'/>"
- + " </timer>"
- + " </task>"
- + " </task-node>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='timed task' />"
+ + " </start-state>"
+ + " <task-node name='timed task'>"
+ + " <task name='find the hole in the market'>"
+ + " <timer duedate='23 business seconds'>"
+ + " <action class='geftem-eu-shuppe-oender-ze-konte'/>"
+ + " </timer>"
+ + " </task>" + " </task-node>" + "</process-definition>");
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
TestSchedulerService testSchedulerService = (TestSchedulerService) jbpmContext.getServices()
- .getSchedulerService();
+ .getSchedulerService();
ProcessInstance processInstance = new ProcessInstance(processDefinition);
processInstance.signal();
@@ -393,10 +387,10 @@
}
}
- static boolean isCustomized = false;
public static class TimerCustomizingAction implements ActionHandler {
private static final long serialVersionUID = 1L;
+ static boolean isCustomized = false;
public void execute(ExecutionContext executionContext) throws Exception {
assertNotNull(executionContext.getTimer());
@@ -407,27 +401,24 @@
public void testTaskTimerActionExecution() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='timed task' />"
- + " </start-state>"
- + " <task-node name='timed task'>"
- + " <task name='find the hole in the market'>"
- + " <event type='timer-create'>"
- + " <action class='org.jbpm.scheduler.exe.SchedulerTest$TimerCustomizingAction' />"
- + " </event>"
- + " <timer name='reminder' duedate='23 business seconds'>"
- + " <action class='geftem-eu-shuppe-oender-ze-konte'/>"
- + " </timer>"
- + " </task>"
- + " </task-node>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='timed task' />"
+ + " </start-state>"
+ + " <task-node name='timed task'>"
+ + " <task name='find the hole in the market'>"
+ + " <event type='timer-create'>"
+ + " <action class='org.jbpm.scheduler.exe.SchedulerTest$TimerCustomizingAction' />"
+ + " </event>"
+ + " <timer name='reminder' duedate='23 business seconds'>"
+ + " <action class='geftem-eu-shuppe-oender-ze-konte'/>"
+ + " </timer>"
+ + " </task>" + " </task-node>" + "</process-definition>");
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
ProcessInstance processInstance = new ProcessInstance(processDefinition);
processInstance.signal();
- assertTrue(isCustomized);
-
+ assertTrue(TimerCustomizingAction.isCustomized);
}
finally {
jbpmContext.close();
@@ -436,29 +427,30 @@
public void testTimerELCreation() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='get old' />"
- + " </start-state>"
- + " <state name='get old'>"
- + " <timer name='pension' "
- + " duedate='#{dateOfPension}' "
- + " transition='time-out-transition' >"
- + " <action class='the-remainder-action-class-name' />"
- + " </timer>"
- + " </state>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='get old' />"
+ + " </start-state>"
+ + " <state name='get old'>"
+ + " <timer name='pension' "
+ + " duedate='#{dateOfPension}' "
+ + " transition='time-out-transition' >"
+ + " <action class='the-remainder-action-class-name' />"
+ + " </timer>"
+ + " </state>"
+ + "</process-definition>");
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
TestSchedulerService testSchedulerService = (TestSchedulerService) jbpmContext.getServices()
- .getSchedulerService();
+ .getSchedulerService();
ProcessInstance processInstance = new ProcessInstance(processDefinition);
Calendar dateOfPension = Calendar.getInstance();
dateOfPension.set(2036, 1, 12, 2, 10, 0);
dateOfPension.clear(Calendar.MILLISECOND);
- processInstance.getContextInstance().setVariable("dateOfPension", dateOfPension.getTime());
+ processInstance.getContextInstance()
+ .setVariable("dateOfPension", dateOfPension.getTime());
processInstance.signal();
@@ -474,8 +466,8 @@
assertEquals(dateOfPensionTest.getTime(), scheduledTimer.getDueDate());
assertNotNull(scheduledTimer.getDueDate());
assertEquals("the-remainder-action-class-name", scheduledTimer.getAction()
- .getActionDelegation()
- .getClassName());
+ .getActionDelegation()
+ .getClassName());
assertSame(processInstance.getRootToken(), scheduledTimer.getToken());
assertEquals("time-out-transition", scheduledTimer.getTransitionName());
}
@@ -486,22 +478,22 @@
public void testTimerELPlusCreation() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='get old' />"
- + " </start-state>"
- + " <state name='get old'>"
- + " <timer name='pension' "
- + " duedate='#{dateOfBirth} + 65 years' "
- + " transition='time-out-transition' >"
- + " <action class='the-remainder-action-class-name' />"
- + " </timer>"
- + " </state>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='get old' />"
+ + " </start-state>"
+ + " <state name='get old'>"
+ + " <timer name='pension' "
+ + " duedate='#{dateOfBirth} + 65 years' "
+ + " transition='time-out-transition' >"
+ + " <action class='the-remainder-action-class-name' />"
+ + " </timer>"
+ + " </state>"
+ + "</process-definition>");
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
TestSchedulerService testSchedulerService = (TestSchedulerService) jbpmContext.getServices()
- .getSchedulerService();
+ .getSchedulerService();
ProcessInstance processInstance = new ProcessInstance(processDefinition);
@@ -524,8 +516,8 @@
assertEquals(dateOfPension.getTime(), scheduledTimer.getDueDate());
assertEquals("the-remainder-action-class-name", scheduledTimer.getAction()
- .getActionDelegation()
- .getClassName());
+ .getActionDelegation()
+ .getClassName());
assertSame(processInstance.getRootToken(), scheduledTimer.getToken());
assertEquals("time-out-transition", scheduledTimer.getTransitionName());
}
@@ -536,29 +528,30 @@
public void testTimerELMinusCreation() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='get old' />"
- + " </start-state>"
- + " <state name='get old'>"
- + " <timer name='pensionReminder' "
- + " duedate='#{dateOfPension} - 1 year' "
- + " transition='time-out-transition' >"
- + " <action class='the-remainder-action-class-name' />"
- + " </timer>"
- + " </state>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='get old' />"
+ + " </start-state>"
+ + " <state name='get old'>"
+ + " <timer name='pensionReminder' "
+ + " duedate='#{dateOfPension} - 1 year' "
+ + " transition='time-out-transition' >"
+ + " <action class='the-remainder-action-class-name' />"
+ + " </timer>"
+ + " </state>"
+ + "</process-definition>");
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
TestSchedulerService testSchedulerService = (TestSchedulerService) jbpmContext.getServices()
- .getSchedulerService();
+ .getSchedulerService();
ProcessInstance processInstance = new ProcessInstance(processDefinition);
Calendar dateOfPension = Calendar.getInstance();
dateOfPension.set(2036, 1, 12, 2, 10, 0);
dateOfPension.clear(Calendar.MILLISECOND);
- processInstance.getContextInstance().setVariable("dateOfPension", dateOfPension.getTime());
+ processInstance.getContextInstance()
+ .setVariable("dateOfPension", dateOfPension.getTime());
processInstance.signal();
@@ -574,8 +567,8 @@
assertEquals(dateOfPensionReminder.getTime(), scheduledTimer.getDueDate());
assertEquals("the-remainder-action-class-name", scheduledTimer.getAction()
- .getActionDelegation()
- .getClassName());
+ .getActionDelegation()
+ .getClassName());
assertSame(processInstance.getRootToken(), scheduledTimer.getToken());
assertEquals("time-out-transition", scheduledTimer.getTransitionName());
}
@@ -586,22 +579,22 @@
public void testTimerELCalendarCreation() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='get old' />"
- + " </start-state>"
- + " <state name='get old'>"
- + " <timer name='pension' "
- + " duedate='#{dateOfPension}' "
- + " transition='time-out-transition' >"
- + " <action class='the-remainder-action-class-name' />"
- + " </timer>"
- + " </state>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='get old' />"
+ + " </start-state>"
+ + " <state name='get old'>"
+ + " <timer name='pension' "
+ + " duedate='#{dateOfPension}' "
+ + " transition='time-out-transition' >"
+ + " <action class='the-remainder-action-class-name' />"
+ + " </timer>"
+ + " </state>"
+ + "</process-definition>");
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
TestSchedulerService testSchedulerService = (TestSchedulerService) jbpmContext.getServices()
- .getSchedulerService();
+ .getSchedulerService();
ProcessInstance processInstance = new ProcessInstance(processDefinition);
@@ -624,8 +617,8 @@
assertEquals(dateOfPensionTest.getTime(), scheduledTimer.getDueDate());
assertNotNull(scheduledTimer.getDueDate());
assertEquals("the-remainder-action-class-name", scheduledTimer.getAction()
- .getActionDelegation()
- .getClassName());
+ .getActionDelegation()
+ .getClassName());
assertSame(processInstance.getRootToken(), scheduledTimer.getToken());
assertEquals("time-out-transition", scheduledTimer.getTransitionName());
}
@@ -636,17 +629,17 @@
public void testTimerELUnsupportedFormatCreation() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='get old' />"
- + " </start-state>"
- + " <state name='get old'>"
- + " <timer name='pension' "
- + " duedate='#{dateOfPension}' "
- + " transition='time-out-transition' >"
- + " <action class='the-remainder-action-class-name' />"
- + " </timer>"
- + " </state>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='get old' />"
+ + " </start-state>"
+ + " <state name='get old'>"
+ + " <timer name='pension' "
+ + " duedate='#{dateOfPension}' "
+ + " transition='time-out-transition' >"
+ + " <action class='the-remainder-action-class-name' />"
+ + " </timer>"
+ + " </state>"
+ + "</process-definition>");
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
ProcessInstance processInstance = new ProcessInstance(processDefinition);
@@ -655,7 +648,7 @@
processInstance.signal();
}
catch (JbpmException je) {
- assert je.getMessage().indexOf("invalid base date") != -1 : je;
+ assert je.getMessage().indexOf("date") != -1 : je;
}
finally {
jbpmContext.close();
@@ -669,7 +662,7 @@
processInstance.signal();
}
catch (JbpmException je) {
- assert je.getMessage().indexOf("invalid base date") != -1 : je;
+ assert je.getMessage().indexOf("date") != -1 : je;
}
finally {
jbpmContext.close();
@@ -678,17 +671,17 @@
public void testTimerErrorCreation() {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
- + " <start-state>"
- + " <transition to='get old' />"
- + " </start-state>"
- + " <state name='get old'>"
- + " <timer name='pension' "
- + " duedate='1 demo' "
- + " transition='time-out-transition' >"
- + " <action class='the-remainder-action-class-name' />"
- + " </timer>"
- + " </state>"
- + "</process-definition>");
+ + " <start-state>"
+ + " <transition to='get old' />"
+ + " </start-state>"
+ + " <state name='get old'>"
+ + " <timer name='pension' "
+ + " duedate='1 demo' "
+ + " transition='time-out-transition' >"
+ + " <action class='the-remainder-action-class-name' />"
+ + " </timer>"
+ + " </state>"
+ + "</process-definition>");
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/resources/log4j.xml
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/resources/log4j.xml 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/resources/log4j.xml 2010-04-15 13:46:26 UTC (rev 6257)
@@ -34,7 +34,7 @@
<!-- ================ -->
<category name="org.jbpm">
- <priority value="DEBUG" />
+ <priority value="INFO" />
</category>
<category name="org.hibernate">
Modified: jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/CommandListenerBean.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/CommandListenerBean.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/CommandListenerBean.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -48,18 +48,18 @@
import org.jbpm.persistence.db.StaleObjectLogConfigurer;
/**
- * This message-driven bean listens for {@link ObjectMessage object messages}
- * containing a command instance. The received commands are executed by the
- * {@link CommandServiceBean command service} bean, using the local interface.
+ * This message-driven bean listens for {@link ObjectMessage object messages} containing a
+ * command instance. The received commands are executed by the {@link CommandServiceBean command
+ * service} bean, using the local interface.
*
- * The body of the message must be a Java object that implements the
- * {@link Command} interface. The message properties, if any, are ignored.
+ * The body of the message must be a Java object that implements the {@link Command} interface.
+ * The message properties, if any, are ignored.
*
* <h3>Environment</h3>
*
* <p>
- * The environment entries and resources available for customization are
- * summarized in the table below.
+ * The environment entries and resources available for customization are summarized in the table
+ * below.
* </p>
*
* <table border="1">
@@ -71,22 +71,20 @@
* <tr>
* <td><code>ejb/LocalCommandServiceBean</code></td>
* <td>EJB Reference</td>
- * <td>Link to the local {@linkplain CommandServiceBean session bean} that
- * executes commands on a separate jBPM context.</td>
+ * <td>Link to the local {@linkplain CommandServiceBean session bean} that executes commands on
+ * a separate jBPM context.</td>
* </tr>
* <tr>
* <td><code>jms/JbpmConnectionFactory</code></td>
* <td>Resource Manager Reference</td>
- * <td>Logical name of the factory that provides JMS connections for producing
- * result messages. Required for command messages that indicate a reply
- * destination.</td>
+ * <td>Logical name of the factory that provides JMS connections for producing result messages.
+ * Required for command messages that indicate a reply destination.</td>
* </tr>
* <tr>
* <td><code>jms/DeadLetterQueue</code></td>
* <td>Message Destination Reference</td>
- * <td>Messages which do not contain a command are sent to the queue referenced
- * here. Optional; if absent, such messages are rejected, which may cause the
- * container to redeliver.</td>
+ * <td>Messages which do not contain a command are sent to the queue referenced here. Optional;
+ * if absent, such messages are rejected, which may cause the container to redeliver.</td>
* </tr>
* </table>
*
@@ -120,8 +118,7 @@
Object result = commandService.execute(command);
// send a response back if a "reply to" destination is set
Destination replyTo = message.getJMSReplyTo();
- if (replyTo != null
- && (result instanceof Serializable || result == null)) {
+ if (replyTo != null && (result instanceof Serializable || result == null)) {
sendResult((Serializable) result, replyTo, message.getJMSMessageID());
}
}
@@ -130,8 +127,8 @@
messageDrivenContext.setRollbackOnly();
// if this is a locking exception, keep it quiet
if (DbPersistenceService.isLockingException(e)) {
- StaleObjectLogConfigurer.getStaleObjectExceptionsLog()
- .error("failed to execute " + command, e);
+ StaleObjectLogConfigurer.getStaleObjectExceptionsLog().error("failed to execute "
+ + command, e);
}
else {
log.error("failed to execute " + command, e);
@@ -166,12 +163,12 @@
// lookup dead letter queue
try {
Context jndiContext = new InitialContext();
- deadLetterQueue =
- (Destination) jndiContext.lookup("java:comp/env/jms/DeadLetterQueue");
+ deadLetterQueue = (Destination) jndiContext.lookup("java:comp/env/jms/DeadLetterQueue");
}
catch (NamingException e) {
- log.debug("failed to retrieve dead letter queue, rejecting: "
- + message);
+ if (log.isDebugEnabled()) {
+ log.debug("failed to retrieve dead letter queue, rejecting: " + message);
+ }
messageDrivenContext.setRollbackOnly();
return;
}
@@ -186,9 +183,9 @@
}
}
- private void sendResult(Serializable result, Destination destination,
- String correlationId) throws JMSException {
- log.debug("sending " + result + " to " + destination);
+ private void sendResult(Serializable result, Destination destination, String correlationId)
+ throws JMSException {
+ if (log.isDebugEnabled()) log.debug("sending " + result + " to " + destination);
Session jmsSession = createSession();
try {
Message resultMessage = jmsSession.createObjectMessage(result);
@@ -206,9 +203,9 @@
jmsConnection = jmsConnectionFactory.createConnection();
}
/*
- * if the connection supports xa, the session will be transacted, else the
- * session will auto acknowledge; in either case no explicit transaction
- * control must be performed - see ejb 2.1 - 17.3.5
+ * if the connection supports xa, the session will be transacted, else the session will auto
+ * acknowledge; in either case no explicit transaction control must be performed - see ejb
+ * 2.1 - 17.3.5
*/
return jmsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
}
@@ -237,12 +234,10 @@
try {
Context jndiContext = new InitialContext();
- LocalCommandServiceHome commandServiceHome =
- (LocalCommandServiceHome) jndiContext.lookup("java:comp/env/ejb/LocalCommandServiceBean");
+ LocalCommandServiceHome commandServiceHome = (LocalCommandServiceHome) jndiContext.lookup("java:comp/env/ejb/LocalCommandServiceBean");
commandService = commandServiceHome.create();
- jmsConnectionFactory =
- (ConnectionFactory) jndiContext.lookup("java:comp/env/jms/JbpmConnectionFactory");
+ jmsConnectionFactory = (ConnectionFactory) jndiContext.lookup("java:comp/env/jms/JbpmConnectionFactory");
}
catch (NamingException e) {
throw new EJBException("error retrieving command service home", e);
Modified: jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/CommandServiceBean.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/CommandServiceBean.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/CommandServiceBean.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -37,18 +37,17 @@
import org.jbpm.command.CommandService;
import org.jbpm.msg.jms.JmsMessageServiceFactory;
import org.jbpm.persistence.jta.JtaDbPersistenceServiceFactory;
-import org.jbpm.tx.TxService;
/**
- * Stateless session bean that executes {@linkplain Command commands} by calling
- * their {@link Command#execute(JbpmContext) execute} method on a separate
- * {@link JbpmContext jBPM context}.
+ * Stateless session bean that executes {@linkplain Command commands} by calling their
+ * {@link Command#execute(JbpmContext) execute} method on a separate {@link JbpmContext jBPM
+ * context}.
*
* <h3>Environment</h3>
*
* <p>
- * The environment entries and resources available for customization are
- * summarized in the table below.
+ * The environment entries and resources available for customization are summarized in the table
+ * below.
* </p>
*
* <table border="1">
@@ -60,41 +59,37 @@
* <tr>
* <td><code>JbpmCfgResource</code></td>
* <td>Environment Entry</td>
- * <td>The classpath resource from which to read the
- * {@linkplain JbpmConfiguration jBPM configuration}. Optional, defaults to
- * <code>
+ * <td>The classpath resource from which to read the {@linkplain JbpmConfiguration jBPM
+ * configuration}. Optional, defaults to <code>
* jbpm.cfg.xml</code>.</td>
* </tr>
* <tr>
* <td><code>ejb/TimerEntityBean</code></td>
* <td>EJB Reference</td>
- * <td>Link to the local {@linkplain TimerEntityBean entity bean} that
- * implements the scheduler service. Required for processes that contain timers.
- * </td>
+ * <td>Link to the local {@linkplain TimerEntityBean entity bean} that implements the scheduler
+ * service. Required for processes that contain timers.</td>
* </tr>
* <tr>
* <td><code>jdbc/JbpmDataSource</code></td>
* <td>Resource Manager Reference</td>
* <td>Logical name of the data source that provides JDBC connections to the
- * {@linkplain JtaDbPersistenceServiceFactory persistence service}. Must match
- * the <code>hibernate.connection.datasource</code> property in the Hibernate
- * configuration file.</td>
+ * {@linkplain JtaDbPersistenceServiceFactory persistence service}. Must match the
+ * <code>hibernate.connection.datasource</code> property in the Hibernate configuration file.</td>
* </tr>
* <tr>
* <td><code>jms/JbpmConnectionFactory</code></td>
* <td>Resource Manager Reference</td>
* <td>Logical name of the factory that provides JMS connections to the
- * {@linkplain JmsMessageServiceFactory message service}. Required for processes
- * that contain asynchronous continuations.</td>
+ * {@linkplain JmsMessageServiceFactory message service}. Required for processes that contain
+ * asynchronous continuations.</td>
* </tr>
* <tr>
* <td><code>jms/JobQueue</code></td>
* <td>Message Destination Reference</td>
- * <td>The message service sends job messages to the queue referenced here. To
- * ensure this is the same queue from which the {@linkplain JobListenerBean job
- * listener bean} receives messages, the <code>message-destination-link
- * </code> points to a common logical
- * destination, <code>JobQueue</code>.</td>
+ * <td>The message service sends job messages to the queue referenced here. To ensure this is
+ * the same queue from which the {@linkplain JobListenerBean job listener bean} receives
+ * messages, the <code>message-destination-link
+ * </code> points to a common logical destination, <code>JobQueue</code>.</td>
* </tr>
* </table>
*
@@ -106,36 +101,26 @@
private static final long serialVersionUID = 1L;
- JbpmConfiguration jbpmConfiguration = null;
- SessionContext sessionContext = null;
+ private JbpmConfiguration jbpmConfiguration;
+ private SessionContext sessionContext;
/**
- * creates a command service that will be used to execute the commands that
- * are passed in the execute method. The command service will be build by
- * creating a jbpm configuration. In case the environment key JbpmCfgResource
- * is specified for this bean, that value will be used to resolve the jbpm
- * configuration file as a resource. If that key is not configured, the
+ * creates a command service that will be used to execute the commands that are passed in the
+ * execute method. The command service will be build by creating a jbpm configuration. In case
+ * the environment key JbpmCfgResource is specified for this bean, that value will be used to
+ * resolve the jbpm configuration file as a resource. If that key is not configured, the
* default jbpm configuration file will be used (jbpm.cfg.xml).
*/
public void ejbCreate() throws CreateException {
String jbpmCfgResource = null;
try {
- log.debug("getting jbpm configuration resource from the environment properties");
Context initial = new InitialContext();
- jbpmCfgResource =
- (String) initial.lookup("java:comp/env/JbpmCfgResource");
+ jbpmCfgResource = (String) initial.lookup("java:comp/env/JbpmCfgResource");
}
catch (NamingException e) {
- log.debug("couldn't find configuration property JbpmCfgResource through JNDI");
- }
-
- if (log.isDebugEnabled()) {
- if (jbpmCfgResource == null) {
- log.debug("getting default jbpm configuration resource (jbpm.cfg.xml)");
+ if (log.isDebugEnabled()) {
+ log.debug("could not fetch configuration resource from jndi: " + e.getMessage());
}
- else {
- log.debug("getting jbpm configuration from resource " + jbpmCfgResource);
- }
}
jbpmConfiguration = JbpmConfiguration.getInstance(jbpmCfgResource);
@@ -144,11 +129,10 @@
public Object execute(Command command) {
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
- log.debug("executing " + command);
+ if (log.isDebugEnabled()) log.debug("executing " + command);
Object result = command.execute(jbpmContext);
// check whether command requested a rollback
- TxService txService = jbpmContext.getServices().getTxService();
- if (txService.isRollbackOnly()) {
+ if (jbpmContext.getServices().getTxService().isRollbackOnly()) {
sessionContext.setRollbackOnly();
}
return result;
Modified: jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/ExecuteJobCommand.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/ExecuteJobCommand.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/ExecuteJobCommand.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -82,9 +82,6 @@
static void executeJob(Job job, JbpmContext jbpmContext) throws Exception {
if (log.isDebugEnabled()) log.debug("executing " + job);
- if (job.execute(jbpmContext)) {
- jbpmContext.getJobSession().deleteJob(job);
- }
+ if (job.execute(jbpmContext)) jbpmContext.getJobSession().deleteJob(job);
}
-
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/TimerEntityBean.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/TimerEntityBean.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/ejb/impl/TimerEntityBean.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -24,7 +24,8 @@
import org.jbpm.scheduler.ejbtimer.TimerInfo;
/**
- * Entity bean that interacts with the EJB timer service to schedule jBPM {@linkplain Timer timers}.
+ * Entity bean that interacts with the EJB timer service to schedule jBPM {@linkplain Timer
+ * timers}.
*
* <h3>Environment</h3>
*
@@ -82,7 +83,7 @@
try {
Context initial = new InitialContext();
LocalCommandServiceHome commandServiceHome =
- (LocalCommandServiceHome) initial.lookup("java:comp/env/ejb/LocalCommandServiceBean");
+ (LocalCommandServiceHome) initial.lookup("java:comp/env/ejb/LocalCommandServiceBean");
commandService = commandServiceHome.create();
}
catch (NamingException e) {
@@ -128,13 +129,14 @@
}
public void ejbTimeout(javax.ejb.Timer ejbTimer) {
- log.debug(ejbTimer + " fired");
+ boolean debug = log.isDebugEnabled();
+ if (debug) log.debug(ejbTimer + " fired");
TimerInfo timerInfo = (TimerInfo) ejbTimer.getInfo();
Timer timer = (Timer) commandService.execute(new ExecuteTimerCommand(timerInfo.getTimerId()));
// if the timer has repeat
if (timer.getRepeat() != null) {
// create a new timer
- log.debug("scheduling timer for repeat on " + timer.getDueDate());
+ if (debug) log.debug("scheduling timer for repeat on " + timer.getDueDate());
createTimer(timer);
}
}
@@ -142,13 +144,14 @@
public void createTimer(org.jbpm.job.Timer timer) {
TimerService timerService = entityContext.getTimerService();
javax.ejb.Timer ejbTimer = timerService.createTimer(timer.getDueDate(), new TimerInfo(timer));
- log.debug("created " + ejbTimer);
+ if (log.isDebugEnabled()) log.debug("created " + ejbTimer);
}
public void cancelTimer(org.jbpm.job.Timer timer) {
long timerId = timer.getId();
Collection timers = entityContext.getTimerService().getTimers();
- log.debug("retrieved " + timers.size() + " ejb timer(s) by id " + timerId);
+ boolean debug = log.isDebugEnabled();
+ if (debug) log.debug("retrieved " + timers.size() + " ejb timer(s) by id " + timerId);
int count = 0;
for (Iterator i = timers.iterator(); i.hasNext();) {
@@ -159,17 +162,16 @@
++count;
}
}
- log.debug("canceled " + count + " ejb timer(s) by id " + timerId);
+ if (debug) log.debug("canceled " + count + " ejb timer(s) by id " + timerId);
}
public void cancelTimersByName(String timerName, Token token) {
Collection timers = entityContext.getTimerService().getTimers();
- log.debug("retrieved " +
- timers.size() +
- " ejb timer(s) by name '" +
- timerName +
- "' for " +
- token);
+ boolean debug = log.isDebugEnabled();
+ if (debug) {
+ log.debug("retrieved " + timers.size() + " ejb timer(s) by name '" + timerName + "' for "
+ + token);
+ }
int count = 0;
for (Iterator i = timers.iterator(); i.hasNext();) {
@@ -180,12 +182,15 @@
++count;
}
}
- log.debug("canceled " + count + " ejb timer(s) by name '" + timerName + "' for " + token);
+ if (debug) {
+ log.debug("canceled " + count + " ejb timer(s) by name '" + timerName + "' for " + token);
+ }
}
public void cancelTimersForProcessInstance(ProcessInstance processInstance) {
Collection timers = entityContext.getTimerService().getTimers();
- log.debug("retrieved " + timers.size() + " timer(s) for " + processInstance);
+ boolean debug = log.isDebugEnabled();
+ if (debug) log.debug("retrieved " + timers.size() + " timer(s) for " + processInstance);
int count = 0;
for (Iterator i = timers.iterator(); i.hasNext();) {
@@ -196,7 +201,7 @@
++count;
}
}
- log.debug("canceled " + count + " ejb timer(s) for " + processInstance);
+ if (debug) log.debug("canceled " + count + " ejb timer(s) for " + processInstance);
}
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/EjbSchedulerService.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/EjbSchedulerService.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/EjbSchedulerService.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -19,16 +19,16 @@
* @deprecated replaced by {@link EntitySchedulerService}
*/
public class EjbSchedulerService implements SchedulerService {
-
+
private static final long serialVersionUID = 1L;
- JobSession jobSession;
- Session session;
- LocalTimerService timerService;
-
+ private JobSession jobSession;
+ private Session session;
+ private LocalTimerService timerService;
+
public EjbSchedulerService(LocalTimerServiceHome timerServiceHome) {
JbpmContext jbpmContext = JbpmContext.getCurrentJbpmContext();
- if (jbpmContext==null) {
+ if (jbpmContext == null) {
throw new JbpmException("instantiation of the EjbSchedulerService requires a current JbpmContext");
}
this.jobSession = jbpmContext.getJobSession();
@@ -36,7 +36,8 @@
try {
timerService = timerServiceHome.create();
- } catch (CreateException e) {
+ }
+ catch (CreateException e) {
throw new JbpmException("ejb local timer creation problem", e);
}
}
@@ -49,31 +50,34 @@
}
public void deleteTimer(Timer timer) {
- log.debug("deleting " + timer);
+ if (log.isDebugEnabled()) log.debug("deleting " + timer);
timerService.cancelTimer(timer);
jobSession.deleteJob(timer);
}
public void deleteTimersByName(String timerName, Token token) {
- log.debug("deleting timers by name '" + timerName + "' for " + token);
+ if (log.isDebugEnabled()) {
+ log.debug("deleting timers by name '" + timerName + "' for " + token);
+ }
timerService.cancelTimersByName(timerName, token);
jobSession.deleteTimersByName(timerName, token);
}
public void deleteTimersByProcessInstance(ProcessInstance processInstance) {
- log.debug("deleting timers for " + processInstance);
+ if (log.isDebugEnabled()) log.debug("deleting timers for " + processInstance);
timerService.cancelTimersForProcessInstance(processInstance);
jobSession.deleteJobsForProcessInstance(processInstance);
}
public void close() {
try {
- log.debug("removing the timer service session bean");
+ if (log.isDebugEnabled()) log.debug("removing the timer service session bean");
timerService.remove();
- } catch (RemoveException e) {
+ }
+ catch (RemoveException e) {
throw new JbpmException("ejb local timer service close problem", e);
}
}
-
- private static Log log = LogFactory.getLog(EjbSchedulerService.class);
+
+ private static final Log log = LogFactory.getLog(EjbSchedulerService.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/EntitySchedulerService.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/EntitySchedulerService.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/EntitySchedulerService.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -20,37 +20,37 @@
public class EntitySchedulerService implements SchedulerService {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- JobSession jobSession;
- Session session;
- LocalTimerEntityHome timerEntityHome;
+ JobSession jobSession;
+ Session session;
+ LocalTimerEntityHome timerEntityHome;
- public EntitySchedulerService(LocalTimerEntityHome timerEntityHome) {
- JbpmContext jbpmContext = JbpmContext.getCurrentJbpmContext();
- if(jbpmContext == null) {
- throw new JbpmException("entity scheduler service must be created inside a jbpm context");
- }
- this.jobSession = jbpmContext.getJobSession();
- this.session = jbpmContext.getSession();
- this.timerEntityHome = timerEntityHome;
- }
+ public EntitySchedulerService(LocalTimerEntityHome timerEntityHome) {
+ JbpmContext jbpmContext = JbpmContext.getCurrentJbpmContext();
+ if (jbpmContext == null) {
+ throw new JbpmException("entity scheduler service must be created inside a jbpm context");
+ }
+ this.jobSession = jbpmContext.getJobSession();
+ this.session = jbpmContext.getSession();
+ this.timerEntityHome = timerEntityHome;
+ }
- public void createTimer(Timer timer) {
- log.debug("creating " + timer);
- jobSession.saveJob(timer);
- session.flush();
- try {
- LocalTimerEntity timerEntity = timerEntityHome.findByPrimaryKey(new Long(timer.getId()));
- timerEntity.createTimer(timer);
- }
- catch (FinderException e) {
- log.error("failed to retrieve entity for " + timer, e);
- }
- }
+ public void createTimer(Timer timer) {
+ if (log.isDebugEnabled()) log.debug("creating " + timer);
+ jobSession.saveJob(timer);
+ session.flush();
+ try {
+ LocalTimerEntity timerEntity = timerEntityHome.findByPrimaryKey(new Long(timer.getId()));
+ timerEntity.createTimer(timer);
+ }
+ catch (FinderException e) {
+ log.error("failed to retrieve entity for " + timer, e);
+ }
+ }
- public void deleteTimer(Timer timer) {
- log.debug("deleting " + timer);
+ public void deleteTimer(Timer timer) {
+ if (log.isDebugEnabled()) log.debug("deleting " + timer);
try {
LocalTimerEntity timerEntity = timerEntityHome.findByPrimaryKey(new Long(timer.getId()));
timerEntity.cancelTimer(timer);
@@ -62,38 +62,43 @@
}
public void deleteTimersByName(String timerName, Token token) {
- try {
- Collection timerEntities = timerEntityHome.findByNameAndTokenId(timerName, new Long(token.getId()));
- log.debug("found " + timerEntities.size() + " timer entities by name '" + timerName + "' for " + token);
- for (Iterator i = timerEntities.iterator(); i.hasNext();) {
- LocalTimerEntity timerEntity = (LocalTimerEntity) i.next();
- timerEntity.cancelTimersByName(timerName, token);
- }
- }
- catch (FinderException e) {
- log.error("failed to retrieve timer entities by name '" + timerName + "' for " + token, e);
- }
- jobSession.deleteTimersByName(timerName, token);
- }
+ try {
+ Collection timerEntities = timerEntityHome.findByNameAndTokenId(timerName, new Long(token.getId()));
+ if (log.isDebugEnabled()) {
+ log.debug("found " + timerEntities.size() + " timer entities by name '" + timerName
+ + "' for " + token);
+ }
+ for (Iterator i = timerEntities.iterator(); i.hasNext();) {
+ LocalTimerEntity timerEntity = (LocalTimerEntity) i.next();
+ timerEntity.cancelTimersByName(timerName, token);
+ }
+ }
+ catch (FinderException e) {
+ log.error("failed to retrieve timer entities by name '" + timerName + "' for " + token, e);
+ }
+ jobSession.deleteTimersByName(timerName, token);
+ }
- public void deleteTimersByProcessInstance(ProcessInstance processInstance) {
- try {
- Collection timerEntities = timerEntityHome.findByProcessInstanceId(new Long(processInstance.getId()));
- log.debug("found " + timerEntities.size() + " timer entities for " + processInstance);
- for (Iterator i = timerEntities.iterator(); i.hasNext();) {
- LocalTimerEntity timerEntity = (LocalTimerEntity) i.next();
- timerEntity.cancelTimersForProcessInstance(processInstance);
- }
- }
- catch (FinderException e) {
- log.error("failed to retrieve timer entities for " + processInstance, e);
- }
- jobSession.deleteJobsForProcessInstance(processInstance);
- }
+ public void deleteTimersByProcessInstance(ProcessInstance processInstance) {
+ try {
+ Collection timerEntities = timerEntityHome.findByProcessInstanceId(new Long(processInstance.getId()));
+ if (log.isDebugEnabled()) {
+ log.debug("found " + timerEntities.size() + " timer entities for " + processInstance);
+ }
+ for (Iterator i = timerEntities.iterator(); i.hasNext();) {
+ LocalTimerEntity timerEntity = (LocalTimerEntity) i.next();
+ timerEntity.cancelTimersForProcessInstance(processInstance);
+ }
+ }
+ catch (FinderException e) {
+ log.error("failed to retrieve timer entities for " + processInstance, e);
+ }
+ jobSession.deleteJobsForProcessInstance(processInstance);
+ }
- public void close() {
- timerEntityHome = null;
- }
+ public void close() {
+ timerEntityHome = null;
+ }
- private static Log log = LogFactory.getLog(EntitySchedulerService.class);
+ private static final Log log = LogFactory.getLog(EntitySchedulerService.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/ExecuteTimerCommand.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/ExecuteTimerCommand.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/ExecuteTimerCommand.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -1,12 +1,11 @@
package org.jbpm.scheduler.ejbtimer;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.jbpm.JbpmContext;
import org.jbpm.command.Command;
+import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.job.Timer;
public class ExecuteTimerCommand implements Command {
@@ -20,28 +19,41 @@
}
public Object execute(JbpmContext jbpmContext) throws Exception {
- Timer timer = jbpmContext.getJobSession().loadTimer(timerId);
- timer.setLockOwner(getClass().getName()); // prevent others from removing timer
- log.debug("executing " + timer);
- try {
- if (timer.execute(jbpmContext)) {
- jbpmContext.getServices().getSchedulerService().deleteTimer(timer);
- }
+ Timer timer = acquireTimer(timerId, jbpmContext);
+ if (timer != null) executeTimer(timer, jbpmContext);
+ return timer;
+ }
+
+ private static Timer acquireTimer(long timerId, JbpmContext jbpmContext) {
+ boolean debug = log.isDebugEnabled();
+ if (debug) log.debug("acquiring timer: " + timerId);
+
+ Timer timer = (Timer) jbpmContext.getSession().get(Timer.class, new Long(timerId));
+ // timer could have been deleted manually
+ // or by ending the process instance
+ if (timer != null) {
+ // register process instance for automatic save
+ // see https://jira.jboss.org/jira/browse/JBPM-1015
+ ProcessInstance processInstance = timer.getProcessInstance();
+ jbpmContext.addAutoSaveProcessInstance(processInstance);
+
+ // mark timer as locked to prevent it from being deleted
+ timer.setLockOwner(Thread.currentThread().getName());
+ if (debug) log.debug("acquired " + timer);
}
- catch (RuntimeException e) {
- // nothing to do but clean up and exit
- throw e;
+ else if (debug) {
+ log.debug("timer not found: " + timerId);
}
- catch (Exception e) {
- // save data about recoverable error condition
- log.error("exception while executing " + timer, e);
- StringWriter memoryWriter = new StringWriter();
- e.printStackTrace(new PrintWriter(memoryWriter));
- timer.setException(memoryWriter.toString());
- timer.setRetries(timer.getRetries() - 1);
- }
+
return timer;
}
+ private static void executeTimer(Timer timer, JbpmContext jbpmContext) throws Exception {
+ if (log.isDebugEnabled()) log.debug("executing " + timer);
+ if (timer.execute(jbpmContext)) {
+ jbpmContext.getServices().getSchedulerService().deleteTimer(timer);
+ }
+ }
+
private static final Log log = LogFactory.getLog(ExecuteTimerCommand.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/TimerServiceBean.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/TimerServiceBean.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/enterprise/src/main/java/org/jbpm/scheduler/ejbtimer/TimerServiceBean.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -21,11 +21,11 @@
*/
package org.jbpm.scheduler.ejbtimer;
-import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;
+import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
@@ -33,10 +33,11 @@
import javax.ejb.TimerService;
import javax.naming.Context;
import javax.naming.InitialContext;
+import javax.naming.NamingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.jbpm.JbpmException;
+
import org.jbpm.ejb.LocalCommandService;
import org.jbpm.ejb.LocalCommandServiceHome;
import org.jbpm.ejb.impl.TimerEntityBean;
@@ -45,8 +46,8 @@
import org.jbpm.job.Timer;
/**
- * Session bean that interacts with the EJB timer service to schedule jBPM
- * {@linkplain Timer timers}.
+ * Session bean that interacts with the EJB timer service to schedule jBPM {@linkplain Timer
+ * timers}.
*
* @deprecated use {@link TimerEntityBean} instead
*/
@@ -54,9 +55,21 @@
private static final long serialVersionUID = 1L;
- SessionContext sessionContext;
-
+ private LocalCommandService commandService;
+ private SessionContext sessionContext;
+
public void ejbCreate() {
+ try {
+ Context initial = new InitialContext();
+ LocalCommandServiceHome commandServiceHome = (LocalCommandServiceHome) initial.lookup("java:comp/env/ejb/LocalCommandServiceBean");
+ commandService = commandServiceHome.create();
+ }
+ catch (NamingException e) {
+ throw new EJBException("failed to retrieve command service home", e);
+ }
+ catch (CreateException e) {
+ throw new EJBException("command service creation failed", e);
+ }
}
public void createTimer(org.jbpm.job.Timer timer) {
@@ -66,13 +79,14 @@
}
public void cancelTimer(org.jbpm.job.Timer timer) {
- // TODO make the scanning of timers for cancellation optional by only deleting the timerjobs in the db.
- // of course, the corresponding ejb timer notifications have to be ignored.
-
+ // TODO make the scanning of timers optional by only deleting the timers in the database
+ // of course, the corresponding ejb timer notifications have to be ignored
long timerId = timer.getId();
Collection timers = sessionContext.getTimerService().getTimers();
- log.debug("examining " + timers.size() + " ejb timer(s) by id " + timerId);
+ boolean debug = log.isDebugEnabled();
+ if (debug) log.debug("examining " + timers.size() + " timers by id " + timerId);
+
int count = 0;
for (Iterator i = timers.iterator(); i.hasNext();) {
javax.ejb.Timer ejbTimer = (javax.ejb.Timer) i.next();
@@ -84,16 +98,20 @@
}
}
}
- log.debug("canceled " + count + " ejb timer(s) by id " + timerId);
+ if (debug) log.debug("canceled " + count + " timers by id " + timerId);
}
public void cancelTimersByName(String timerName, Token token) {
- // TODO make the scanning of timers for cancellation optional by only deleting the timerjobs in the db.
- // of course, the corresponding ejb timer notifications have to be ignored.
-
+ // TODO make the scanning of timers optional by only deleting the timers in the database
+ // of course, the corresponding ejb timer notifications have to be ignored
Collection timers = sessionContext.getTimerService().getTimers();
- log.debug("examining " + timers.size() + " ejb timer(s) by name '" + timerName + "' for " + token);
+ boolean debug = log.isDebugEnabled();
+ if (debug) {
+ log.debug("examining " + timers.size() + " timers by name '" + timerName + "' for "
+ + token);
+ }
+
int count = 0;
for (Iterator i = timers.iterator(); i.hasNext();) {
javax.ejb.Timer ejbTimer = (javax.ejb.Timer) i.next();
@@ -105,15 +123,17 @@
}
}
}
- log.debug("canceled " + count + " ejb timer(s) by name '" + timerName + "' for " + token);
+ if (debug) {
+ log.debug("canceled " + count + " timers by name '" + timerName + "' for " + token);
+ }
}
public void cancelTimersForProcessInstance(ProcessInstance processInstance) {
- // TODO make the scanning of timers for cancellation optional by only deleting the timerjobs in the db.
- // of course, the corresponding ejb timer notifications have to be ignored.
-
+ // TODO make the scanning of timers optional by only deleting the timers in the database
+ // of course, the corresponding ejb timer notifications have to be ignored
Collection timers = sessionContext.getTimerService().getTimers();
- log.debug("examining " + timers.size() + " timer(s) for " + processInstance);
+ boolean debug = log.isDebugEnabled();
+ if (debug) log.debug("examining " + timers.size() + " timers for " + processInstance);
int count = 0;
for (Iterator i = timers.iterator(); i.hasNext();) {
@@ -126,51 +146,37 @@
}
}
}
- log.debug("canceled " + count + " ejb timer(s) for " + processInstance);
+ if (debug) log.debug("canceled " + count + " timers for " + processInstance);
}
public void ejbTimeout(javax.ejb.Timer ejbTimer) {
- log.debug(ejbTimer + " fired");
- String localCommandServiceJndiName = "java:comp/env/ejb/LocalCommandServiceBean";
- try {
- Context initial = new InitialContext();
- LocalCommandServiceHome localCommandServiceHome = (LocalCommandServiceHome) initial.lookup(localCommandServiceJndiName);
- LocalCommandService localCommandService = localCommandServiceHome.create();
- Serializable info = ejbTimer.getInfo();
- if (! (info instanceof TimerInfo)) {
- if (info ==null) {
- throw new NullPointerException("timer info is null");
- } else {
- throw new ClassCastException("timer info ("+info.getClass().getName()+") is not of the expected class "+TimerInfo.class.getName());
- }
- }
- TimerInfo timerInfo = (TimerInfo) info;
- Timer timer = (Timer) localCommandService.execute(new ExecuteTimerCommand(timerInfo.getTimerId()));
- // if the timer has repeat
- if ( (timer!=null)
- && (timer.getRepeat()!=null)
- ) {
- // create a new timer
- log.debug("scheduling timer for repeat at "+timer.getDueDate());
- createTimer(timer);
- }
- } catch (Exception e) {
- JbpmException jbpmException = new JbpmException("couldn't execute timer", e);
- log.error(jbpmException);
- throw jbpmException;
+ boolean debug = log.isDebugEnabled();
+ if (debug) log.debug(ejbTimer + " fired");
+
+ TimerInfo timerInfo = (TimerInfo) ejbTimer.getInfo();
+ Timer timer = (Timer) commandService.execute(new ExecuteTimerCommand(timerInfo.getTimerId()));
+ // if timer is repetitive
+ if (timer != null && timer.getRepeat() != null) {
+ // create a new timer
+ if (debug) log.debug("scheduling timer for repeat at " + timer.getDueDate());
+ createTimer(timer);
}
}
- public void setSessionContext(SessionContext sessionContext) throws EJBException, RemoteException {
+ public void setSessionContext(SessionContext sessionContext) throws EJBException,
+ RemoteException {
this.sessionContext = sessionContext;
}
public void ejbActivate() throws EJBException, RemoteException {
}
+
public void ejbPassivate() throws EJBException, RemoteException {
}
+
public void ejbRemove() throws EJBException, RemoteException {
+ commandService = null;
}
- private static Log log = LogFactory.getLog(TimerServiceBean.class);
+ private static final Log log = LogFactory.getLog(TimerServiceBean.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/examples/src/test/java/org/jbpm/examples/assignment/RulesAssignmentHandler.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/examples/src/test/java/org/jbpm/examples/assignment/RulesAssignmentHandler.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/examples/src/test/java/org/jbpm/examples/assignment/RulesAssignmentHandler.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -27,7 +27,7 @@
protected List objectNames;
private static final long serialVersionUID = 1L;
- private static Log log = LogFactory.getLog(RulesAssignmentHandler.class);
+ private static final Log log = LogFactory.getLog(RulesAssignmentHandler.class);
public void assign(Assignable assignable, ExecutionContext executionContext) throws Exception {
// load up the rule base
@@ -40,19 +40,20 @@
.getPersistenceService()
.getCustomSession(IdentitySession.class);
// users
+ boolean debug = log.isDebugEnabled();
for (Iterator iter = identitySession.getUsers().iterator(); iter.hasNext();) {
User user = (User) iter.next();
- log.debug("user: " + user.getName());
+ if (debug) log.debug("user: " + user.getName());
workingMemory.insert(user);
}
// group
Group group = identitySession.getGroupByName(this.group);
- log.debug("group: " + group.getName());
+ if (debug) log.debug("group: " + group.getName());
workingMemory.insert(group);
// memberships
for (Iterator iter = group.getMemberships().iterator(); iter.hasNext();) {
Membership membership = (Membership) iter.next();
- log.debug("membership: " + membership.getName());
+ if (debug) log.debug("membership: " + membership.getName());
workingMemory.insert(membership);
}
@@ -62,15 +63,14 @@
String objectName = (String) iter.next();
Object object = ci.getVariable(objectName);
- log.debug("variable '" + objectName + "': " + object);
+ if (debug) log.debug("variable '" + objectName + "': " + object);
workingMemory.insert(object);
}
// insert the assignable so that it may be used to set results
- log.debug("assignable: " + assignable);
+ if (debug) log.debug("assignable: " + assignable);
workingMemory.insert(assignable);
- log.debug("firing all rulles");
workingMemory.fireAllRules();
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/examples/src/test/java/org/jbpm/examples/rulesaction/RulesActionHandler.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/examples/src/test/java/org/jbpm/examples/rulesaction/RulesActionHandler.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/examples/src/test/java/org/jbpm/examples/rulesaction/RulesActionHandler.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -27,8 +27,8 @@
private static final Log log = LogFactory.getLog(RulesActionHandler.class.getName());
/**
- * The RulesActionHandler gets variables from the ContextInstance, and asserts them into the Rules
- * Engine and invokes the rules.
+ * The RulesActionHandler gets variables from the ContextInstance, and asserts them into the
+ * Rules Engine and invokes the rules.
*/
public void execute(ExecutionContext executionContext) throws Exception {
// load up the rulebase
@@ -36,12 +36,13 @@
WorkingMemory workingMemory = ruleBase.newStatefulSession();
// read variables
+ boolean debug = log.isDebugEnabled();
ContextInstance ci = executionContext.getContextInstance();
for (Iterator iter = objectNames.iterator(); iter.hasNext();) {
String objectName = (String) iter.next();
Object object = ci.getVariable(objectName);
- log.debug("variable '" + objectName + "': " + object);
+ if (debug) log.debug("variable '" + objectName + "': " + object);
workingMemory.insert(object);
}
@@ -49,11 +50,10 @@
// so that the rules can update the process
workingMemory.setGlobal("ci", ci);
workingMemory.fireAllRules();
-
workingMemory.clearAgenda();
- // propagate the token so that the process continues
- executionContext.getToken().signal();
+ // if this action is the behavior of a node, continue execution
+ if (executionContext.getEvent() == null) executionContext.leaveNode();
}
/**
@@ -62,7 +62,7 @@
private static RuleBase readRule(String ruleFileName) throws Exception {
PackageBuilder builder = new PackageBuilder();
builder.addPackageFromDrl(new InputStreamReader(
- RulesActionHandler.class.getResourceAsStream(ruleFileName)));
+ RulesActionHandler.class.getResourceAsStream(ruleFileName)));
RuleBase ruleBase = RuleBaseFactory.newRuleBase();
ruleBase.addPackage(builder.getPackage());
Modified: jbpm3/branches/jbpm-3.2-soa/modules/identity/src/main/java/org/jbpm/identity/assignment/ExpressionAssignmentHandler.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/identity/src/main/java/org/jbpm/identity/assignment/ExpressionAssignmentHandler.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/identity/src/main/java/org/jbpm/identity/assignment/ExpressionAssignmentHandler.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -23,8 +23,6 @@
import java.util.Set;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
import org.jbpm.JbpmContext;
import org.jbpm.graph.exe.ExecutionContext;
import org.jbpm.graph.exe.Token;
@@ -38,8 +36,8 @@
import org.jbpm.taskmgmt.exe.SwimlaneInstance;
/**
- * implements an expression language for assigning actors to tasks based on this
- * identity component.
+ * implements an expression language for assigning actors to tasks based on this identity
+ * component.
*
* <pre>
* syntax : first-term --> next-term --> next-term --> ... --> next-term
@@ -89,14 +87,15 @@
// else if the expression evaluated to a group
else if (entity instanceof Group) {
// put the group in the pool
- assignable.setPooledActors(new String[] { entity.getName() });
+ assignable.setPooledActors(new String[] {
+ entity.getName()
+ });
}
}
/**
- * serves as a hook for customizing the way the identity session is retrieved.
- * overload this method to reuse this expression assignment handler for your
- * user data store.
+ * serves as a hook for customizing the way the identity session is retrieved. overload this
+ * method to reuse this expression assignment handler for your user data store.
*/
protected ExpressionSession getExpressionSession() {
JbpmContext jbpmContext = JbpmContext.getCurrentJbpmContext();
@@ -110,8 +109,6 @@
protected Entity resolveFirstTerm(String term) {
Entity entity;
- log.debug("resolving first term: '" + term);
-
if (term.equalsIgnoreCase("previous")) {
String userName = SecurityHelper.getAuthenticatedActorId();
entity = getUserByName(userName);
@@ -151,8 +148,6 @@
}
protected Entity resolveNextTerm(String term) {
- log.debug("resolving term: " + term);
-
if (term.startsWith("group(") && term.endsWith(")")) {
String groupType = term.substring(6, term.length() - 1).trim();
User user = (User) entity;
@@ -173,7 +168,6 @@
else {
throw new ExpressionAssignmentException("could not interpret term: " + term);
}
-
return entity;
}
@@ -206,6 +200,4 @@
}
return swimlaneInstance.getActorId();
}
-
- private static final Log log = LogFactory.getLog(ExpressionAssignmentHandler.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/identity/src/main/java/org/jbpm/identity/hibernate/IdentitySchema.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/identity/src/main/java/org/jbpm/identity/hibernate/IdentitySchema.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/identity/src/main/java/org/jbpm/identity/hibernate/IdentitySchema.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -21,188 +21,194 @@
*/
package org.jbpm.identity.hibernate;
-import java.io.*;
-import java.lang.reflect.*;
-import java.sql.*;
-import java.util.*;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Iterator;
import java.util.List;
+import java.util.Properties;
-import org.apache.commons.logging.*;
-import org.hibernate.cfg.*;
-import org.hibernate.connection.*;
-import org.hibernate.dialect.*;
-import org.hibernate.engine.*;
-import org.hibernate.mapping.*;
-import org.hibernate.tool.hbm2ddl.*;
-import org.hibernate.util.*;
+import org.hibernate.HibernateException;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.connection.ConnectionProvider;
+import org.hibernate.connection.ConnectionProviderFactory;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.engine.Mapping;
+import org.hibernate.mapping.ForeignKey;
+import org.hibernate.mapping.Table;
+import org.hibernate.tool.hbm2ddl.SchemaExport;
+import org.hibernate.util.JDBCExceptionReporter;
+
import org.jbpm.JbpmException;
public class IdentitySchema {
- private static final String IDENTITY_TABLE_PREFIX = "JBPM_ID_";
-
- Configuration configuration = null;
- Properties properties = null;
- Dialect dialect = null;
- Mapping mapping = null;
- String[] createSql = null;
- String[] dropSql = null;
- String[] cleanSql = null;
+ private static final String IDENTITY_TABLE_PATTERN = "JBPM_ID_%";
+ private static final String[] TABLE_TYPES = {
+ "TABLE"
+ };
- ConnectionProvider connectionProvider = null;
- Connection connection = null;
- Statement statement = null;
+ private final Configuration configuration;
+ private ConnectionProvider connectionProvider;
public IdentitySchema(Configuration configuration) {
this.configuration = configuration;
- this.properties = configuration.getProperties();
- this.dialect = Dialect.getDialect(properties);
- try {
- // get the mapping field via reflection :-(
- Field mappingField = Configuration.class.getDeclaredField("mapping");
- mappingField.setAccessible(true);
- this.mapping = (Mapping) mappingField.get(configuration);
- } catch (Exception e) {
- throw new JbpmException("couldn't get the hibernate mapping", e);
- }
}
+ private Dialect getDialect() {
+ return Dialect.getDialect(configuration.getProperties());
+ }
+
+ private String getDefaultCatalog() {
+ return configuration.getProperty(Environment.DEFAULT_CATALOG);
+ }
+
+ private String getDefaultSchema() {
+ return configuration.getProperty(Environment.DEFAULT_SCHEMA);
+ }
+
// scripts lazy initializations /////////////////////////////////////////////
-
+
public String[] getCreateSql() {
- if (createSql==null) {
- createSql = configuration.generateSchemaCreationScript(dialect);
- }
- return createSql;
+ return configuration.generateSchemaCreationScript(getDialect());
}
-
+
public String[] getDropSql() {
- if (dropSql==null) {
- dropSql = configuration.generateDropSchemaScript(dialect);
- }
- return dropSql;
+ return configuration.generateDropSchemaScript(getDialect());
}
-
+
public String[] getCleanSql() {
- if (cleanSql==null) {
- // 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();
- if ( fk.isPhysicalConstraint() ) {
- // collect the drop key constraint
- dropForeignKeysSql.add( fk.sqlDropString(
- dialect,
- properties.getProperty(Environment.DEFAULT_CATALOG),
- properties.getProperty(Environment.DEFAULT_SCHEMA) ) );
- createForeignKeysSql.add( fk.sqlCreateString(
- dialect,
- mapping,
- properties.getProperty(Environment.DEFAULT_CATALOG),
- properties.getProperty(Environment.DEFAULT_SCHEMA) ) );
- }
- }
+ List dropForeignKeysSql = new ArrayList();
+ List createForeignKeysSql = new ArrayList();
+
+ Dialect dialect = getDialect();
+ String defaultCatalog = getDefaultCatalog();
+ String defaultSchema = getDefaultSchema();
+ Mapping mapping = configuration.buildMapping();
+
+ // loop over all table mappings
+ for (Iterator tm = configuration.getTableMappings(); tm.hasNext();) {
+ Table table = (Table) tm.next();
+ if (!table.isPhysicalTable()) continue;
+
+ for (Iterator subIter = table.getForeignKeyIterator(); subIter.hasNext();) {
+ ForeignKey foreignKey = (ForeignKey) subIter.next();
+ if (foreignKey.isPhysicalConstraint()) {
+ // collect the drop key constraint
+ dropForeignKeysSql.add(foreignKey.sqlDropString(dialect, defaultCatalog, defaultSchema));
+ createForeignKeysSql.add(foreignKey.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
}
}
+ }
- List deleteSql = new ArrayList();
- iter = configuration.getTableMappings();
- while (iter.hasNext()) {
- Table table = (Table) iter.next();
- deleteSql.add("delete from "+table.getName());
- }
+ List deleteSql = dropForeignKeysSql;
+ for (Iterator iter = configuration.getTableMappings(); iter.hasNext();) {
+ Table table = (Table) iter.next();
+ deleteSql.add("delete from " + table.getName());
+ }
- List cleanSqlList = new ArrayList();
- cleanSqlList.addAll(dropForeignKeysSql);
- cleanSqlList.addAll(deleteSql);
- cleanSqlList.addAll(createForeignKeysSql);
-
- cleanSql = (String[]) cleanSqlList.toArray(new String[cleanSqlList.size()]);
- }
- return cleanSql;
+ List cleanSqlList = dropForeignKeysSql;
+ cleanSqlList.addAll(createForeignKeysSql);
+
+ return (String[]) cleanSqlList.toArray(new String[cleanSqlList.size()]);
}
// runtime table detection //////////////////////////////////////////////////
-
+
public boolean hasIdentityTables() {
- return (getIdentityTables().size()>0);
+ return !getIdentityTables().isEmpty();
}
public List getIdentityTables() {
// delete all the data in the jbpm tables
- List jbpmTableNames = new ArrayList();
+ Connection connection = null;
try {
- createConnection();
- ResultSet resultSet = connection.getMetaData().getTables("", "", null, null);
- while(resultSet.next()) {
- String tableName = resultSet.getString("TABLE_NAME");
- if ( (tableName!=null)
- && (tableName.length()>5)
- && (IDENTITY_TABLE_PREFIX.equalsIgnoreCase(tableName.substring(0,5))) ) {
- jbpmTableNames.add(tableName);
+ connection = createConnection();
+
+ List identityTables = new ArrayList();
+ ResultSet resultSet = connection.getMetaData()
+ .getTables(null, null, IDENTITY_TABLE_PATTERN, TABLE_TYPES);
+ try {
+ while (resultSet.next()) {
+ String tableName = resultSet.getString("TABLE_NAME");
+ if (tableName != null && tableName.length() > 5
+ && IDENTITY_TABLE_PATTERN.equalsIgnoreCase(tableName.substring(0, 5))) {
+ identityTables.add(tableName);
+ }
}
}
- } catch (SQLException e) {
- throw new JbpmException("couldn't get the jbpm table names");
- } finally {
- closeConnection();
+ finally {
+ resultSet.close();
+ }
+ return identityTables;
}
- return jbpmTableNames;
+ catch (SQLException e) {
+ throw new JbpmException("could not get identity tables");
+ }
+ finally {
+ closeConnection(connection);
+ }
}
-
+
// script execution methods /////////////////////////////////////////////////
-
+
public void dropSchema() {
- execute( getDropSql() );
+ execute(getDropSql());
}
public void createSchema() {
- execute( getCreateSql() );
+ execute(getCreateSql());
}
public void cleanSchema() {
- execute( getCleanSql() );
+ execute(getCleanSql());
}
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);
- } catch (IOException e) {
+ 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);
+ }
+ catch (IOException e) {
throw new JbpmException("couldn't generate scripts", e);
}
}
// main /////////////////////////////////////////////////////////////////////
-
+
public static void main(String[] args) {
if (args == null || args.length == 0) {
syntax();
- } else if ("create".equalsIgnoreCase(args[0])) {
+ }
+ else if ("create".equalsIgnoreCase(args[0])) {
new IdentitySchema(IdentitySessionFactory.createConfiguration()).createSchema();
- } else if ("drop".equalsIgnoreCase(args[0])) {
+ }
+ else if ("drop".equalsIgnoreCase(args[0])) {
new IdentitySchema(IdentitySessionFactory.createConfiguration()).dropSchema();
- } else if ("clean".equalsIgnoreCase(args[0])) {
+ }
+ else if ("clean".equalsIgnoreCase(args[0])) {
new IdentitySchema(IdentitySessionFactory.createConfiguration()).cleanSchema();
- } else if ("scripts".equalsIgnoreCase(args[0]) && args.length == 3) {
+ }
+ else if ("scripts".equalsIgnoreCase(args[0]) && args.length == 3) {
new IdentitySchema(IdentitySessionFactory.createConfiguration()).saveSqlScripts(args[1], args[2]);
- } else {
+ }
+ else {
syntax();
}
}
-
+
private static void syntax() {
System.err.println("syntax:");
System.err.println("IdentitySchema create");
@@ -214,83 +220,88 @@
private void saveSqlScript(String fileName, String[] sql) throws FileNotFoundException {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
PrintStream printStream = new PrintStream(fileOutputStream);
- for (int i=0; i<sql.length; i++) {
- printStream.println(sql[i]+getSqlDelimiter());
+ for (int i = 0; i < sql.length; i++) {
+ printStream.println(sql[i] + getSqlDelimiter());
}
}
-
+
// sql script execution /////////////////////////////////////////////////////
- public void execute(String[] sqls) {
- String sql = null;
- String showSqlText = properties.getProperty("hibernate.show_sql");
- boolean showSql = ("true".equalsIgnoreCase(showSqlText));
-
+ public void execute(String[] script) {
+ Connection connection = null;
try {
- createConnection();
- statement = connection.createStatement();
-
- for (int i=0; i<sqls.length; i++) {
- sql = sqls[i];
- String delimitedSql = sql+getSqlDelimiter();
-
- if (showSql) log.debug(delimitedSql);
- statement.executeUpdate(delimitedSql);
+ connection = createConnection();
+ Statement statement = connection.createStatement();
+ try {
+ boolean showSql = getShowSql();
+ for (int i = 0; i < script.length; i++) {
+ String sql = script[i];
+ if (showSql) System.out.println(sql);
+ statement.executeUpdate(sql);
+ }
}
-
- } catch (SQLException e) {
- throw new JbpmException("couldn't execute sql '"+sql+"'", e);
- } finally {
- closeConnection();
+ finally {
+ statement.close();
+ }
}
+ catch (SQLException e) {
+ throw new JbpmException("failed to execute sql", e);
+ }
+ finally {
+ closeConnection(connection);
+ }
}
- private void closeConnection() {
- if (statement!=null) {
+ private boolean getShowSql() {
+ return "true".equalsIgnoreCase(configuration.getProperty(Environment.SHOW_SQL));
+ }
+
+ private void closeConnection(Connection connection) {
+ if (connectionProvider != null) {
try {
- statement.close();
+ if (connection != null) {
+ JDBCExceptionReporter.logAndClearWarnings(connection);
+ connectionProvider.closeConnection(connection);
+ }
}
catch (SQLException e) {
- log.debug("couldn't close jdbc statement", e);
+ JDBCExceptionReporter.logExceptions(e);
}
- }
- if (connection!=null) {
- try {
- JDBCExceptionReporter.logWarnings( connection.getWarnings() );
- connection.clearWarnings();
- connectionProvider.closeConnection(connection);
+ finally {
connectionProvider.close();
+ connectionProvider = null;
}
- catch (SQLException e) {
- log.debug("couldn't close jdbc connection", e);
- }
}
}
- private void createConnection() throws SQLException {
- connectionProvider = ConnectionProviderFactory.newConnectionProvider(properties);
- connection = connectionProvider.getConnection();
- if ( !connection.getAutoCommit() ) {
+ private Connection createConnection() throws SQLException {
+ try {
+ connectionProvider = ConnectionProviderFactory.newConnectionProvider(configuration.getProperties());
+ }
+ catch (HibernateException e) {
+ throw new SQLException(e.getMessage());
+ }
+ Connection connection = connectionProvider.getConnection();
+ if (connection.getAutoCommit() == false) {
connection.commit();
connection.setAutoCommit(true);
}
+ return connection;
}
-
+
public Properties getProperties() {
- return properties;
+ return configuration.getProperties();
}
// sql delimiter ////////////////////////////////////////////////////////////
-
- private static String sqlDelimiter = null;
+
+ private static String sqlDelimiter;
+
private synchronized String getSqlDelimiter() {
- if (sqlDelimiter==null) {
- sqlDelimiter = properties.getProperty("jbpm.sql.delimiter", ";");
+ if (sqlDelimiter == null) {
+ sqlDelimiter = getProperties().getProperty("jbpm.sql.delimiter", ";");
}
return sqlDelimiter;
}
- // logger ///////////////////////////////////////////////////////////////////
-
- private static final Log log = LogFactory.getLog(IdentitySchema.class);
}
Modified: jbpm3/branches/jbpm-3.2-soa/modules/identity/src/main/java/org/jbpm/identity/hibernate/IdentitySessionFactory.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/identity/src/main/java/org/jbpm/identity/hibernate/IdentitySessionFactory.java 2010-04-13 08:02:00 UTC (rev 6256)
+++ jbpm3/branches/jbpm-3.2-soa/modules/identity/src/main/java/org/jbpm/identity/hibernate/IdentitySessionFactory.java 2010-04-15 13:46:26 UTC (rev 6257)
@@ -23,8 +23,6 @@
import java.sql.Connection;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
@@ -33,10 +31,10 @@
import org.jbpm.identity.User;
public class IdentitySessionFactory {
-
+
protected Configuration configuration;
protected SessionFactory sessionFactory;
-
+
public IdentitySessionFactory() {
this(createConfiguration());
}
@@ -58,12 +56,11 @@
Configuration configuration = null;
// create the hibernate configuration
configuration = new Configuration();
-
- if (resource!=null) {
- log.debug("using '"+resource+"' as hibernate configuration for jbpm");
+
+ if (resource != null) {
configuration.configure(resource);
- } else {
- log.debug("using the default hibernate configuration file: hibernate.cfg.xml");
+ }
+ else {
configuration.configure();
}
return configuration;
@@ -86,9 +83,8 @@
public Configuration getConfiguration() {
return configuration;
}
+
public SessionFactory getSessionFactory() {
return sessionFactory;
}
-
- private static final Log log = LogFactory.getLog(IdentitySessionFactory.class);
}
More information about the jbpm-commits
mailing list