CLOSED - issue BATCH-1024: FlowJob's start state should be the first state listed in the config

This commit is contained in:
dsyer
2009-01-27 16:05:25 +00:00
parent 17d7bc15c9
commit 73bfca8bb8
5 changed files with 1149 additions and 1183 deletions

View File

@@ -1,80 +1,83 @@
/*
* Copyright 2006-2008 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.configuration.xml;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
/**
* @author Dave Syer
*
*/
public class FlowParser {
/**
* @param element the top level element containing a flow definition
* @param parserContext the {@link ParserContext}
* @param flowName the name of the flow
* @return a bean definition for a {@link org.springframework.batch.core.job.flow.Flow}
*/
public AbstractBeanDefinition parse(Element element, ParserContext parserContext, String flowName) {
List<RuntimeBeanReference> stateTransitions = new ArrayList<RuntimeBeanReference>();
@SuppressWarnings("unchecked")
List<Element> stepElements = (List<Element>) DomUtils.getChildElementsByTagName(element, "step");
StepParser stepParser = new StepParser();
for (Element stepElement : stepElements) {
stateTransitions.addAll(stepParser.parse(stepElement, parserContext));
}
@SuppressWarnings("unchecked")
List<Element> decisionElements = (List<Element>) DomUtils.getChildElementsByTagName(element, "decision");
DecisionParser decisionParser = new DecisionParser();
for (Element stepElement : decisionElements) {
stateTransitions.addAll(decisionParser.parse(stepElement, parserContext));
}
@SuppressWarnings("unchecked")
List<Element> splitElements = (List<Element>) DomUtils.getChildElementsByTagName(element, "split");
SplitParser splitParser = new SplitParser();
for (Element stepElement : splitElements) {
stateTransitions.addAll(splitParser.parse(stepElement, parserContext));
}
BeanDefinitionBuilder flowBuilder =
BeanDefinitionBuilder.genericBeanDefinition("org.springframework.batch.core.job.flow.support.SimpleFlow");
flowBuilder.addConstructorArgValue(flowName );
ManagedList managedList = new ManagedList();
@SuppressWarnings( { "unchecked", "unused" })
boolean dummy = managedList.addAll(stateTransitions);
flowBuilder.addPropertyValue("stateTransitions", managedList);
AbstractBeanDefinition flowDef = flowBuilder.getBeanDefinition();
parserContext.getReaderContext().registerWithGeneratedName(flowDef);
return flowDef;
}
}
/*
* Copyright 2006-2008 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.configuration.xml;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* @author Dave Syer
*
*/
public class FlowParser {
/**
* @param element the top level element containing a flow definition
* @param parserContext the {@link ParserContext}
* @param flowName the name of the flow
* @return a bean definition for a {@link org.springframework.batch.core.job.flow.Flow}
*/
public AbstractBeanDefinition parse(Element element, ParserContext parserContext, String flowName) {
List<RuntimeBeanReference> stateTransitions = new ArrayList<RuntimeBeanReference>();
StepParser stepParser = new StepParser();
DecisionParser decisionParser = new DecisionParser();
SplitParser splitParser = new SplitParser();
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);
if (node instanceof Element) {
String nodeName = node.getLocalName();
if(nodeName.equals("step"))
{
stateTransitions.addAll(stepParser.parse((Element)node, parserContext));
}
else if(nodeName.equals("decision"))
{
stateTransitions.addAll(decisionParser.parse((Element)node, parserContext));
}
else if(nodeName.equals("split"))
{
stateTransitions.addAll(splitParser.parse((Element)node, parserContext));
}
}
}
BeanDefinitionBuilder flowBuilder = BeanDefinitionBuilder
.genericBeanDefinition("org.springframework.batch.core.job.flow.support.SimpleFlow");
flowBuilder.addConstructorArgValue(flowName);
ManagedList managedList = new ManagedList();
@SuppressWarnings( { "unchecked", "unused" })
boolean dummy = managedList.addAll(stateTransitions);
flowBuilder.addPropertyValue("stateTransitions", managedList);
AbstractBeanDefinition flowDef = flowBuilder.getBeanDefinition();
parserContext.getReaderContext().registerWithGeneratedName(flowDef);
return flowDef;
}
}

View File

