001/* 002 * Copyright 2006-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 */ 016 017package org.springframework.batch.test; 018 019import java.util.ArrayList; 020import java.util.List; 021 022import org.springframework.batch.core.JobExecution; 023import org.springframework.batch.core.StepExecution; 024import org.springframework.batch.item.ExecutionContext; 025import org.springframework.lang.Nullable; 026 027/** 028 * Convenience class for accessing {@link ExecutionContext} values from job and 029 * step executions. 030 * 031 * @author Dave Syer 032 * @author Mahmoud Ben Hassine 033 * @since 2.1.4 034 * 035 */ 036public class ExecutionContextTestUtils { 037 038 @SuppressWarnings("unchecked") 039 @Nullable 040 public static <T> T getValueFromJob(JobExecution jobExecution, String key) { 041 return (T) jobExecution.getExecutionContext().get(key); 042 } 043 044 @Nullable 045 public static <T> T getValueFromStepInJob(JobExecution jobExecution, String stepName, String key) { 046 StepExecution stepExecution = null; 047 List<String> stepNames = new ArrayList<String>(); 048 for (StepExecution candidate : jobExecution.getStepExecutions()) { 049 String name = candidate.getStepName(); 050 stepNames.add(name); 051 if (name.equals(stepName)) { 052 stepExecution = candidate; 053 } 054 } 055 if (stepExecution == null) { 056 throw new IllegalArgumentException("No such step in this job execution: " + stepName + " not in " 057 + stepNames); 058 } 059 @SuppressWarnings("unchecked") 060 T result = (T) stepExecution.getExecutionContext().get(key); 061 return result; 062 } 063 064 @SuppressWarnings("unchecked") 065 @Nullable 066 public static <T> T getValueFromStep(StepExecution stepExecution, String key) { 067 return (T) stepExecution.getExecutionContext().get(key); 068 } 069 070}