ALF-4346: Scheduled Persistent Actions CRUD

- implement persistence of scheduled actions
- tests
- TODO: further tests e.g. various updates of associated action

git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@21916 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
David Caruana
2010-08-20 17:51:56 +00:00
parent dd65fccd7b
commit 4cad8ab1fd
8 changed files with 713 additions and 359 deletions

View File

@@ -604,6 +604,7 @@
<!-- Scheduled persisted actions - load into quartz --> <!-- Scheduled persisted actions - load into quartz -->
<bean id="scheduledPersistedActionServiceBootstrap" class="org.alfresco.repo.action.scheduled.ScheduledPersistedActionServiceImpl$ScheduledPersistedActionServiceBootstrap"> <bean id="scheduledPersistedActionServiceBootstrap" class="org.alfresco.repo.action.scheduled.ScheduledPersistedActionServiceImpl$ScheduledPersistedActionServiceBootstrap">
<property name="scheduledPersistedActionService" ref="scheduledPersistedActionService" /> <property name="scheduledPersistedActionService" ref="scheduledPersistedActionService" />
<property name="transactionHelper" ref="retryingTransactionHelper" />
</bean> </bean>
<!-- Startup Message --> <!-- Startup Message -->

View File

@@ -1419,6 +1419,38 @@
</property> </property>
</bean> </bean>
<bean id="ScheduledPersistedActionService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>org.alfresco.service.cmr.action.scheduled.ScheduledPersistedActionService</value>
</property>
<property name="target">
<ref bean="scheduledPersistedActionService" />
</property>
<property name="interceptorNames">
<list>
<idref local="ScheduledPersistedActionService_transaction" />
<idref bean="AuditMethodInterceptor" />
<idref bean="exceptionTranslator" />
<idref local="ScheduledPersistedActionService_security" />
</list>
</property>
</bean>
<bean id="ScheduledPersistedActionService_transaction"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="*">${server.transaction.mode.default}</prop>
</props>
</property>
</bean>
<bean id="ScheduledPersistedActionService_security"
class="org.alfresco.repo.security.permissions.impl.AlwaysProceedMethodInterceptor" />
<bean id="PublicServiceAccessService" class="org.springframework.aop.framework.ProxyFactoryBean"> <bean id="PublicServiceAccessService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces"> <property name="proxyInterfaces">
<value>org.alfresco.service.cmr.security.PublicServiceAccessService</value> <value>org.alfresco.service.cmr.security.PublicServiceAccessService</value>

View File

@@ -51,6 +51,12 @@ public interface ActionModel
static final QName ASPECT_ACTIONS = QName.createQName(ACTION_MODEL_URI, "actions"); static final QName ASPECT_ACTIONS = QName.createQName(ACTION_MODEL_URI, "actions");
static final QName ASSOC_ACTION_FOLDER = QName.createQName(ACTION_MODEL_URI, "actionFolder"); static final QName ASSOC_ACTION_FOLDER = QName.createQName(ACTION_MODEL_URI, "actionFolder");
static final QName TYPE_ACTION_SCHEDULE = QName.createQName(ACTION_MODEL_URI, "actionSchedule");
static final QName PROP_START_DATE = QName.createQName(ACTION_MODEL_URI, "startDate");
static final QName PROP_INTERVAL_COUNT = QName.createQName(ACTION_MODEL_URI, "intervalCount");
static final QName PROP_INTERVAL_PERIOD = QName.createQName(ACTION_MODEL_URI, "intervalPeriod");
static final QName ASSOC_SCHEDULED_ACTION = QName.createQName(ACTION_MODEL_URI, "scheduledAction");
//static final QName ASPECT_ACTIONABLE = QName.createQName(ACTION_MODEL_URI, "actionable"); //static final QName ASPECT_ACTIONABLE = QName.createQName(ACTION_MODEL_URI, "actionable");
//static final QName ASSOC_SAVED_ACTION_FOLDERS = QName.createQName(ACTION_MODEL_URI, "savedActionFolders"); //static final QName ASSOC_SAVED_ACTION_FOLDERS = QName.createQName(ACTION_MODEL_URI, "savedActionFolders");
//static final QName TYPE_SAVED_ACTION_FOLDER = QName.createQName(ACTION_MODEL_URI, "savedactionfolder"); //static final QName TYPE_SAVED_ACTION_FOLDER = QName.createQName(ACTION_MODEL_URI, "savedactionfolder");

View File

@@ -235,11 +235,12 @@
<parameter name="caseSensitive"><value>true</value></parameter> <parameter name="caseSensitive"><value>true</value></parameter>
<parameter name="allowedValues"> <parameter name="allowedValues">
<list> <list>
<value>M</value> <value>Month</value>
<value>W</value> <value>Week</value>
<value>D</value> <value>Day</value>
<value>h</value> <value>Hour</value>
<value>m</value> <value>Minute</value>
<value>Second</value>
</list> </list>
</parameter> </parameter>
</constraint> </constraint>
@@ -248,6 +249,10 @@
</properties> </properties>
<associations> <associations>
<association name="act:scheduledAction"> <association name="act:scheduledAction">
<source>
<mandatory>false</mandatory>
<many>false</many>
</source>
<target> <target>
<class>act:action</class> <class>act:action</class>
<mandatory>true</mandatory> <mandatory>true</mandatory>

View File