@@ -1,281 +1,237 @@
/*
* 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.support;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.springframework.batch.core.JobExecutionException;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.core.job.flow.FlowExecution;
import org.springframework.batch.core.job.flow.FlowExecutionException;
import org.springframework.batch.core.job.flow.FlowExecutor;
import org.springframework.beans.factory.InitializingBean;
/**
* A {@link Flow} that branches conditionally depending on the exit status of
* the last {@link State}. The input parameters are the state transitions (in no
* particular order). The start state name can be specified explicitly (and must
* exist in the set of transitions), or computed from the existing transitions,
* if unambiguous.
*
* @author Dave Syer
*
*/
public class SimpleFlow implements Flow, InitializingBean {
private State startState;
private Map<String, SortedSet<StateTransition>> transitionMap = new HashMap<String, SortedSet<StateTransition>>();
private Map<String, State> stateMap = new HashMap<String, State>();
private String startStateName;
private Collection<StateTransition> stateTransitions = new HashSet<StateTransition>();
private final String name;
/**
* Create a flow with the given name.
*
* @param name the name of the flow
*/
public SimpleFlow(String name) {
this.name = name;
}
/**
* Get the name for this flow.
*
* @see Flow#getName()
*/
public String getName() {
return name;
}
/**
* Public setter for the start state name.
* @param startStateName the name of the start state
*/
public void setStartStateName(String startStateName) {
this.startStateName = startStateName;
}
/**
* Public setter for the stateTransitions.
* @param stateTransitions the stateTransitions to set
*/
public void setStateTransitions(Collection<StateTransition> stateTransitions) {
this.stateTransitions = stateTransitions;
}
/**
* Locate start state and pre-populate data structures needed for execution.
*
* @see InitializingBean#afterPropertiesSet()
*/
public void afterPropertiesSet() throws Exception {
initializeTransitions();
}
/**
* @see Flow#start(FlowExecutor)
*/
public FlowExecution start(FlowExecutor executor) throws FlowExecutionException {
if (startState == null) {
initializeTransitions();
}
State state = startState;
String stateName = state.getName();
return resume(stateName, executor);
}
/**
* @see Flow#resume(String, FlowExecutor)
*/
public FlowExecution resume(String stateName, FlowExecutor executor) throws FlowExecutionException {
String status = FlowExecution.UNKNOWN;
State state = stateMap.get(stateName);
// Terminate if there are no more states
while (state != null) {
stateName = state.getName();
try {
status = state.handle(executor);
}
catch (Exception e) {
executor.close(new FlowExecution(stateName, status));
throw new FlowExecutionException(String.format("Ended flow=%s at state=%s with exception", name,
stateName), e);
}
state = nextState(stateName, status);
}
FlowExecution result = new FlowExecution(stateName, status);
executor.close(result);
return result;
}
/**
* @return the next {@link Step} (or null if this is the end)
* @throws JobExecutionException
*/
private State nextState(String stateName, String status) throws FlowExecutionException {
// Special status value indicating that a state wishes to pause
// execution
if (status.equals(FlowExecution.PAUSED)) {
return null;
}
Set<StateTransition> set = transitionMap.get(stateName);
if (set == null) {
throw new FlowExecutionException(String.format("No transitions found in flow=%s for state=%s", getName(),
stateName));
}
String next = null;
for (StateTransition stateTransition : set) {
if (stateTransition.matches(status)) {
if (stateTransition.isEnd()) {
// End of job
return null;
}
next = stateTransition.getNext();
break;
}
}
if (next == null) {
throw new FlowExecutionException(String.format(
"Next state not found in flow=%s for state=%s with exit status=%s", getName(), stateName, status));
}
if (!stateMap.containsKey(next)) {
throw new FlowExecutionException(String.format("Next state not specified in flow=%s for next=%s",
getName(), next));
}
return stateMap.get(next);
}
/**
* Analyse the transitions provided and generate all the information needed
* to execute the flow.
*/
private void initializeTransitions() {
startState = null;
transitionMap.clear();
stateMap.clear();
boolean hasEndStep = false;
for (StateTransition stateTransition : stateTransitions) {
State state = stateTransition.getState();
stateMap.put(state.getName(), state);
}
for (StateTransition stateTransition : stateTransitions) {
State state = stateTransition.getState();
if (!stateTransition.isEnd()) {
String next = stateTransition.getNext();
if (!stateMap.containsKey(next)) {
throw new IllegalArgumentException("Missing state for [" + stateTransition + "]");
}
}
else {
hasEndStep = true;
}
String name = state.getName();
SortedSet<StateTransition> set = transitionMap.get(name);
if (set == null) {
set = new TreeSet<StateTransition>();
transitionMap.put(name, set);
}
set.add(stateTransition);
}
if (!hasEndStep) {
throw new IllegalArgumentException(
"No end state was found. You must specify at least one transition with no next state.");
}
if (startStateName != null) {
startState = stateMap.get(startStateName);
if (startState == null) {
throw new IllegalArgumentException(
"Start state does not exist (if you specify a startStateName make sure "
+ "a state with that name is in one of the transitions): [" + startStateName + "]");
}
}
else {
// Try and locate a transition with no incoming links
Set<String> nextStateNames = new HashSet<String>();
for (StateTransition stateTransition : stateTransitions) {
nextStateNames.add(stateTransition.getNext());
}
for (StateTransition stateTransition : stateTransitions) {
State state = stateTransition.getState();
if (!nextStateNames.contains(state.getName())) {
if (startState != null && !startState.getName().equals(state.getName())) {
throw new IllegalArgumentException(String.format(
"Multiple possible start states found: [%s, %s]. "
+ "Please specify one explicitly with the startStateName property.", startState
.getName(), state.getName()));
}
startState = state;
}
}
if (startState == null) {
throw new IllegalArgumentException(
"No start state could be located (no transition without incoming links)");
}
}
}
}
/*
* 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.support;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.springframework.batch.core.JobExecutionException;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.core.job.flow.FlowExecution;
import org.springframework.batch.core.job.flow.FlowExecutionException;
import org.springframework.batch.core.job.flow.FlowExecutor;
import org.springframework.beans.factory.InitializingBean;
/**
* A {@link Flow} that branches conditionally depending on the exit status of
* the last {@link State}. The input parameters are the state transitions (in no
* particular order). The start state name can be specified explicitly (and must
* exist in the set of transitions), or computed from the existing transitions,
* if unambiguous.
*
* @author Dave Syer
*
*/
public class SimpleFlow implements Flow, InitializingBean {
private State startState;
private Map<String, SortedSet<StateTransition>> transitionMap = new HashMap<String, SortedSet<StateTransition>>();
private Map<String, State> stateMap = new HashMap<String, State>();
private List<StateTransition> stateTransitions = new ArrayList<StateTransition>();
private final String name;
/**
* Create a flow with the given name.
*
* @param name the name of the flow
*/
public SimpleFlow(String name) {
this.name = name;
}
/**
* Get the name for this flow.
*
* @see Flow#getName()
*/
public String getName() {
return name;
}
/**
* Public setter for the stateTransitions.
*
* @param stateTransitions the stateTransitions to set
*/
public void setStateTransitions(List<StateTransition> stateTransitions) {
this.stateTransitions = stateTransitions;
}
/**
* Locate start state and pre-populate data structures needed for execution.
*
* @see InitializingBean#afterPropertiesSet()
*/
public void afterPropertiesSet() throws Exception {
initializeTransitions();
}
/**
* @see Flow#start(FlowExecutor)
*/
public FlowExecution start(FlowExecutor executor) throws FlowExecutionException {
if (startState == null) {
initializeTransitions();
}
State state = startState;
String stateName = state.getName();
return resume(stateName, executor);
}
/**
* @see Flow#resume(String, FlowExecutor)
*/
public FlowExecution resume(String stateName, FlowExecutor executor) throws FlowExecutionException {
String status = FlowExecution.UNKNOWN;
State state = stateMap.get(stateName);
// Terminate if there are no more states
while (state != null) {
stateName = state.getName();
try {
status = state.handle(executor);
}
catch (Exception e) {
executor.close(new FlowExecution(stateName, status));
throw new FlowExecutionException(String.format("Ended flow=%s at state=%s with exception", name,
stateName), e);
}
state = nextState(stateName, status);
}
FlowExecution result = new FlowExecution(stateName, status);
executor.close(result);
return result;
}
/**
* @return the next {@link Step} (or null if this is the end)
* @throws JobExecutionException
*/
private State nextState(String stateName, String status) throws FlowExecutionException {
// Special status value indicating that a state wishes to pause
// execution
if (status.equals(FlowExecution.PAUSED)) {
return null;
}
Set<StateTransition> set = transitionMap.get(stateName);
if (set == null) {
throw new FlowExecutionException(String.format("No transitions found in flow=%s for state=%s", getName(),
stateName));
}
String next = null;
for (StateTransition stateTransition : set) {
if (stateTransition.matches(status)) {
if (stateTransition.isEnd()) {
// End of job
return null;
}
next = stateTransition.getNext();
break;
}
}
if (next == null) {
throw new FlowExecutionException(String.format(
"Next state not found in flow=%s for state=%s with exit status=%s", getName(), stateName, status));
}
if (!stateMap.containsKey(next)) {
throw new FlowExecutionException(String.format("Next state not specified in flow=%s for next=%s",
getName(), next));
}
return stateMap.get(next);
}
/**
* Analyse the transitions provided and generate all the information needed
* to execute the flow.
*/
private void initializeTransitions() {
startState = null;
transitionMap.clear();
stateMap.clear();
boolean hasEndStep = false;
if (stateTransitions.isEmpty()) {
throw new IllegalArgumentException("No start state was found. You must specify at least one step in a job.");
}
for (StateTransition stateTransition : stateTransitions) {
State state = stateTransition.getState();
stateMap.put(state.getName(), state);
}
for (StateTransition stateTransition : stateTransitions) {
State state = stateTransition.getState();
if (!stateTransition.isEnd()) {
String next = stateTransition.getNext();
if (!stateMap.containsKey(next)) {
throw new IllegalArgumentException("Missing state for [" + stateTransition + "]");
}
}
else {
hasEndStep = true;
}
String name = state.getName();
SortedSet<StateTransition> set = transitionMap.get(name);
if (set == null) {
set = new TreeSet<StateTransition>();
transitionMap.put(name, set);
}
set.add(stateTransition);
}
if (!hasEndStep) {
throw new IllegalArgumentException(
"No end state was found. You must specify at least one transition with no next state.");
}
startState = stateTransitions.get(0).getState();
}
}

