View Javadoc

1   /*
2    * Copyright 2006-2009 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.batch.test;
18  
19  import java.util.ArrayList;
20  import java.util.List;
21  
22  import org.springframework.batch.core.JobExecution;
23  import org.springframework.batch.core.StepExecution;
24  import org.springframework.batch.item.ExecutionContext;
25  
26  /**
27   * Convenience class for accessing {@link ExecutionContext} values from job and
28   * step executions.
29   * 
30   * @author Dave Syer
31   * @since 2.1.4
32   * 
33   */
34  public class ExecutionContextTestUtils {
35  
36  	@SuppressWarnings("unchecked")
37  	public static <T> T getValueFromJob(JobExecution jobExecution, String key) {
38  		return (T) jobExecution.getExecutionContext().get(key);
39  	}
40  
41  	public static <T> T getValueFromStepInJob(JobExecution jobExecution, String stepName, String key) {
42  		StepExecution stepExecution = null;
43  		List<String> stepNames = new ArrayList<String>();
44  		for (StepExecution candidate : jobExecution.getStepExecutions()) {
45  			String name = candidate.getStepName();
46  			stepNames.add(name);
47  			if (name.equals(stepName)) {
48  				stepExecution = candidate;
49  			}
50  		}
51  		if (stepExecution == null) {
52  			throw new IllegalArgumentException("No such step in this job execution: " + stepName + " not in "
53  					+ stepNames);
54  		}
55  		@SuppressWarnings("unchecked")
56  		T result = (T) stepExecution.getExecutionContext().get(key);
57  		return result;
58  	}
59  
60  	@SuppressWarnings("unchecked")
61  	public static <T> T getValueFromStep(StepExecution stepExecution, String key) {
62  		return (T) stepExecution.getExecutionContext().get(key);
63  	}
64  
65  }