BATCH-679, BATCH-879: add Flow abstraction and FlowJob with support for decisions, splits and pauses.

This commit is contained in:
dsyer
2008-10-27 13:50:27 +00:00
parent 26f6327e4b
commit 48bbafb449
34 changed files with 2244 additions and 387 deletions

View File

@@ -21,11 +21,12 @@ package org.springframework.batch.core;
* Enumeration representing the status of a an Execution.
*
* @author Lucas Ward
* @author Dave Syer
*/
public enum BatchStatus {
COMPLETED, STARTED, STARTING, FAILED, STOPPING, STOPPED, UNKNOWN, PAUSED;
COMPLETED, STARTED, STARTING, PAUSED, FAILED, STOPPING, STOPPED, UNKNOWN;
public static BatchStatus max(BatchStatus status1, BatchStatus status2) {
if (status1.compareTo(status2)<0) {

View File

@@ -193,6 +193,24 @@ public class JobExecution extends Entity {
status = BatchStatus.STOPPING;
}
/**
* Signal that this job execution wishes to be paused.
*/
public void pause() {
status = BatchStatus.PAUSED;
}
/**
* Test if the {@link JobExecution} has been paused.
*
* @see #pause()
*
* @return true if this instance is paused
*/
public boolean isPaused() {
return status==BatchStatus.PAUSED;
}
/**
* Sets the {@link ExecutionContext} for this execution
*

View File

@@ -217,14 +217,22 @@ public abstract class AbstractJob implements Job, BeanNameAware, InitializingBea
if (execution.getStatus() != BatchStatus.STOPPING) {
execution.setStartTime(new Date());
updateStatus(execution, BatchStatus.STARTING);
// If paused we need to retain the status so that subclasses can
// handle the resume, otherwise we mark it as started...
if (!execution.isPaused()) {
updateStatus(execution, BatchStatus.STARTED);
}
listener.beforeJob(execution);
StepExecution lastStepExecution = doExecute(execution);
if (lastStepExecution != null) {
execution.setStatus(lastStepExecution.getStatus());
if (!execution.isPaused()) {
// If the subclass wants to pause don't change the
// status.
execution.setStatus(lastStepExecution.getStatus());
}
execution.setExitStatus(lastStepExecution.getExitStatus());
}
}
@@ -232,27 +240,17 @@ public abstract class AbstractJob implements Job, BeanNameAware, InitializingBea
// The job was already stopped before we even got this far. Deal
// with it in the same way as any other interruption.
if (execution.getStatus() == BatchStatus.PAUSED) {
// do nothing
}
else {
execution.setStatus(BatchStatus.STOPPED);
execution.setExitStatus(ExitStatus.FINISHED);
execution.setStatus(BatchStatus.STOPPED);
execution.setExitStatus(ExitStatus.FINISHED);
}
}
}
catch (JobInterruptedException e) {
logger.error(e);
if (execution.getStatus() == BatchStatus.PAUSED) {
// do nothing
}
else {
execution.setExitStatus(ExitStatus.FAILED);
execution.setStatus(BatchStatus.STOPPED);
execution.addFailureException(e);
}
execution.setExitStatus(ExitStatus.FAILED);
execution.setStatus(BatchStatus.STOPPED);
execution.addFailureException(e);
}
catch (Throwable t) {
logger.error(t);
@@ -313,7 +311,6 @@ public abstract class AbstractJob implements Job, BeanNameAware, InitializingBea
if (shouldStart(jobInstance, step)) {
updateStatus(execution, BatchStatus.STARTED);
currentStepExecution = execution.createStepExecution(step.getName());
StepExecution lastStepExecution = jobRepository.getLastStepExecution(jobInstance, step.getName());
@@ -327,7 +324,7 @@ public abstract class AbstractJob implements Job, BeanNameAware, InitializingBea
else {
currentStepExecution.setExecutionContext(new ExecutionContext());
}
jobRepository.add(currentStepExecution);
step.execute(currentStepExecution);

View File

@@ -0,0 +1,26 @@
package org.springframework.batch.core.job.flow;
import org.springframework.batch.flow.AbstractState;
/**
* @author Dave Syer
*
*/
public class DecisionState extends AbstractState<JobFlowExecutor> {
private final JobExecutionDecider decider;
/**
* @param name
*/
DecisionState(String name, JobExecutionDecider decider) {
super(name);
this.decider = decider;
}
@Override
public String handle(JobFlowExecutor context) throws Exception {
return decider.decide(context.getJobExecution());
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.core.job.flow;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionException;
import org.springframework.batch.core.JobInterruptedException;
import org.springframework.batch.core.StartLimitExceededException;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.job.AbstractJob;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.batch.flow.Flow;
import org.springframework.batch.flow.FlowExecution;
import org.springframework.batch.flow.FlowExecutionException;
import org.springframework.util.Assert;
/**
* @author Dave Syer
*
*/
public class FlowJob extends AbstractJob {
private Flow<JobFlowExecutor> flow;
/**
* Public setter for the flow.
* @param flow the flow to set
*/
public void setFlow(Flow<JobFlowExecutor> flow) {
this.flow = flow;
}
/**
* @see AbstractJob#doExecute(JobExecution)
*/
@Override
protected StepExecution doExecute(final JobExecution execution) throws JobExecutionException {
try {
FlowExecution result = flow.start(new JobFlowExecutor() {
public String executeStep(Step step) throws JobInterruptedException, JobRestartException, StartLimitExceededException {
StepExecution stepExecution = handleStep(step, execution);
return stepExecution==null ? FlowExecution.COMPLETED : stepExecution.getExitStatus().getExitCode();
}
public JobExecution getJobExecution() {
return execution;
}
});
return getLastStepExecution(execution, result);
}
catch (FlowExecutionException e) {
if (e.getCause() instanceof JobExecutionException) {
throw (JobExecutionException) e.getCause();
}
throw new JobExecutionException("Flow execution ended unexpectedly", e);
}
}
/**
* @param execution the current {@link JobExecution}
* @param result the result of the flow execution
* @return a {@link StepExecution} with matching properties to the result
*/
private StepExecution getLastStepExecution(JobExecution execution, FlowExecution result) {
StepExecution value = null;
StepExecution backup = null;
for (StepExecution stepExecution : execution.getStepExecutions()) {
if (stepExecution.getStepName().equals(result.getName())
&& stepExecution.getExitStatus().getExitCode().equals(result.getStatus())) {
value = stepExecution;
}
if (isLater(backup,stepExecution)) {
backup = stepExecution;
}
}
if (value==null) {
value = backup;
}
Assert.state(value != null, String.format(
"Could not locate step execution matching expected properties: flowExecution=%s, stepExecutions=%s",
result, execution.getStepExecutions()));
return value;
}
/**
* @param first
* @param second
* @return true if the first is deemed to be executed after the second
*/
private boolean isLater(StepExecution first, StepExecution second) {
if (first==null) {
return true;
}
if (first.getEndTime()==null) {
return first.getStartTime().after(second.getStartTime());
}
if (second.getEndTime()==null) {
return false;
}
return first.getEndTime().after(second.getEndTime());
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.core.job.flow;
import org.springframework.batch.core.JobExecution;
/**
* @author Dave Syer
*
*/
public interface JobExecutionDecider {
/**
* Strategy for branching an execution based on the state of an ongoing
* {@link JobExecution}. The return value will be used as a status to
* determine the next step in the job.
*
* @param jobExecution a job execution
* @return the exit status code
*/
String decide(JobExecution jobExecution);
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.core.job.flow;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobInterruptedException;
import org.springframework.batch.core.StartLimitExceededException;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.batch.flow.Flow;
/**
* Context and execution strategy for {@link FlowJob} to allow it to delegate
* its execution step by step.
*
* @author Dave Syer
*
*/
public interface JobFlowExecutor {
/**
* @param step a {@link Step} to execute
* @return the exit status that drives the surrounding {@link Flow}
* @throws StartLimitExceededException
* @throws JobRestartException
* @throws JobInterruptedException
*/
String executeStep(Step step) throws JobInterruptedException, JobRestartException, StartLimitExceededException;
/**
* @return the current {@link JobExecution}
*/
JobExecution getJobExecution();
}

View File

@@ -0,0 +1,40 @@
package org.springframework.batch.core.job.flow;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.flow.AbstractState;
import org.springframework.batch.flow.FlowExecution;
/**
* @author Dave Syer
*
*/
public class PauseState extends AbstractState<JobFlowExecutor> {
/**
* @param name
*/
PauseState(String name) {
super(name);
}
@Override
public String handle(JobFlowExecutor context) throws Exception {
JobExecution jobExecution = context.getJobExecution();
// This state is just a toggle for the status of the job execution. If
// not already paused we pause it, and expect the flow to respect the
// status.
if (!jobExecution.isPaused()) {
jobExecution.pause();
return FlowExecution.PAUSED;
}
// ...otherwise set the status to show that it has resumed
jobExecution.setStatus(BatchStatus.STARTED);
return FlowExecution.COMPLETED;
}
}

View File

@@ -0,0 +1,31 @@
package org.springframework.batch.core.job.flow;
import org.springframework.batch.core.Step;
import org.springframework.batch.flow.AbstractState;
import org.springframework.batch.flow.State;
/**
* {@link State} implementation that delegates to a {@link JobFlowExecutor} to
* execute the specified {@link Step}.
*
* @author Dave Syer
*
*/
public class StepState extends AbstractState<JobFlowExecutor> {
private final Step step;
/**
* @param step the step that will be executed
*/
StepState(Step step) {
super(step.getName());
this.step = step;
}
@Override
public String handle(JobFlowExecutor context) throws Exception {
return context.executeStep(step);
}
}

View File

@@ -15,13 +15,12 @@
*/
package org.springframework.batch.core.launch;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
/**
* Simple interface for controlling jobs, including possible ad-hoc executions,
@@ -39,13 +38,11 @@ public interface JobLauncher {
/**
* Start a job execution for the given {@link Job} and {@link JobParameters}
* . If a JobExecution was able to be created successfully, it will always
* be returned by this method, regardless of whether or not the execution
* was successful.
*
* If there exists a past {@link JobExecution} and its status is
* {@link BatchStatus#PAUSED}, the same JobExecution should be continued
* instead of new one created.
* . If a {@link JobExecution} was able to be created successfully, it will
* always be returned by this method, regardless of whether or not the
* execution was successful. If there is a past {@link JobExecution} which
* has paused, the same {@link JobExecution} is returned instead of a new
* one created.
*
* @return the {@link JobExecution} if it returns synchronously. If the
* implementation is asynchronous, the status might well be unknown.

View File

@@ -17,16 +17,15 @@ package org.springframework.batch.core.launch.support;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobInstance;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.task.SyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;
@@ -85,7 +84,7 @@ public class SimpleJobLauncher implements JobLauncher, InitializingBean {
final JobExecution jobExecution;
JobExecution lastExecution = jobRepository.getLastJobExecution(job.getName(), jobParameters);
if (lastExecution != null) {
if (lastExecution.getStatus() == BatchStatus.PAUSED) {
if (lastExecution.isPaused()) {
jobExecution = lastExecution;
// this execution will be continued => delete the end time
jobExecution.setEndTime(null);

View File

@@ -370,7 +370,7 @@ public class SimpleJobOperator implements JobOperator, InitializingBean {
public boolean pause(long executionId) throws NoSuchJobExecutionException {
JobExecution jobExecution = findExecutionById(executionId);
jobExecution.setStatus(BatchStatus.PAUSED);
jobExecution.pause();
jobRepository.update(jobExecution);
return true;
}

View File

@@ -322,7 +322,7 @@ public class SimpleJobRepository implements JobRepository {
private void checkForInterruption(StepExecution stepExecution){
JobExecution jobExecution = stepExecution.getJobExecution();
jobExecutionDao.synchronizeStatus(jobExecution);
if(jobExecution.getStatus() == BatchStatus.STOPPING || jobExecution.getStatus() == BatchStatus.PAUSED){
if(jobExecution.getStatus() == BatchStatus.STOPPING){
stepExecution.setTerminateOnly();
}
}

View File

@@ -1,221 +0,0 @@
/*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.core.job;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Collections;
import org.junit.Before;
import org.junit.Test;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionException;
import org.springframework.batch.core.JobInterruptedException;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.UnexpectedJobExecutionException;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean;
import org.springframework.batch.core.step.StepSupport;
import org.springframework.batch.repeat.ExitStatus;
import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
/**
* @author Dave Syer
*
*/
public class ConditionalJobTests {
private ConditionalJob job = new ConditionalJob("job");
private JobExecution jobExecution;
@Before
public void setUp() throws Exception {
MapJobRepositoryFactoryBean.clear();
MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean();
factory.setTransactionManager(new ResourcelessTransactionManager());
factory.afterPropertiesSet();
JobRepository jobRepository = (JobRepository) factory.getObject();
job.setJobRepository(jobRepository);
jobExecution = jobRepository.createJobExecution("job", new JobParameters());
}
@Test(expected = IllegalArgumentException.class)
public void testEmptySteps() throws Exception {
job.setStepTransitions(Collections.<StepTransition> emptySet());
job.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void testNoNextStepSpecified() throws Exception {
job.setStepTransitions(Collections.singleton(new StepTransition(new StepSupport("step"), "*", "foo")));
job.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void testNoStartStep() throws Exception {
job.setStepTransitions(Arrays.asList(new StepTransition(new StepSupport("step"), "FAILED", "step"),
new StepTransition(new StepSupport("step"), "*")));
job.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void testNoEndStep() throws Exception {
job.setStepTransitions(Collections.singleton(new StepTransition(new StepSupport("step"), "FAILED", "step")));
job.setStartStepName("step");
job.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void testMultipleStartSteps() throws Exception {
job.setStepTransitions(Arrays.asList(new StepTransition(new StubStep("step1"), "*"), new StepTransition(
new StubStep("step2"), "*")));
job.afterPropertiesSet();
}
@Test
public void testNoMatchForNextStep() throws Exception {
job.setStepTransitions(Arrays.asList(new StepTransition(new StubStep("step1"), "FOO", "step2"),
new StepTransition(new StubStep("step2"), "*")));
job.afterPropertiesSet();
try {
job.doExecute(jobExecution);
fail("Expected JobExecutionException");
}
catch (JobExecutionException e) {
// expected
String message = e.getMessage();
assertTrue("Wrong message: " + message, message.toLowerCase().contains("next step not found"));
}
}
@Test
public void testOneStep() throws Exception {
job.setStepTransitions(Arrays.asList(new StepTransition(new StubStep("step1"), "*")));
job.afterPropertiesSet();
StepExecution stepExecution = job.doExecute(jobExecution);
assertEquals(ExitStatus.FINISHED, stepExecution.getExitStatus());
assertEquals(1, jobExecution.getStepExecutions().size());
}
@Test
public void testExplicitStartStep() throws Exception {
job.setStepTransitions(Arrays.asList(new StepTransition(new StubStep("step"), "FAILED", "step"),
new StepTransition(new StubStep("step"), "*")));
job.setStartStepName("step");
job.afterPropertiesSet();
StepExecution stepExecution = job.doExecute(jobExecution);
assertEquals(ExitStatus.FINISHED, stepExecution.getExitStatus());
assertEquals(1, jobExecution.getStepExecutions().size());
}
@Test
public void testTwoSteps() throws Exception {
job.setStepTransitions(Arrays.asList(new StepTransition(new StubStep("step1"), "*", "step2"),
new StepTransition(new StubStep("step2"), "*")));
job.afterPropertiesSet();
StepExecution stepExecution = job.doExecute(jobExecution);
assertEquals(ExitStatus.FINISHED, stepExecution.getExitStatus());
assertEquals(2, jobExecution.getStepExecutions().size());
}
@Test
public void testFailedStep() throws Exception {
job.setStepTransitions(Arrays.asList(new StepTransition(new StubStep("step1") {
@Override
public void execute(StepExecution stepExecution) throws JobInterruptedException,
UnexpectedJobExecutionException {
stepExecution.setStatus(BatchStatus.FAILED);
stepExecution.setExitStatus(ExitStatus.FAILED);
}
}, "*", "step2"), new StepTransition(new StubStep("step2"), "*")));
job.afterPropertiesSet();
StepExecution stepExecution = job.doExecute(jobExecution);
assertEquals(ExitStatus.FINISHED, stepExecution.getExitStatus());
assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus());
assertEquals(2, jobExecution.getStepExecutions().size());
}
@Test
public void testStoppingStep() throws Exception {
job.setStepTransitions(Arrays.asList(new StepTransition(new StubStep("step1") {
@Override
public void execute(StepExecution stepExecution) throws JobInterruptedException,
UnexpectedJobExecutionException {
stepExecution.setStatus(BatchStatus.STOPPED);
}
}, "*", "step2"),
new StepTransition(new StubStep("step2"), "*")));
job.afterPropertiesSet();
try {
job.doExecute(jobExecution);
fail("Expected JobInterruptedException");
} catch (JobInterruptedException e) {
// expected
}
assertEquals(1, jobExecution.getStepExecutions().size());
}
@Test
public void testBranching() throws Exception {
job.setStepTransitions(Arrays.asList(new StepTransition(new StubStep("step1"), "*", "step2"),
new StepTransition(new StubStep("step1"), "COMPLETED", "step3"), new StepTransition(new StubStep(
"step2"), "*"), new StepTransition(new StubStep("step3"), "*")));
job.afterPropertiesSet();
StepExecution stepExecution = job.doExecute(jobExecution);
assertEquals(ExitStatus.FINISHED, stepExecution.getExitStatus());
assertEquals(2, jobExecution.getStepExecutions().size());
assertEquals("step3", stepExecution.getStepName());
}
/**
* @author Dave Syer
*
*/
private static class StubStep extends StepSupport {
/**
*
*/
public StubStep() {
super();
}
/**
* @param string
*/
public StubStep(String string) {
super(string);
}
/**
* @see StepSupport#execute(StepExecution)
*/
@Override
public void execute(StepExecution stepExecution) throws JobInterruptedException,
UnexpectedJobExecutionException {
stepExecution.setStatus(BatchStatus.COMPLETED);
stepExecution.setExitStatus(ExitStatus.FINISHED);
}
}
}

View File

@@ -1,129 +0,0 @@
/*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.core.job;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.batch.core.step.StepSupport;
import org.springframework.batch.repeat.ExitStatus;
/**
* @author Dave Syer
*
*/
public class StepTransitionTests {
@Test
public void testIsEnd() {
StepTransition transition = new StepTransition(new StepSupport(), "");
assertTrue(transition.isEnd());
assertNull(transition.getNext());
}
@Test
public void testMatchesStar() {
StepTransition transition = new StepTransition(new StepSupport(), "*", "start");
assertTrue(transition.matches(ExitStatus.CONTINUABLE));
}
@Test
public void testMatchesNull() {
StepTransition transition = new StepTransition(new StepSupport(), null, "start");
assertTrue(transition.matches(ExitStatus.CONTINUABLE));
}
@Test
public void testMatchesEmpty() {
StepTransition transition = new StepTransition(new StepSupport(), "", "start");
assertTrue(transition.matches(ExitStatus.CONTINUABLE));
}
@Test
public void testMatchesExact() {
StepTransition transition = new StepTransition(new StepSupport(), "CONTINUABLE", "start");
assertTrue(transition.matches(ExitStatus.CONTINUABLE));
}
@Test
public void testMatchesWildcard() {
StepTransition transition = new StepTransition(new StepSupport(), "CONTIN*", "start" );
assertTrue(transition.matches(ExitStatus.CONTINUABLE));
}
@Test
public void testMatchesPlaceholder() {
StepTransition transition = new StepTransition(new StepSupport(), "CONTIN???LE", "start");
assertTrue(transition.matches(ExitStatus.CONTINUABLE));
}
@Test
public void testSimpleOrderingEqual() {
StepTransition transition = new StepTransition(new StepSupport(), "CONTIN???LE", "start");
assertEquals(0, transition.compareTo(transition));
}
@Test
public void testSimpleOrderingMoreGeneral() {
StepTransition transition = new StepTransition(new StepSupport(), "CONTIN???LE", "start");
StepTransition other = new StepTransition(new StepSupport(), "CONTINUABLE", "start");
assertEquals(1, transition.compareTo(other));
assertEquals(-1, other.compareTo(transition));
}
@Test
public void testSimpleOrderingMostGeneral() {
StepTransition transition = new StepTransition(new StepSupport(), "*", "start");
StepTransition other = new StepTransition(new StepSupport(), "CONTINUABLE", "start");
assertEquals(1, transition.compareTo(other));
assertEquals(-1, other.compareTo(transition));
}
@Test
public void testSubstringAndWildcard() {
StepTransition transition = new StepTransition(new StepSupport(), "CONTIN*", "start");
StepTransition other = new StepTransition(new StepSupport(), "CONTINUABLE", "start");
assertEquals(1, transition.compareTo(other));
assertEquals(-1, other.compareTo(transition));
}
@Test
public void testSimpleOrderingMostToNextGeneral() {
StepTransition transition = new StepTransition(new StepSupport(), "*", "start");
StepTransition other = new StepTransition(new StepSupport(), "C?", "start");
assertEquals(1, transition.compareTo(other));
assertEquals(-1, other.compareTo(transition));
}
@Test
public void testSimpleOrderingAdjacent() {
StepTransition transition = new StepTransition(new StepSupport(), "CON*", "start");
StepTransition other = new StepTransition(new StepSupport(), "CON?", "start");
assertEquals(1, transition.compareTo(other));
assertEquals(-1, other.compareTo(transition));
}
@Test
public void testToString() {
StepTransition transition = new StepTransition(new StepSupport(), "CONTIN???LE", "start");
String string = transition.toString();
assertTrue("Wrong string: " + string, string.contains("StepTransition"));
assertTrue("Wrong string: " + string, string.contains("start"));
assertTrue("Wrong string: " + string, string.contains("CONTIN???LE"));
assertTrue("Wrong string: " + string, string.contains("next="));
}
}

View File

@@ -0,0 +1,228 @@
/*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.core.job.flow;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.junit.Before;
import org.junit.Test;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobInterruptedException;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.UnexpectedJobExecutionException;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean;
import org.springframework.batch.core.step.StepSupport;
import org.springframework.batch.flow.SimpleFlow;
import org.springframework.batch.flow.StateTransition;
import org.springframework.batch.repeat.ExitStatus;
import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
/**
* @author Dave Syer
*
*/
public class FlowJobTests {
private FlowJob job = new FlowJob();
private JobExecution jobExecution;
private JobRepository jobRepository;
@Before
public void setUp() throws Exception {
MapJobRepositoryFactoryBean.clear();
MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean();
factory.setTransactionManager(new ResourcelessTransactionManager());
factory.afterPropertiesSet();
jobRepository = (JobRepository) factory.getObject();
job.setJobRepository(jobRepository);
jobExecution = jobRepository.createJobExecution("job", new JobParameters());
}
@Test
public void testTwoSteps() throws Exception {
SimpleFlow<JobFlowExecutor> flow = new SimpleFlow<JobFlowExecutor>("job");
Collection<StateTransition<JobFlowExecutor>> transitions = new ArrayList<StateTransition<JobFlowExecutor>>();
transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "step2"));
transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step2"))));
flow.setStateTransitions(transitions);
job.setFlow(flow);
job.afterPropertiesSet();
StepExecution stepExecution = job.doExecute(jobExecution);
assertEquals(ExitStatus.FINISHED, stepExecution.getExitStatus());
assertEquals(2, jobExecution.getStepExecutions().size());
}
@Test
public void testFailedStep() throws Exception {
SimpleFlow<JobFlowExecutor> flow = new SimpleFlow<JobFlowExecutor>("job");
Collection<StateTransition<JobFlowExecutor>> transitions = new ArrayList<StateTransition<JobFlowExecutor>>();
transitions.add(StateTransition.createStateTransition(new StepState(new StepSupport("step1") {
@Override
public void execute(StepExecution stepExecution) throws JobInterruptedException,
UnexpectedJobExecutionException {
stepExecution.setStatus(BatchStatus.FAILED);
stepExecution.setExitStatus(ExitStatus.FAILED);
}
}), "step2"));
transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step2"))));
flow.setStateTransitions(transitions);
job.setFlow(flow);
job.afterPropertiesSet();
StepExecution stepExecution = job.doExecute(jobExecution);
assertEquals(ExitStatus.FINISHED, stepExecution.getExitStatus());
assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus());
assertEquals(2, jobExecution.getStepExecutions().size());
}
@Test
public void testStoppingStep() throws Exception {
SimpleFlow<JobFlowExecutor> flow = new SimpleFlow<JobFlowExecutor>("job");
Collection<StateTransition<JobFlowExecutor>> transitions = new ArrayList<StateTransition<JobFlowExecutor>>();
transitions.add(StateTransition.createStateTransition(new StepState(new StepSupport("step1") {
@Override
public void execute(StepExecution stepExecution) throws JobInterruptedException,
UnexpectedJobExecutionException {
stepExecution.setStatus(BatchStatus.STOPPED);
}
}), "step2"));
transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step2"))));
flow.setStateTransitions(transitions);
job.setFlow(flow);
job.afterPropertiesSet();
try {
job.doExecute(jobExecution);
fail("Expected JobInterruptedException");
}
catch (JobInterruptedException e) {
// expected
}
assertEquals(1, jobExecution.getStepExecutions().size());
}
@Test
public void testBranching() throws Exception {
SimpleFlow<JobFlowExecutor> flow = new SimpleFlow<JobFlowExecutor>("job");
Collection<StateTransition<JobFlowExecutor>> transitions = new ArrayList<StateTransition<JobFlowExecutor>>();
transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "step2"));
transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "COMPLETED", "step3"));
transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step2"))));
transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step3"))));
flow.setStateTransitions(transitions);
job.setFlow(flow);
job.afterPropertiesSet();
StepExecution stepExecution = job.doExecute(jobExecution);
assertEquals(ExitStatus.FINISHED, stepExecution.getExitStatus());
assertEquals(2, jobExecution.getStepExecutions().size());
assertEquals("step3", stepExecution.getStepName());
}
@Test
public void testBasicFlow() throws Throwable {
SimpleFlow<JobFlowExecutor> flow = new SimpleFlow<JobFlowExecutor>("job");
Step step = new StubStep("step");
flow.setStateTransitions(Collections.singleton(StateTransition.createEndStateTransition(new StepState(step),
"*")));
job.setFlow(flow);
job.execute(jobExecution);
if (!jobExecution.getAllFailureExceptions().isEmpty()) {
throw jobExecution.getAllFailureExceptions().get(0);
}
assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
}
@Test
public void testDecisionFlow() throws Throwable {
SimpleFlow<JobFlowExecutor> flow = new SimpleFlow<JobFlowExecutor>("job");
JobExecutionDecider decider = new JobExecutionDecider() {
public String decide(JobExecution jobExecution) {
return "SWITCH";
}
};
Collection<StateTransition<JobFlowExecutor>> transitions = new ArrayList<StateTransition<JobFlowExecutor>>();
transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "*", "decision"));
transitions.add(StateTransition.createStateTransition(new DecisionState("decision", decider), "*", "step2"));
transitions.add(StateTransition
.createStateTransition(new DecisionState("decision", decider), "SWITCH", "step3"));
transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step2")), "*"));
transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step3")), "*"));
flow.setStateTransitions(transitions);
job.setFlow(flow);
StepExecution stepExecution = job.doExecute(jobExecution);
if (!jobExecution.getAllFailureExceptions().isEmpty()) {
throw jobExecution.getAllFailureExceptions().get(0);
}
assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus());
assertEquals(2, jobExecution.getStepExecutions().size());
assertEquals("step3", stepExecution.getStepName());
}
@Test
public void testPauseFlow() throws Throwable {
SimpleFlow<JobFlowExecutor> flow = new SimpleFlow<JobFlowExecutor>("job");
Collection<StateTransition<JobFlowExecutor>> transitions = new ArrayList<StateTransition<JobFlowExecutor>>();
transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "*", "pause"));
transitions.add(StateTransition.createStateTransition(new PauseState("pause"), "*", "step2"));
transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step2")), "*"));
flow.setStateTransitions(transitions);
job.setFlow(flow);
job.execute(jobExecution);
if (!jobExecution.getAllFailureExceptions().isEmpty()) {
throw jobExecution.getAllFailureExceptions().get(0);
}
assertEquals(BatchStatus.PAUSED, jobExecution.getStatus());
assertEquals(1, jobExecution.getStepExecutions().size());
job.execute(jobExecution);
if (!jobExecution.getAllFailureExceptions().isEmpty()) {
throw jobExecution.getAllFailureExceptions().get(0);
}
assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
assertEquals(2, jobExecution.getStepExecutions().size());
}
/**
* @author Dave Syer
*
*/
private class StubStep extends StepSupport {
private StubStep(String name) {
super(name);
}
public void execute(StepExecution stepExecution) throws JobInterruptedException {
stepExecution.setStatus(BatchStatus.COMPLETED);
stepExecution.setExitStatus(ExitStatus.FINISHED);
jobRepository.update(stepExecution);
}
}
}

View File

@@ -30,7 +30,6 @@ import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobInstance;
@@ -195,7 +194,7 @@ public class SimpleJobLauncherTests {
public void testResumePausedInstance() throws Exception {
long id = 9;
JobExecution jobExecution = new JobExecution(null, id);
jobExecution.setStatus(BatchStatus.PAUSED);
jobExecution.pause();
expect(jobRepository.getLastJobExecution(job.getName(), jobParameters)).andReturn(jobExecution);
replay(jobRepository);