001/*
002 * Copyright 2006-2007 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.listener;
017
018import java.util.Arrays;
019import java.util.Collection;
020
021import org.springframework.batch.core.JobParameters;
022import org.springframework.batch.core.Step;
023import org.springframework.batch.core.StepExecution;
024import org.springframework.batch.item.ExecutionContext;
025
026/**
027 * This class can be used to automatically copy items from the
028 * {@link JobParameters} to the {@link Step} {@link ExecutionContext}. A list of
029 * keys should be provided that correspond to the items in the {@link Step}
030 * {@link ExecutionContext} that should be copied.
031 * 
032 * @author Dave Syer
033 * @since 2.0
034 */
035public class JobParameterExecutionContextCopyListener extends StepExecutionListenerSupport {
036
037        private Collection<String> keys = null;
038
039        /**
040         * @param keys A list of keys corresponding to items in the
041         * {@link JobParameters} that should be copied.
042         */
043        public void setKeys(String[] keys) {
044                this.keys = Arrays.asList(keys);
045        }
046
047        /**
048         * Copy attributes from the {@link JobParameters} to the {@link Step}
049         * {@link ExecutionContext}, if not already present. The the key is already
050         * present we assume that a restart is in operation and the previous value
051         * is needed. If the provided keys are empty defaults to copy all keys in
052         * the {@link JobParameters}.
053         */
054        @Override
055        public void beforeStep(StepExecution stepExecution) {
056                ExecutionContext stepContext = stepExecution.getExecutionContext();
057                JobParameters jobParameters = stepExecution.getJobParameters();
058                Collection<String> keys = this.keys;
059                if (keys == null) {
060                        keys = jobParameters.getParameters().keySet();
061                }
062                for (String key : keys) {
063                        if (!stepContext.containsKey(key)) {
064                                stepContext.put(key, jobParameters.getParameters().get(key).getValue());
065                        }
066                }
067        }
068}