| 1 | /* |
| 2 | * Copyright 2006-2007 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 | package org.springframework.batch.core.listener; |
| 17 | |
| 18 | import java.util.Arrays; |
| 19 | import java.util.Collection; |
| 20 | |
| 21 | import org.springframework.batch.core.JobParameters; |
| 22 | import org.springframework.batch.core.Step; |
| 23 | import org.springframework.batch.core.StepExecution; |
| 24 | import org.springframework.batch.item.ExecutionContext; |
| 25 | |
| 26 | /** |
| 27 | * This class can be used to automatically copy items from the |
| 28 | * {@link JobParameters} to the {@link Step} {@link ExecutionContext}. A list of |
| 29 | * keys should be provided that correspond to the items in the {@link Step} |
| 30 | * {@link ExecutionContext} that should be copied. |
| 31 | * |
| 32 | * @author Dave Syer |
| 33 | * @since 2.0 |
| 34 | */ |
| 35 | public class JobParameterExecutionContextCopyListener extends StepExecutionListenerSupport { |
| 36 | |
| 37 | private Collection<String> keys = null; |
| 38 | |
| 39 | /** |
| 40 | * @param keys A list of keys corresponding to items in the |
| 41 | * {@link JobParameters} that should be copied. |
| 42 | */ |
| 43 | public void setKeys(String[] keys) { |
| 44 | this.keys = Arrays.asList(keys); |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * Copy attributes from the {@link JobParameters} to the {@link Step} |
| 49 | * {@link ExecutionContext}, if not already present. The the key is already |
| 50 | * present we assume that a restart is in operation and the previous value |
| 51 | * is needed. If the provided keys are empty defaults to copy all keys in |
| 52 | * the {@link JobParameters}. |
| 53 | */ |
| 54 | @Override |
| 55 | public void beforeStep(StepExecution stepExecution) { |
| 56 | ExecutionContext stepContext = stepExecution.getExecutionContext(); |
| 57 | JobParameters jobParameters = stepExecution.getJobParameters(); |
| 58 | Collection<String> keys = this.keys; |
| 59 | if (keys == null) { |
| 60 | keys = jobParameters.getParameters().keySet(); |
| 61 | } |
| 62 | for (String key : keys) { |
| 63 | if (!stepContext.containsKey(key)) { |
| 64 | stepContext.put(key, jobParameters.getParameters().get(key).getValue()); |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | } |