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 */
016package org.springframework.batch.core.scope.context;
017
018import java.util.Queue;
019import java.util.concurrent.LinkedBlockingQueue;
020
021import org.apache.commons.logging.Log;
022import org.apache.commons.logging.LogFactory;
023import org.springframework.batch.core.Step;
024import org.springframework.batch.core.StepExecution;
025import org.springframework.batch.repeat.RepeatCallback;
026import org.springframework.batch.repeat.RepeatContext;
027import org.springframework.batch.repeat.RepeatStatus;
028import org.springframework.util.ObjectUtils;
029
030/**
031 * Convenient base class for clients who need to do something in a repeat
032 * callback inside a {@link Step}.
033 *
034 * @author Dave Syer
035 * @author Mahmoud Ben Hassine
036 *
037 */
038public abstract class StepContextRepeatCallback implements RepeatCallback {
039
040        private final Queue<ChunkContext> attributeQueue = new LinkedBlockingQueue<ChunkContext>();
041
042        private final StepExecution stepExecution;
043
044        private final Log logger = LogFactory.getLog(StepContextRepeatCallback.class);
045
046        /**
047         * @param stepExecution instance of {@link StepExecution} to be used by StepContextRepeatCallback.
048         */
049        public StepContextRepeatCallback(StepExecution stepExecution) {
050                this.stepExecution = stepExecution;
051        }
052
053        /**
054         * Manage the {@link StepContext} lifecycle. Business processing should be
055         * delegated to {@link #doInChunkContext(RepeatContext, ChunkContext)}. This
056         * is to ensure that the current thread has a reference to the context, even
057         * if the callback is executed in a pooled thread. Handles the registration
058         * and unregistration of the step context, so clients should not duplicate
059         * those calls.
060         *
061         * @see RepeatCallback#doInIteration(RepeatContext)
062         */
063        @Override
064        public RepeatStatus doInIteration(RepeatContext context) throws Exception {
065
066                // The StepContext has to be the same for all chunks,
067                // otherwise step-scoped beans will be re-initialised for each chunk.
068                StepContext stepContext = StepSynchronizationManager.register(stepExecution);
069                if (logger.isDebugEnabled()) {
070                        logger.debug("Preparing chunk execution for StepContext: "+ObjectUtils.identityToString(stepContext));
071                }
072
073                ChunkContext chunkContext = attributeQueue.poll();
074                if (chunkContext == null) {
075                        chunkContext = new ChunkContext(stepContext);
076                }
077
078                try {
079                        if (logger.isDebugEnabled()) {
080                                logger.debug("Chunk execution starting: queue size="+attributeQueue.size());
081                        }
082                        return doInChunkContext(context, chunkContext);
083                }
084                finally {
085                        // Still some stuff to do with the data in this chunk,
086                        // pass it back.
087                        if (!chunkContext.isComplete()) {
088                                attributeQueue.add(chunkContext);
089                        }
090                        StepSynchronizationManager.close();
091                }
092        }
093
094        /**
095         * Do the work required for this chunk of the step. The {@link ChunkContext}
096         * provided is managed by the base class, so that if there is still work to
097         * do for the task in hand state can be stored here. In a multi-threaded
098         * client, the base class ensures that only one thread at a time can be
099         * working on each instance of {@link ChunkContext}. Workers should signal
100         * that they are finished with a context by removing all the attributes they
101         * have added. If a worker does not remove them another thread might see
102         * stale state.
103         *
104         * @param context the current {@link RepeatContext}
105         * @param chunkContext the chunk context in which to carry out the work
106         * @return the repeat status from the execution
107         * @throws Exception implementations can throw an exception if anything goes
108         * wrong
109         */
110        public abstract RepeatStatus doInChunkContext(RepeatContext context, ChunkContext chunkContext) throws Exception;
111
112}