View File

@@ -20,8 +20,8 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
@@ -72,7 +72,7 @@ public class FlowJobTests {
@Test
public void testTwoSteps() throws Exception {
SimpleFlow flow = new SimpleFlow("job");
Collection<StateTransition> transitions = new ArrayList<StateTransition>();
List<StateTransition> transitions = new ArrayList<StateTransition>();
transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "step2"));
transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step2"))));
flow.setStateTransitions(transitions);
@@ -86,7 +86,7 @@ public class FlowJobTests {
@Test
public void testFailedStep() throws Exception {
SimpleFlow flow = new SimpleFlow("job");
Collection<StateTransition> transitions = new ArrayList<StateTransition>();
List<StateTransition> transitions = new ArrayList<StateTransition>();
transitions.add(StateTransition.createStateTransition(new StepState(new StepSupport("step1") {
@Override
public void execute(StepExecution stepExecution) throws JobInterruptedException,
@@ -108,7 +108,7 @@ public class FlowJobTests {
@Test
public void testFailedStepRestarted() throws Exception {
SimpleFlow flow = new SimpleFlow("job");
Collection<StateTransition> transitions = new ArrayList<StateTransition>();
List<StateTransition> transitions = new ArrayList<StateTransition>();
transitions.add(StateTransition.createStateTransition(new StepState(new StepSupport("step1") {
@Override
public void execute(StepExecution stepExecution) throws JobInterruptedException,
@@ -150,7 +150,7 @@ public class FlowJobTests {
@Test
public void testStoppingStep() throws Exception {
SimpleFlow flow = new SimpleFlow("job");
Collection<StateTransition> transitions = new ArrayList<StateTransition>();
List<StateTransition> transitions = new ArrayList<StateTransition>();
transitions.add(StateTransition.createStateTransition(new StepState(new StepSupport("step1") {
@Override
public void execute(StepExecution stepExecution) throws JobInterruptedException,
@@ -175,7 +175,7 @@ public class FlowJobTests {
@Test
public void testEndStateStopped() throws Exception {
SimpleFlow flow = new SimpleFlow("job");
Collection<StateTransition> transitions = new ArrayList<StateTransition>();
List<StateTransition> transitions = new ArrayList<StateTransition>();
transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "end"));
transitions.add(StateTransition.createStateTransition(new EndState(BatchStatus.STOPPED, "end"), "step2"));
transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step2"))));
@@ -194,7 +194,7 @@ public class FlowJobTests {
public void testEndStateFailed() throws Exception {
SimpleFlow flow = new SimpleFlow("job");
Collection<StateTransition> transitions = new ArrayList<StateTransition>();
List<StateTransition> transitions = new ArrayList<StateTransition>();
transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "end"));
transitions.add(StateTransition.createStateTransition(new EndState(BatchStatus.FAILED, "end"), "step2"));
transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step2"))));
@@ -209,7 +209,7 @@ public class FlowJobTests {
@Test
public void testEndStateStoppedWithRestart() throws Exception {
SimpleFlow flow = new SimpleFlow("job");
Collection<StateTransition> transitions = new ArrayList<StateTransition>();
List<StateTransition> transitions = new ArrayList<StateTransition>();
transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "end"));
transitions.add(StateTransition.createStateTransition(new EndState(BatchStatus.STOPPED, "end"), "step2"));
transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step2"))));
@@ -232,7 +232,7 @@ public class FlowJobTests {
@Test
public void testBranching() throws Exception {
SimpleFlow flow = new SimpleFlow("job");
Collection<StateTransition> transitions = new ArrayList<StateTransition>();
List<StateTransition> transitions = new ArrayList<StateTransition>();
transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "step2"));
transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "COMPLETED",
"step3"));
@@ -251,8 +251,8 @@ public class FlowJobTests {
public void testBasicFlow() throws Throwable {
SimpleFlow flow = new SimpleFlow("job");
Step step = new StubStep("step");
flow.setStateTransitions(Collections.singleton(StateTransition.createEndStateTransition(new StepState(step),
"*")));
flow.setStateTransitions(Collections.singletonList(StateTransition.createEndStateTransition(
new StepState(step), "*")));
job.setFlow(flow);
job.execute(jobExecution);
if (!jobExecution.getAllFailureExceptions().isEmpty()) {
@@ -272,7 +272,7 @@ public class FlowJobTests {
}
};
Collection<StateTransition> transitions = new ArrayList<StateTransition>();
List<StateTransition> transitions = new ArrayList<StateTransition>();
transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "*", "decision"));
transitions.add(StateTransition.createStateTransition(new DecisionState(decider, "decision"), "*", "step2"));
transitions.add(StateTransition

View File

@@ -1,243 +1,241 @@
/*
* 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.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.springframework.batch.core.job.flow.FlowExecution;
import org.springframework.batch.core.job.flow.FlowExecutionException;
import org.springframework.batch.core.job.flow.FlowExecutor;
import org.springframework.batch.core.job.flow.support.SimpleFlow;
import org.springframework.batch.core.job.flow.support.StateTransition;
/**
* @author Dave Syer
*
*/
public class SimpleFlowTests {
private SimpleFlow flow = new SimpleFlow("job");
private FlowExecutor executor = new JobFlowExecutorSupport();
@Test(expected = IllegalArgumentException.class)
public void testEmptySteps() throws Exception {
flow.setStateTransitions(Collections.<StateTransition> emptySet());
flow.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void testNoNextStepSpecified() throws Exception {
flow.setStateTransitions(Collections.singleton(StateTransition.createStateTransition(new StateSupport(
"step"), "foo")));
flow.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void testNoStartStep() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StateSupport("step"),
FlowExecution.FAILED, "step"), StateTransition
.createEndStateTransition(new StateSupport("step"))));
flow.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void testNoEndStep() throws Exception {
flow.setStateTransitions(Collections.singleton(StateTransition.createStateTransition(new StateSupport(
"step"), FlowExecution.FAILED, "step")));
flow.setStartStateName("step");
flow.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void testMultipleStartSteps() throws Exception {
flow.setStateTransitions(collect(StateTransition.createEndStateTransition(new StubState("step1")),
StateTransition.createEndStateTransition(new StubState("step2"))));
flow.afterPropertiesSet();
}
@Test
public void testNoMatchForNextStep() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1"), "FOO", "step2"),
StateTransition.createEndStateTransition(new StubState("step2"))));
flow.afterPropertiesSet();
try {
flow.start(executor);
fail("Expected JobExecutionException");
}
catch (FlowExecutionException e) {
// expected
String message = e.getMessage();
assertTrue("Wrong message: " + message, message.toLowerCase().contains("next state not found"));
}
}
@Test
public void testOneStep() throws Exception {
flow.setStateTransitions(Collections
.singleton(StateTransition.createEndStateTransition(new StubState("step1"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.start(executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step1", execution.getName());
}
@Test
public void testOneStepWithListenerCallsClose() throws Exception {
flow.setStateTransitions(Collections
.singleton(StateTransition.createEndStateTransition(new StubState("step1"))));
flow.afterPropertiesSet();
final List<FlowExecution> list = new ArrayList<FlowExecution>();
executor = new JobFlowExecutorSupport() {
@Override
public void close(FlowExecution result) {
list.add(result);
}
};
FlowExecution execution = flow.start(executor);
assertEquals(1, list.size());
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step1", execution.getName());
}
@Test
public void testExplicitStartStep() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step"),
FlowExecution.FAILED, "step"), StateTransition.createEndStateTransition(new StubState("step"))));
flow.setStartStateName("step");
flow.afterPropertiesSet();
FlowExecution execution = flow.start(executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step", execution.getName());
}
@Test
public void testTwoSteps() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1"), "step2"),
StateTransition.createEndStateTransition(new StubState("step2"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.start(executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step2", execution.getName());
}
@Test
public void testResume() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1"), "step2"),
StateTransition.createEndStateTransition(new StubState("step2"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.resume("step2", executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step2", execution.getName());
}
@Test
public void testFailedStep() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1") {
@Override
public String handle(FlowExecutor executor) {
return FlowExecution.FAILED;
}
}, "step2"), StateTransition.createEndStateTransition(new StubState("step2"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.start(executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step2", execution.getName());
}
@Test
public void testBranching() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1"), "step2"),
StateTransition.createStateTransition(new StubState("step1"), FlowExecution.COMPLETED, "step3"),
StateTransition.createEndStateTransition(new StubState("step2")), StateTransition
.createEndStateTransition(new StubState("step3"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.start(executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step3", execution.getName());
}
@Test
public void testPause() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1"), "step2"),
StateTransition.createStateTransition(new StubState("step2") {
private boolean paused = false;
@Override
public String handle(FlowExecutor executor) throws Exception {
if (!paused) {
paused = true;
return FlowExecution.PAUSED;
}
paused = false;
return FlowExecution.COMPLETED;
}
}, "step3"), StateTransition.createEndStateTransition(new StubState("step3"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.start(executor);
assertEquals(FlowExecution.PAUSED, execution.getStatus());
assertEquals("step2", execution.getName());
execution = flow.resume(execution.getName(), executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step3", execution.getName());
}
private Collection<StateTransition> collect(StateTransition s1, StateTransition s2) {
Collection<StateTransition> list = new ArrayList<StateTransition>();
list.add(s1);
list.add(s2);
return list;
}
private Collection<StateTransition> collect(StateTransition s1, StateTransition s2,
StateTransition s3) {
Collection<StateTransition> list = collect(s1, s2);
list.add(s3);
return list;
}
private Collection<StateTransition> collect(StateTransition s1, StateTransition s2,
StateTransition s3, StateTransition s4) {
Collection<StateTransition> list = collect(s1, s2, s3);
list.add(s4);
return list;
}
/**
* @author Dave Syer
*
*/
private static class StubState extends StateSupport {
/**
* @param string
*/
public StubState(String string) {
super(string);
}
}
}
/*
* 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.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.springframework.batch.core.job.flow.FlowExecution;
import org.springframework.batch.core.job.flow.FlowExecutionException;
import org.springframework.batch.core.job.flow.FlowExecutor;
/**
* @author Dave Syer
*
*/
public class SimpleFlowTests {
private SimpleFlow flow = new SimpleFlow("job");
private FlowExecutor executor = new JobFlowExecutorSupport();
@Test(expected = IllegalArgumentException.class)
public void testEmptySteps() throws Exception {
flow.setStateTransitions(Collections.<StateTransition> emptyList());
flow.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void testNoNextStepSpecified() throws Exception {
flow.setStateTransitions(Collections.singletonList(StateTransition.createStateTransition(new StateSupport(
"step"), "foo")));
flow.afterPropertiesSet();
}
@Test
public void testStepLoop() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StateSupport("step"),
FlowExecution.FAILED, "step"), StateTransition.createEndStateTransition(new StateSupport("step"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.start(executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step", execution.getName());
}
@Test(expected = IllegalArgumentException.class)
public void testNoEndStep() throws Exception {
flow.setStateTransitions(Collections.singletonList(StateTransition.createStateTransition(new StateSupport(
"step"), FlowExecution.FAILED, "step")));
flow.afterPropertiesSet();
}
@Test
public void testUnconnectedSteps() throws Exception {
flow.setStateTransitions(collect(StateTransition.createEndStateTransition(new StubState("step1")),
StateTransition.createEndStateTransition(new StubState("step2"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.start(executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step1", execution.getName());
}
@Test
public void testNoMatchForNextStep() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1"), "FOO", "step2"),
StateTransition.createEndStateTransition(new StubState("step2"))));
flow.afterPropertiesSet();
try {
flow.start(executor);
fail("Expected JobExecutionException");
}
catch (FlowExecutionException e) {
// expected
String message = e.getMessage();
assertTrue("Wrong message: " + message, message.toLowerCase().contains("next state not found"));
}
}
@Test
public void testOneStep() throws Exception {
flow.setStateTransitions(Collections.singletonList(StateTransition.createEndStateTransition(new StubState(
"step1"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.start(executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step1", execution.getName());
}
@Test
public void testOneStepWithListenerCallsClose() throws Exception {
flow.setStateTransitions(Collections.singletonList(StateTransition.createEndStateTransition(new StubState(
"step1"))));
flow.afterPropertiesSet();
final List<FlowExecution> list = new ArrayList<FlowExecution>();
executor = new JobFlowExecutorSupport() {
@Override
public void close(FlowExecution result) {
list.add(result);
}
};
FlowExecution execution = flow.start(executor);
assertEquals(1, list.size());
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step1", execution.getName());
}
@Test
public void testExplicitStartStep() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step"),
FlowExecution.FAILED, "step"), StateTransition.createEndStateTransition(new StubState("step"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.start(executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step", execution.getName());
}
@Test
public void testTwoSteps() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1"), "step2"),
StateTransition.createEndStateTransition(new StubState("step2"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.start(executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step2", execution.getName());
}
@Test
public void testResume() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1"), "step2"),
StateTransition.createEndStateTransition(new StubState("step2"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.resume("step2", executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step2", execution.getName());
}
@Test
public void testFailedStep() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1") {
@Override
public String handle(FlowExecutor executor) {
return FlowExecution.FAILED;
}
}, "step2"), StateTransition.createEndStateTransition(new StubState("step2"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.start(executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step2", execution.getName());
}
@Test
public void testBranching() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1"), "step2"),
StateTransition.createStateTransition(new StubState("step1"), FlowExecution.COMPLETED, "step3"),
StateTransition.createEndStateTransition(new StubState("step2")), StateTransition
.createEndStateTransition(new StubState("step3"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.start(executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step3", execution.getName());
}
@Test
public void testPause() throws Exception {
flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1"), "step2"),
StateTransition.createStateTransition(new StubState("step2") {
private boolean paused = false;
@Override
public String handle(FlowExecutor executor) throws Exception {
if (!paused) {
paused = true;
return FlowExecution.PAUSED;
}
paused = false;
return FlowExecution.COMPLETED;
}
}, "step3"), StateTransition.createEndStateTransition(new StubState("step3"))));
flow.afterPropertiesSet();
FlowExecution execution = flow.start(executor);
assertEquals(FlowExecution.PAUSED, execution.getStatus());
assertEquals("step2", execution.getName());
execution = flow.resume(execution.getName(), executor);
assertEquals(FlowExecution.COMPLETED, execution.getStatus());
assertEquals("step3", execution.getName());
}
private List<StateTransition> collect(StateTransition s1, StateTransition s2) {
List<StateTransition> list = new ArrayList<StateTransition>();
list.add(s1);
list.add(s2);
return list;
}
private List<StateTransition> collect(StateTransition s1, StateTransition s2, StateTransition s3) {
List<StateTransition> list = collect(s1, s2);
list.add(s3);
return list;
}
private List<StateTransition> collect(StateTransition s1, StateTransition s2, StateTransition s3, StateTransition s4) {
List<StateTransition> list = collect(s1, s2, s3);
list.add(s4);
return list;
}
/**
* @author Dave Syer
*
*/
private static class StubState extends StateSupport {
/**
* @param string
*/
public StubState(String string) {
super(string);
}
}
}