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.integration.async;
017
018import org.springframework.batch.core.StepExecution;
019import org.springframework.batch.core.scope.context.StepContext;
020import org.springframework.batch.core.scope.context.StepSynchronizationManager;
021import org.springframework.integration.support.MessageBuilder;
022import org.springframework.messaging.Message;
023import org.springframework.messaging.MessageChannel;
024import org.springframework.messaging.support.ChannelInterceptor;
025import org.springframework.messaging.support.ChannelInterceptorAdapter;
026
027/**
028 * A {@link ChannelInterceptor} that adds the current {@link StepExecution} (if
029 * there is one) as a header to the message. Downstream asynchronous handlers
030 * can then take advantage of the step context without needing to be step
031 * scoped, which is a problem for handlers executing in another thread because
032 * the scope context is not available.
033 *
034 * @author Dave Syer
035 *
036 */
037public class StepExecutionInterceptor extends ChannelInterceptorAdapter {
038
039        /**
040         * The name of the header
041         */
042        public static final String STEP_EXECUTION = "stepExecution";
043
044        @Override
045        public Message<?> preSend(Message<?> message, MessageChannel channel) {
046                StepContext context = StepSynchronizationManager.getContext();
047                if (context == null) {
048                        return message;
049                }
050                return MessageBuilder.fromMessage(message).setHeader(STEP_EXECUTION, context.getStepExecution()).build();
051        }
052
053}