001/*
002 * Copyright 2013-2018 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.springframework.batch.core.jsr.job.flow.support;
017
018import java.util.Set;
019
020import org.springframework.batch.core.Step;
021import org.springframework.batch.core.StepExecution;
022import org.springframework.batch.core.configuration.xml.SimpleFlowFactoryBean.DelegateState;
023import org.springframework.batch.core.job.flow.Flow;
024import org.springframework.batch.core.job.flow.FlowExecutionException;
025import org.springframework.batch.core.job.flow.FlowExecutionStatus;
026import org.springframework.batch.core.job.flow.State;
027import org.springframework.batch.core.job.flow.support.SimpleFlow;
028import org.springframework.batch.core.job.flow.support.StateTransition;
029import org.springframework.batch.core.jsr.job.flow.support.state.JsrStepState;
030import org.springframework.batch.item.ExecutionContext;
031import org.springframework.lang.Nullable;
032import org.springframework.util.StringUtils;
033
034/**
035 * Implements JSR-352 specific logic around the execution of a flow.  Specifically, this
036 * {@link Flow} implementation will attempt to find the next state based on the provided
037 * exit status.  If none is found (the exit status isn't mapped), it will attempt to
038 * resolve the next state basing it on the last step's batch status.  Only if both
039 * attempts fail, the flow will fail due to the inability to find the next state.
040 *
041 * @author Michael Minella
042 * @author Mahmoud Ben Hassine
043 * @since 3.0
044 */
045public class JsrFlow extends SimpleFlow {
046
047        private JsrStepState currentStep;
048
049        /**
050         * @param name name of the flow
051         */
052        public JsrFlow(String name) {
053                super(name);
054        }
055
056        @Nullable
057        public String getMostRecentStepName() {
058                if(currentStep != null) {
059                        return currentStep.getStep().getName();
060                } else {
061                        return null;
062                }
063        }
064
065        @Override
066        protected boolean isFlowContinued(State state, FlowExecutionStatus status, StepExecution stepExecution) {
067                if(state instanceof DelegateState) {
068                        state = ((DelegateState) state).getState();
069                }
070
071                if(state instanceof JsrStepState) {
072                        currentStep = (JsrStepState) state;
073                }
074
075                return super.isFlowContinued(state, status, stepExecution);
076        }
077
078        @Override
079        protected State nextState(String stateName, FlowExecutionStatus status, StepExecution stepExecution) throws FlowExecutionException {
080                State nextState = findState(stateName, status, stepExecution);
081
082                if(stepExecution != null) {
083                        ExecutionContext executionContext = stepExecution.getJobExecution().getExecutionContext();
084                        if(executionContext.containsKey("batch.stoppedStep")) {
085                                String stepName = executionContext.getString("batch.stoppedStep");
086
087                                if(stateName.endsWith(stepName)) {
088                                        if(nextState != null && executionContext.containsKey("batch.restartStep") && StringUtils.hasText(executionContext.getString("batch.restartStep"))) {
089                                                nextState = findState(stateName, new FlowExecutionStatus(status.getName() + ".RESTART"), stepExecution);
090                                        }
091                                }
092                        }
093                }
094
095                return nextState;
096        }
097
098        /**
099         * @return the next {@link Step} (or null if this is the end)
100         * @throws FlowExecutionException
101         */
102        private State findState(String stateName, FlowExecutionStatus status, StepExecution stepExecution) throws FlowExecutionException {
103                Set<StateTransition> set = getTransitionMap().get(stateName);
104
105                if (set == null) {
106                        throw new FlowExecutionException(String.format("No transitions found in flow=%s for state=%s", getName(),
107                                        stateName));
108                }
109
110                String next = null;
111                String exitCode = status.getName();
112                for (StateTransition stateTransition : set) {
113                        if (stateTransition.matches(exitCode) || (exitCode.equals("PENDING") && stateTransition.matches("STOPPED"))) {
114                                if (stateTransition.isEnd()) {
115                                        // End of job
116                                        return null;
117                                }
118                                next = stateTransition.getNext();
119                                break;
120                        }
121                }
122
123                if (next == null) {
124                        if(stepExecution != null) {
125                                exitCode = stepExecution.getStatus().toString();
126
127                                for (StateTransition stateTransition : set) {
128                                        if (stateTransition.matches(exitCode) || (exitCode.equals("PENDING") && stateTransition.matches("STOPPED"))) {
129                                                if (stateTransition.isEnd()) {
130                                                        // End of job
131                                                        return null;
132                                                }
133                                                next = stateTransition.getNext();
134                                                break;
135                                        }
136                                }
137                        }
138
139                        if(next == null) {
140                                throw new FlowExecutionException(String.format(
141                                                "Next state not found in flow=%s for state=%s with exit status=%s", getName(), stateName, status.getName()));
142                        }
143                }
144
145                if (!getStateMap().containsKey(next)) {
146                        throw new FlowExecutionException(String.format("Next state not specified in flow=%s for next=%s",
147                                        getName(), next));
148                }
149
150                return getStateMap().get(next);
151        }
152}