@@ -75,7 +75,7 @@ public class ScheduledPersistedActionImpl implements ScheduledPersistedAction
/** Get where the action lives */ /** Get where the action lives */
public NodeRef getActionNodeRef() public NodeRef getActionNodeRef()
{ {
return action.getNodeRef(); return action == null ? null : action.getNodeRef();
} }
/** /**
@@ -157,8 +157,8 @@ public class ScheduledPersistedActionImpl implements ScheduledPersistedAction
/** /**
* Returns the interval in a form like 1D (1 day) * Returns the interval in a form like 1Day (1 day)
* or 2h (2 hours), or null if a period+count * or 2Hour (2 hours), or null if a period+count
* hasn't been set * hasn't been set
*/ */
public String getScheduleInterval() public String getScheduleInterval()
@@ -167,7 +167,7 @@ public class ScheduledPersistedActionImpl implements ScheduledPersistedAction
{ {
return null; return null;
} }
return intervalCount.toString() + intervalPeriod.getLetter(); return intervalCount.toString() + intervalPeriod.name();
} }
/** /**

View File

@@ -20,6 +20,7 @@ package org.alfresco.repo.action.scheduled;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@@ -29,14 +30,22 @@ import org.alfresco.repo.action.ActionModel;
import org.alfresco.repo.action.RuntimeActionService; import org.alfresco.repo.action.RuntimeActionService;
import org.alfresco.repo.model.Repository; import org.alfresco.repo.model.Repository;
import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.action.Action; import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ActionService; import org.alfresco.service.cmr.action.ActionService;
import org.alfresco.service.cmr.action.scheduled.ScheduledPersistedAction; import org.alfresco.service.cmr.action.scheduled.ScheduledPersistedAction;
import org.alfresco.service.cmr.action.scheduled.ScheduledPersistedActionService; import org.alfresco.service.cmr.action.scheduled.ScheduledPersistedActionService;
import org.alfresco.service.cmr.action.scheduled.ScheduledPersistedAction.IntervalPeriod;
import org.alfresco.service.cmr.repository.AssociationRef;
import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.namespace.QName; import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.GUID;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.quartz.Job; import org.quartz.Job;
@@ -66,7 +75,7 @@ public class ScheduledPersistedActionServiceImpl implements ScheduledPersistedAc
protected static NodeRef SCHEDULED_ACTION_ROOT_NODE_REF; protected static NodeRef SCHEDULED_ACTION_ROOT_NODE_REF;
protected static final Set<QName> ACTION_TYPES = new HashSet<QName>(Arrays protected static final Set<QName> ACTION_TYPES = new HashSet<QName>(Arrays
.asList(new QName[] { ActionModel.TYPE_ACTION })); // TODO .asList(new QName[] { ActionModel.TYPE_ACTION_SCHEDULE }));
protected static final String SCHEDULER_GROUP = "PersistedActions"; protected static final String SCHEDULER_GROUP = "PersistedActions";
@@ -113,7 +122,7 @@ public class ScheduledPersistedActionServiceImpl implements ScheduledPersistedAc
NodeRef dataDictionary = startupNodeService.getChildByName( NodeRef dataDictionary = startupNodeService.getChildByName(
repositoryHelper.getCompanyHome(), repositoryHelper.getCompanyHome(),
ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS,
"data dictionary" "Data Dictionary"
); );
SCHEDULED_ACTION_ROOT_NODE_REF = startupNodeService.getChildByName( SCHEDULED_ACTION_ROOT_NODE_REF = startupNodeService.getChildByName(
dataDictionary, dataDictionary,
@@ -151,16 +160,72 @@ public class ScheduledPersistedActionServiceImpl implements ScheduledPersistedAc
*/ */
public void saveSchedule(ScheduledPersistedAction schedule) public void saveSchedule(ScheduledPersistedAction schedule)
{ {
ScheduledPersistedActionImpl scheduleImpl = (ScheduledPersistedActionImpl)schedule;
// Remove if already there // Remove if already there
removeFromScheduler((ScheduledPersistedActionImpl) schedule); removeFromScheduler(scheduleImpl);
// TODO Create the node + relationship if not already there if (scheduleImpl.getPersistedAtNodeRef() == null)
{
// if not already persisted, create the persistent schedule
createPersistentSchedule(scheduleImpl);
}
// Save to the repo // update the persistent schedule with schedule properties
// TODO Persist details updatePersistentSchedule(scheduleImpl);
// Add to the scheduler again // Add to the scheduler again
addToScheduler((ScheduledPersistedActionImpl) schedule); addToScheduler(scheduleImpl);
}
private void createPersistentSchedule(ScheduledPersistedActionImpl schedule)
{
ChildAssociationRef childAssoc = nodeService.createNode(SCHEDULED_ACTION_ROOT_NODE_REF,
ContentModel.ASSOC_CONTAINS, QName.createQName(GUID.generate()),
ActionModel.TYPE_ACTION_SCHEDULE);
schedule.setPersistedAtNodeRef(childAssoc.getChildRef());
}
private void updatePersistentSchedule(ScheduledPersistedActionImpl schedule)
{
NodeRef nodeRef = schedule.getPersistedAtNodeRef();
if (nodeRef == null)
throw new IllegalStateException("Must be persisted first");
// update schedule properties
nodeService.setProperty(nodeRef, ActionModel.PROP_START_DATE, schedule.getScheduleStart());
nodeService.setProperty(nodeRef, ActionModel.PROP_INTERVAL_COUNT, schedule.getScheduleIntervalCount());
IntervalPeriod period = schedule.getScheduleIntervalPeriod();
nodeService.setProperty(nodeRef, ActionModel.PROP_INTERVAL_PERIOD, period == null ? null : period.name());
// update scheduled action (represented as an association)
// NOTE: can only associate to a single action from a schedule (as specified by the action model)
// update association to reflect updated schedule
AssociationRef actionAssoc = findActionAssociationFromSchedule(nodeRef);
NodeRef actionNodeRef = schedule.getActionNodeRef();
if (actionNodeRef == null)
{
if (actionAssoc != null)
{
// remove associated action
nodeService.removeAssociation(actionAssoc.getSourceRef(), actionAssoc.getTargetRef(), actionAssoc.getTypeQName());
}
}
else
{
if (actionAssoc == null)
{
// create associated action
nodeService.createAssociation(nodeRef, actionNodeRef, ActionModel.ASSOC_SCHEDULED_ACTION);
}
else if (!actionAssoc.getTargetRef().equals(actionNodeRef))
{
// associated action has changed... first remove existing association
nodeService.removeAssociation(actionAssoc.getSourceRef(), actionAssoc.getTargetRef(), actionAssoc.getTypeQName());
nodeService.createAssociation(nodeRef, actionNodeRef, ActionModel.ASSOC_SCHEDULED_ACTION);
}
}
} }
/** /**
@@ -169,11 +234,24 @@ public class ScheduledPersistedActionServiceImpl implements ScheduledPersistedAc
*/ */
public void deleteSchedule(ScheduledPersistedAction schedule) public void deleteSchedule(ScheduledPersistedAction schedule)
{ {
ScheduledPersistedActionImpl scheduleImpl = (ScheduledPersistedActionImpl)schedule;
// Remove from the scheduler // Remove from the scheduler
removeFromScheduler((ScheduledPersistedActionImpl) schedule); removeFromScheduler(scheduleImpl);
// Now remove from the repo // Now remove from the repo
// TODO deletePersistentSchedule(scheduleImpl);
}
private void deletePersistentSchedule(ScheduledPersistedActionImpl schedule)
{
NodeRef nodeRef = schedule.getPersistedAtNodeRef();
if (nodeRef == null)
return;
// NOTE: this will also cascade delete action association
nodeService.deleteNode(nodeRef);
schedule.setPersistedAtNodeRef(null);
} }
/** /**
@@ -182,11 +260,35 @@ public class ScheduledPersistedActionServiceImpl implements ScheduledPersistedAc
*/ */
public ScheduledPersistedAction getSchedule(Action persistedAction) public ScheduledPersistedAction getSchedule(Action persistedAction)
{ {
// TODO look for a relationship of the special type from NodeRef nodeRef = persistedAction.getNodeRef();
// the action, then if we find it load the schedule via it if (nodeRef == null)
{
// action is not persistent
return null; return null;
} }
// locate associated schedule for action
List<AssociationRef> assocs = nodeService.getSourceAssocs(nodeRef, RegexQNamePattern.MATCH_ALL);
AssociationRef scheduledAssoc = null;
for (AssociationRef assoc : assocs)
{
if (ActionModel.ASSOC_SCHEDULED_ACTION.equals(assoc.getTypeQName()))
{
scheduledAssoc = assoc;
break;
}
}
if (scheduledAssoc == null)
{
// there is no associated schedule
return null;
}
// load the scheduled action
return loadPersistentSchedule(scheduledAssoc.getSourceRef());
}
/** /**
* Returns all currently scheduled actions. * Returns all currently scheduled actions.
*/ */
@@ -204,15 +306,56 @@ public class ScheduledPersistedActionServiceImpl implements ScheduledPersistedAc
childAssocs.size()); childAssocs.size());
for (ChildAssociationRef actionAssoc : childAssocs) for (ChildAssociationRef actionAssoc : childAssocs)
{ {
// TODO ScheduledPersistedActionImpl scheduleImpl = loadPersistentSchedule(actionAssoc.getChildRef());
// Action nextAction = scheduledActions.add(scheduleImpl);
// runtimeActionService.createAction(actionAssoc.getChildRef());
// renderingActions.add(new ReplicationDefinitionImpl(nextAction));
} }
return scheduledActions; return scheduledActions;
} }
protected ScheduledPersistedActionImpl loadPersistentSchedule(NodeRef schedule)
{
if (!nodeService.exists(schedule))
return null;
// create action
Action action = null;
AssociationRef actionAssoc = findActionAssociationFromSchedule(schedule);
if (actionAssoc != null)
{
action = runtimeActionService.createAction(actionAssoc.getTargetRef());
}
// create schedule
ScheduledPersistedActionImpl scheduleImpl = new ScheduledPersistedActionImpl(action);
scheduleImpl.setPersistedAtNodeRef(schedule);
scheduleImpl.setScheduleStart((Date)nodeService.getProperty(schedule, ActionModel.PROP_START_DATE));
scheduleImpl.setScheduleIntervalCount((Integer)nodeService.getProperty(schedule, ActionModel.PROP_INTERVAL_COUNT));
String period = (String)nodeService.getProperty(schedule, ActionModel.PROP_INTERVAL_PERIOD);
if (period != null)
{
scheduleImpl.setScheduleIntervalPeriod(IntervalPeriod.valueOf(period));
}
return scheduleImpl;
}
private AssociationRef findActionAssociationFromSchedule(NodeRef schedule)
{
List<AssociationRef> assocs = nodeService.getTargetAssocs(schedule, RegexQNamePattern.MATCH_ALL);
AssociationRef actionAssoc = null;
for (AssociationRef assoc : assocs)
{
if (ActionModel.ASSOC_SCHEDULED_ACTION.equals(assoc.getTypeQName()))
{
actionAssoc = assoc;
break;
}
}
return actionAssoc;
}
/** /**
* Takes an entry out of the scheduler, if it's currently there. * Takes an entry out of the scheduler, if it's currently there.
*/ */
@@ -287,15 +430,36 @@ public class ScheduledPersistedActionServiceImpl implements ScheduledPersistedAc
public static class ScheduledPersistedActionServiceBootstrap extends AbstractLifecycleBean public static class ScheduledPersistedActionServiceBootstrap extends AbstractLifecycleBean
{ {
private ScheduledPersistedActionServiceImpl service; private ScheduledPersistedActionServiceImpl service;
private RetryingTransactionHelper txnHelper;
public void setScheduledPersistedActionService(ScheduledPersistedActionServiceImpl scheduledPersistedActionService) public void setScheduledPersistedActionService(ScheduledPersistedActionServiceImpl scheduledPersistedActionService)
{ {
this.service = scheduledPersistedActionService; this.service = scheduledPersistedActionService;
} }
public void setTransactionHelper(RetryingTransactionHelper txnHelper)
{
this.txnHelper = txnHelper;
}
public void onBootstrap(ApplicationEvent event) public void onBootstrap(ApplicationEvent event)
{
AuthenticationUtil.runAs(new RunAsWork<Object>()
{
public Object doWork()
{
RetryingTransactionCallback<Object> callback = new RetryingTransactionCallback<Object>()
{
public Object execute() throws Throwable
{ {
service.locatePersistanceFolder(); service.locatePersistanceFolder();
service.schedulePreviouslyPersisted(); service.schedulePreviouslyPersisted();
return null;
}
};
return txnHelper.doInTransaction(callback);
}
}, AuthenticationUtil.getSystemUserName());
} }
public void onShutdown(ApplicationEvent event) public void onShutdown(ApplicationEvent event)

View File

@@ -19,6 +19,7 @@
package org.alfresco.repo.action.scheduled; package org.alfresco.repo.action.scheduled;
import java.util.Date; import java.util.Date;
import java.util.List;
import javax.transaction.UserTransaction; import javax.transaction.UserTransaction;
@@ -28,8 +29,6 @@ import org.alfresco.model.ContentModel;
import org.alfresco.repo.action.ActionImpl; import org.alfresco.repo.action.ActionImpl;
import org.alfresco.repo.action.RuntimeActionService; import org.alfresco.repo.action.RuntimeActionService;
import org.alfresco.repo.action.ActionServiceImplTest.SleepActionExecuter; import org.alfresco.repo.action.ActionServiceImplTest.SleepActionExecuter;
import org.alfresco.repo.action.executer.ActionExecuter;
import org.alfresco.repo.model.Repository;
import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.action.Action; import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ActionService; import org.alfresco.service.cmr.action.ActionService;
@@ -49,7 +48,6 @@ import org.quartz.JobExecutionException;
import org.quartz.Scheduler; import org.quartz.Scheduler;
import org.quartz.SimpleTrigger; import org.quartz.SimpleTrigger;
import org.quartz.Trigger; import org.quartz.Trigger;
import org.quartz.core.jmx.JobDetailSupport;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
@@ -60,79 +58,84 @@ import org.springframework.context.ConfigurableApplicationContext;
*/ */
public class ScheduledPersistedActionServiceTest extends TestCase public class ScheduledPersistedActionServiceTest extends TestCase
{ {
private static ConfigurableApplicationContext ctx = private static ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) ApplicationContextHelper
(ConfigurableApplicationContext)ApplicationContextHelper.getApplicationContext(); .getApplicationContext();
private ScheduledPersistedActionService service; private ScheduledPersistedActionService service;
private ScheduledPersistedActionServiceImpl serviceImpl;
private Scheduler scheduler; private Scheduler scheduler;
private TransactionService transactionService; private TransactionService transactionService;
private RuntimeActionService runtimeActionService; private RuntimeActionService runtimeActionService;
private ActionService actionService; private ActionService actionService;
private NodeService nodeService; private NodeService nodeService;
private Repository repositoryHelper;
private Action testAction; private Action testAction;
private NodeRef scheduledRoot; private Action testAction2;
@Override @Override
protected void setUp() throws Exception protected void setUp() throws Exception
{ {
actionService = (ActionService) ctx.getBean("actionService"); actionService = (ActionService) ctx.getBean("actionService");
nodeService = (NodeService) ctx.getBean("nodeService"); nodeService = (NodeService) ctx.getBean("nodeService");
repositoryHelper = (Repository) ctx.getBean("repositoryHelper");
transactionService = (TransactionService) ctx.getBean("transactionService"); transactionService = (TransactionService) ctx.getBean("transactionService");
runtimeActionService = (RuntimeActionService) ctx.getBean("actionService"); runtimeActionService = (RuntimeActionService) ctx.getBean("actionService");
service = (ScheduledPersistedActionService) ctx.getBean("scheduledPersistedActionService"); service = (ScheduledPersistedActionService) ctx.getBean("ScheduledPersistedActionService");
serviceImpl = (ScheduledPersistedActionServiceImpl) ctx.getBean("scheduledPersistedActionService");
scheduler = (Scheduler) ctx.getBean("schedulerFactory"); scheduler = (Scheduler) ctx.getBean("schedulerFactory");
// Set the current security context as admin // Set the current security context as admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName()); AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
UserTransaction txn = transactionService.getUserTransaction(); UserTransaction txn = transactionService.getUserTransaction();
txn.begin(); txn.begin();
// Zap any existing persisted entries
scheduledRoot = ScheduledPersistedActionServiceImpl.SCHEDULED_ACTION_ROOT_NODE_REF;
for(ChildAssociationRef child : nodeService.getChildAssocs(scheduledRoot))
{
QName type = nodeService.getType( child.getChildRef() );
if(ScheduledPersistedActionServiceImpl.ACTION_TYPES.contains(type))
{
nodeService.deleteNode(child.getChildRef());
}
}
// Register the test executor, if needed // Register the test executor, if needed
SleepActionExecuter.registerIfNeeded(ctx); SleepActionExecuter.registerIfNeeded(ctx);
// Zap all test schedules
// List<ScheduledPersistedAction> schedules = service.listSchedules();
// for (ScheduledPersistedAction schedule : schedules)
// {
// service.deleteSchedule(schedule);
// }
// Persist an action that uses the test executor // Persist an action that uses the test executor
testAction = new TestAction(actionService.createAction(SleepActionExecuter.NAME)); testAction = new TestAction(actionService.createAction(SleepActionExecuter.NAME));
NodeRef actionNodeRef = runtimeActionService.createActionNodeRef(// runtimeActionService.createActionNodeRef(
testAction, //
ScheduledPersistedActionServiceImpl.SCHEDULED_ACTION_ROOT_NODE_REF, testAction, ScheduledPersistedActionServiceImpl.SCHEDULED_ACTION_ROOT_NODE_REF,
ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS, QName.createQName("TestAction"));
QName.createQName("TestAction")
); testAction2 = new TestAction(actionService.createAction(SleepActionExecuter.NAME));
runtimeActionService.createActionNodeRef(
//
testAction2, ScheduledPersistedActionServiceImpl.SCHEDULED_ACTION_ROOT_NODE_REF,
ContentModel.ASSOC_CONTAINS, QName.createQName("TestAction2"));
// Finish setup // Finish setup
txn.commit(); txn.commit();
} }
@Override @Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception
{
UserTransaction txn = transactionService.getUserTransaction(); UserTransaction txn = transactionService.getUserTransaction();
txn.begin(); txn.begin();
// Zap all test schedules
List<ScheduledPersistedAction> schedules = service.listSchedules();
for (ScheduledPersistedAction schedule : schedules)
{
service.deleteSchedule(schedule);
}
txn.commit(); txn.commit();
} }
/** /**
* Test that the {@link ScheduledPersistedAction} implementation * Test that the {@link ScheduledPersistedAction} implementation behaves
* behaves properly * properly
*/ */
public void testPersistedActionImpl() throws Exception public void testPersistedActionImpl() throws Exception
{ {
@@ -144,14 +147,202 @@ public class ScheduledPersistedActionServiceTest extends TestCase
*/ */
/** /**
* Tests that we can create, save, edit, delete etc the * Tests that we can create, save, edit, delete etc the scheduled persisted
* scheduled persisted actions * actions
*/ */
public void testCreation()
{
ScheduledPersistedAction schedule = service.createSchedule(testAction);
assertNotNull(schedule);
assertTrue(testAction == schedule.getAction());
assertEquals(testAction.getNodeRef(), schedule.getAction().getNodeRef());
assertNull(schedule.getScheduleStart());
assertNull(schedule.getScheduleInterval());
assertNull(schedule.getScheduleIntervalCount());
assertNull(schedule.getScheduleIntervalPeriod());
Date now = new Date();
schedule.setScheduleStart(now);
assertEquals(now, schedule.getScheduleStart());
schedule.setScheduleIntervalCount(2);
assertEquals(new Integer(2), schedule.getScheduleIntervalCount());
schedule.setScheduleIntervalPeriod(ScheduledPersistedAction.IntervalPeriod.Day);
assertEquals(ScheduledPersistedAction.IntervalPeriod.Day, schedule.getScheduleIntervalPeriod());
}
public void testCreateSaveLoad() throws Exception
{
// create and save schedule
ScheduledPersistedAction schedule = service.createSchedule(testAction);
assertNotNull(schedule);
Date now = new Date();
schedule.setScheduleStart(now);
schedule.setScheduleIntervalCount(2);
schedule.setScheduleIntervalPeriod(ScheduledPersistedAction.IntervalPeriod.Day);
service.saveSchedule(schedule);
// Load it again, should have the same details still
ScheduledPersistedAction retrieved = serviceImpl.loadPersistentSchedule(((ScheduledPersistedActionImpl)schedule).getPersistedAtNodeRef());
assertNotNull(retrieved);
assertEquals(testAction.getNodeRef(), retrieved.getAction().getNodeRef());
assertEquals(now, retrieved.getScheduleStart());
assertEquals(new Integer(2), retrieved.getScheduleIntervalCount());
assertEquals(ScheduledPersistedAction.IntervalPeriod.Day, retrieved.getScheduleIntervalPeriod());
// Load a 2nd copy, won't be any changes
ScheduledPersistedAction second = serviceImpl.loadPersistentSchedule(((ScheduledPersistedActionImpl)schedule).getPersistedAtNodeRef());
assertNotNull(second);
assertEquals(testAction.getNodeRef(), second.getAction().getNodeRef());
assertEquals(now, second.getScheduleStart());
assertEquals(new Integer(2), second.getScheduleIntervalCount());
assertEquals(ScheduledPersistedAction.IntervalPeriod.Day, second.getScheduleIntervalPeriod());
}
/** /**
* Tests that the listings work, both of all scheduled, * Ensures that we can create, save, edit, save
* and from an action * load, edit, save, load etc, all without
* problems, and without creating duplicates
*/ */
public void testEditing() throws Exception
{
// create and save schedule
ScheduledPersistedAction schedule = service.createSchedule(testAction);
assertNotNull(schedule);
Date now = new Date();
schedule.setScheduleStart(now);
schedule.setScheduleIntervalCount(2);
schedule.setScheduleIntervalPeriod(ScheduledPersistedAction.IntervalPeriod.Day);
service.saveSchedule(schedule);
// Load and check it hasn't changed
ScheduledPersistedAction retrieved = serviceImpl.loadPersistentSchedule(((ScheduledPersistedActionImpl)schedule).getPersistedAtNodeRef());
assertNotNull(retrieved);
assertEquals(testAction.getNodeRef(), retrieved.getAction().getNodeRef());
assertEquals(now, retrieved.getScheduleStart());
assertEquals(new Integer(2), retrieved.getScheduleIntervalCount());
assertEquals(ScheduledPersistedAction.IntervalPeriod.Day, retrieved.getScheduleIntervalPeriod());
// Save and re-load without changes
service.saveSchedule(schedule);
retrieved = serviceImpl.loadPersistentSchedule(((ScheduledPersistedActionImpl)schedule).getPersistedAtNodeRef());
assertNotNull(retrieved);
assertEquals(testAction.getNodeRef(), retrieved.getAction().getNodeRef());
assertEquals(now, retrieved.getScheduleStart());
assertEquals(new Integer(2), retrieved.getScheduleIntervalCount());
assertEquals(ScheduledPersistedAction.IntervalPeriod.Day, retrieved.getScheduleIntervalPeriod());
// Make some small changes
retrieved.setScheduleIntervalCount(3);
service.saveSchedule(retrieved);
retrieved = serviceImpl.loadPersistentSchedule(((ScheduledPersistedActionImpl)schedule).getPersistedAtNodeRef());
assertNotNull(retrieved);
assertEquals(testAction.getNodeRef(), retrieved.getAction().getNodeRef());
assertEquals(now, retrieved.getScheduleStart());
assertEquals(new Integer(3), retrieved.getScheduleIntervalCount());
assertEquals(ScheduledPersistedAction.IntervalPeriod.Day, retrieved.getScheduleIntervalPeriod());
// And some more changes
retrieved.setScheduleIntervalPeriod(ScheduledPersistedAction.IntervalPeriod.Month);
now = new Date();
retrieved.setScheduleStart(now);
service.saveSchedule(retrieved);
retrieved = serviceImpl.loadPersistentSchedule(((ScheduledPersistedActionImpl)schedule).getPersistedAtNodeRef());
assertNotNull(retrieved);
assertEquals(testAction.getNodeRef(), retrieved.getAction().getNodeRef());
assertEquals(now, retrieved.getScheduleStart());
assertEquals(new Integer(3), retrieved.getScheduleIntervalCount());
assertEquals(ScheduledPersistedAction.IntervalPeriod.Month, retrieved.getScheduleIntervalPeriod());
// TODO: associated action
}
/**
* Tests that the listings work, both of all scheduled, and from an action
*/
public void testLoadList() throws Exception
{
assertEquals(0, service.listSchedules().size());
// Create
ScheduledPersistedAction schedule1 = service.createSchedule(testAction);
assertNotNull(schedule1);
ScheduledPersistedAction schedule2 = service.createSchedule(testAction2);
assertNotNull(schedule2);
assertEquals(0, service.listSchedules().size());
service.saveSchedule(schedule1);
assertEquals(1, service.listSchedules().size());
assertEquals(testAction.getNodeRef(), service.listSchedules().get(0).getActionNodeRef());
service.saveSchedule(schedule2);
assertEquals(2, service.listSchedules().size());
}
public void testLoadFromAction() throws Exception
{
// Create schedule
ScheduledPersistedAction schedule1 = service.createSchedule(testAction);
assertNotNull(schedule1);
service.saveSchedule(schedule1);
// retrieve schedule for action which doesn't have schedule
ScheduledPersistedAction retrieved = service.getSchedule(testAction2);
assertNull(retrieved);
retrieved = service.getSchedule(testAction);
assertNotNull(retrieved);
assertEquals(testAction.getNodeRef(), retrieved.getActionNodeRef());
}
/**
* Ensures that deletion works correctly
*/
public void testDeletion() throws Exception
{
// Delete does nothing if not persisted
assertEquals(0, service.listSchedules().size());
ScheduledPersistedAction schedule1 = service.createSchedule(testAction);
assertEquals(0, service.listSchedules().size());
service.deleteSchedule(schedule1);
assertEquals(0, service.listSchedules().size());
// Create and save two
ScheduledPersistedAction schedule2 = service.createSchedule(testAction2);
service.saveSchedule(schedule1);
service.saveSchedule(schedule2);
assertEquals(2, service.listSchedules().size());
NodeRef schedule1NodeRef = ((ScheduledPersistedActionImpl)schedule1).getPersistedAtNodeRef();
NodeRef schedule2NodeRef = ((ScheduledPersistedActionImpl)schedule2).getPersistedAtNodeRef();
// Delete one - the correct one goes!
service.deleteSchedule(schedule2);
assertEquals(1, service.listSchedules().size());
assertEquals(testAction.getNodeRef(), service.listSchedules().get(0).getActionNodeRef());
assertNotNull(serviceImpl.loadPersistentSchedule(schedule1NodeRef));
assertNull(serviceImpl.loadPersistentSchedule(schedule2NodeRef));
// Re-delete already deleted, no change
service.deleteSchedule(schedule2);
assertEquals(1, service.listSchedules().size());
assertEquals(testAction.getNodeRef(), service.listSchedules().get(0).getActionNodeRef());
assertNotNull(serviceImpl.loadPersistentSchedule(schedule1NodeRef));
assertNull(serviceImpl.loadPersistentSchedule(schedule2NodeRef));
// Delete the 2nd
service.deleteSchedule(schedule1);
assertEquals(0, service.listSchedules().size());
assertNull(serviceImpl.loadPersistentSchedule(schedule1NodeRef));
assertNull(serviceImpl.loadPersistentSchedule(schedule2NodeRef));
// Can add back in again after being deleted
service.saveSchedule(schedule1);
assertEquals(1, service.listSchedules().size());
assertEquals(testAction.getNodeRef(), service.listSchedules().get(0).getActionNodeRef());
}
/** /**
* Tests that things get properly injected onto the job bean * Tests that things get properly injected onto the job bean
@@ -160,12 +351,8 @@ public class ScheduledPersistedActionServiceTest extends TestCase
{ {
// The job should run almost immediately // The job should run almost immediately
Job job = new TestJob(); Job job = new TestJob();
JobDetail details = new JobDetail( JobDetail details = new JobDetail("ThisIsATest", null, job.getClass());
"ThisIsATest", null, job.getClass() Trigger now = new SimpleTrigger("TestTrigger", new Date(1));
);
Trigger now = new SimpleTrigger(
"TestTrigger", new Date(1)
);
now.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW); now.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);
Scheduler scheduler = (Scheduler) ctx.getBean("schedulerFactory"); Scheduler scheduler = (Scheduler) ctx.getBean("schedulerFactory");
@@ -188,32 +375,23 @@ public class ScheduledPersistedActionServiceTest extends TestCase
*/ */
public void testExecution() throws Exception public void testExecution() throws Exception
{ {
final SleepActionExecuter sleepActionExec = final SleepActionExecuter sleepActionExec = (SleepActionExecuter) ctx.getBean(SleepActionExecuter.NAME);
(SleepActionExecuter)ctx.getBean(SleepActionExecuter.NAME);
sleepActionExec.resetTimesExecuted(); sleepActionExec.resetTimesExecuted();
sleepActionExec.setSleepMs(1); sleepActionExec.setSleepMs(1);
ScheduledPersistedAction schedule; ScheduledPersistedAction schedule;
// Until the schedule is persisted, nothing will happen // Until the schedule is persisted, nothing will happen
schedule = service.createSchedule(testAction); schedule = service.createSchedule(testAction);
assertEquals(0, scheduler.getJobNames(ScheduledPersistedActionServiceImpl.SCHEDULER_GROUP).length); assertEquals(0, scheduler.getJobNames(ScheduledPersistedActionServiceImpl.SCHEDULER_GROUP).length);
// A job due to start in 1 second, and run once // A job due to start in 1 second, and run once
schedule = service.createSchedule(testAction); schedule = service.createSchedule(testAction);
schedule.setScheduleStart( schedule.setScheduleStart(new Date(System.currentTimeMillis() + 1000));
new Date(System.currentTimeMillis()+1000)
);
assertNull(schedule.getScheduleInterval()); assertNull(schedule.getScheduleInterval());
assertNull(schedule.getScheduleIntervalCount()); assertNull(schedule.getScheduleIntervalCount());
assertNull(schedule.getScheduleIntervalPeriod()); assertNull(schedule.getScheduleIntervalPeriod());
// TODO - Remove this hacky workaround when real persistence is in
((ScheduledPersistedActionImpl)schedule).setPersistedAtNodeRef(
testAction.getNodeRef()
);
System.out.println("Job starts in 1 second, no repeat..."); System.out.println("Job starts in 1 second, no repeat...");
service.saveSchedule(schedule); service.saveSchedule(schedule);
@@ -233,31 +411,21 @@ public class ScheduledPersistedActionServiceTest extends TestCase
service.deleteSchedule(schedule); service.deleteSchedule(schedule);
assertEquals(0, scheduler.getJobNames(ScheduledPersistedActionServiceImpl.SCHEDULER_GROUP).length); assertEquals(0, scheduler.getJobNames(ScheduledPersistedActionServiceImpl.SCHEDULER_GROUP).length);
// ========================== // ==========================
// A job that runs every 2 seconds, for the next 3.5 seconds // A job that runs every 2 seconds, for the next 3.5 seconds
// (Should get to run twice, now and @2 secs) // (Should get to run twice, now and @2 secs)
schedule = service.createSchedule(testAction); schedule = service.createSchedule(testAction);
schedule.setScheduleStart( schedule.setScheduleStart(new Date(0));
new Date(0) ((ScheduledPersistedActionImpl) schedule).setScheduleEnd(new Date(System.currentTimeMillis() + 3500));
);
((ScheduledPersistedActionImpl)schedule).setScheduleEnd(
new Date(System.currentTimeMillis()+3500)
);
schedule.setScheduleIntervalCount(2); schedule.setScheduleIntervalCount(2);
schedule.setScheduleIntervalPeriod(IntervalPeriod.Second); schedule.setScheduleIntervalPeriod(IntervalPeriod.Second);
assertEquals("2s", schedule.getScheduleInterval()); assertEquals("2Second", schedule.getScheduleInterval());
// Reset count // Reset count
sleepActionExec.resetTimesExecuted(); sleepActionExec.resetTimesExecuted();
assertEquals(0, sleepActionExec.getTimesExecuted()); assertEquals(0, sleepActionExec.getTimesExecuted());
// TODO - Remove this hacky workaround when real persistence is in
((ScheduledPersistedActionImpl)schedule).setPersistedAtNodeRef(
testAction.getNodeRef()
);
System.out.println("Job starts now, repeats twice @ 2s"); System.out.println("Job starts now, repeats twice @ 2s");
service.saveSchedule(schedule); service.saveSchedule(schedule);
@@ -270,28 +438,20 @@ public class ScheduledPersistedActionServiceTest extends TestCase
service.deleteSchedule(schedule); service.deleteSchedule(schedule);
assertEquals(0, scheduler.getJobNames(ScheduledPersistedActionServiceImpl.SCHEDULER_GROUP).length); assertEquals(0, scheduler.getJobNames(ScheduledPersistedActionServiceImpl.SCHEDULER_GROUP).length);
// ========================== // ==========================
// A job that starts in 2 seconds time, and runs // A job that starts in 2 seconds time, and runs
// every second until we kill it // every second until we kill it
schedule = service.createSchedule(testAction); schedule = service.createSchedule(testAction);
schedule.setScheduleStart( schedule.setScheduleStart(new Date(System.currentTimeMillis() + 2000));
new Date(System.currentTimeMillis()+2000)
);
schedule.setScheduleIntervalCount(1); schedule.setScheduleIntervalCount(1);
schedule.setScheduleIntervalPeriod(IntervalPeriod.Second); schedule.setScheduleIntervalPeriod(IntervalPeriod.Second);
assertEquals("1s", schedule.getScheduleInterval()); assertEquals("1Second", schedule.getScheduleInterval());
// Reset count // Reset count
sleepActionExec.resetTimesExecuted(); sleepActionExec.resetTimesExecuted();
assertEquals(0, sleepActionExec.getTimesExecuted()); assertEquals(0, sleepActionExec.getTimesExecuted());
// TODO - Remove this hacky workaround when real persistence is in
((ScheduledPersistedActionImpl)schedule).setPersistedAtNodeRef(
testAction.getNodeRef()
);
System.out.println("Job starts in 2s, repeats @ 1s"); System.out.println("Job starts in 2s, repeats @ 1s");
service.saveSchedule(schedule); service.saveSchedule(schedule);
@@ -304,25 +464,18 @@ public class ScheduledPersistedActionServiceTest extends TestCase
assertEquals(0, scheduler.getJobNames(ScheduledPersistedActionServiceImpl.SCHEDULER_GROUP).length); assertEquals(0, scheduler.getJobNames(ScheduledPersistedActionServiceImpl.SCHEDULER_GROUP).length);
// Check it ran an appropriate number of times // Check it ran an appropriate number of times
assertEquals( assertEquals("Didn't run enough - " + sleepActionExec.getTimesExecuted(), true, sleepActionExec
"Didn't run enough - " + sleepActionExec.getTimesExecuted(), .getTimesExecuted() >= 3);
true, assertEquals("Ran too much - " + sleepActionExec.getTimesExecuted(), true,
sleepActionExec.getTimesExecuted() >= 3 sleepActionExec.getTimesExecuted() < 5);
);
assertEquals(
"Ran too much - " + sleepActionExec.getTimesExecuted(),
true,
sleepActionExec.getTimesExecuted() < 5
);
// Ensure it finished shutting down // Ensure it finished shutting down
Thread.sleep(500); Thread.sleep(500);
} }
/** /**
* Tests that when we have more than one schedule * Tests that when we have more than one schedule defined and active, then
* defined and active, then the correct things run * the correct things run at the correct times, and we never get confused
* at the correct times, and we never get confused
*/ */
public void DISABLEDtestMultipleExecutions() throws Exception public void DISABLEDtestMultipleExecutions() throws Exception
{ {
@@ -342,7 +495,6 @@ public class ScheduledPersistedActionServiceTest extends TestCase
// ============================================================================ // ============================================================================
/** /**
* For unit testing only - not thread safe! * For unit testing only - not thread safe!
*/ */
@@ -351,17 +503,19 @@ public class ScheduledPersistedActionServiceTest extends TestCase
private static boolean gotContext = false; private static boolean gotContext = false;
private static boolean ran = false; private static boolean ran = false;
public TestJob() { public TestJob()
{
gotContext = false; gotContext = false;
ran = false; ran = false;
} }
public void setApplicationContext(ApplicationContext applicationContext) public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
throws BeansException { {
gotContext = true; gotContext = true;
} }
public void execute(JobExecutionContext paramJobExecutionContext)
throws JobExecutionException { public void execute(JobExecutionContext paramJobExecutionContext) throws JobExecutionException
{
ran = true; ran = true;
} }
} }

View File

@@ -83,26 +83,18 @@ public interface ScheduledPersistedAction
/** /**
* Returns the interval in a form like 1D (1 day) * Returns the interval in a form like 1Day (1 day)
* or 2h (2 hours) * or 2Hour (2 hours)
*/ */
public String getScheduleInterval(); public String getScheduleInterval();
public static enum IntervalPeriod { public static enum IntervalPeriod {
Month ('M'), Month,
Week ('W'), Week,
Day ('D'), Day,
Hour ('h'), Hour,
Minute ('m'), Minute,
Second ('s'); Second;
private final char letter;
IntervalPeriod(char letter) {
this.letter = letter;
}
public char getLetter() {
return letter;
}
} }
} }