001/*
002 * Copyright 2006-2012 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.core.step;
018
019import org.apache.commons.logging.Log;
020import org.apache.commons.logging.LogFactory;
021import org.springframework.batch.core.JobInterruptedException;
022import org.springframework.batch.core.StepExecution;
023
024/**
025 * Policy that checks the current thread to see if it has been interrupted.
026 *
027 * @author Lucas Ward
028 * @author Dave Syer
029 *
030 */
031public class ThreadStepInterruptionPolicy implements StepInterruptionPolicy {
032
033        protected static final Log logger = LogFactory.getLog(ThreadStepInterruptionPolicy.class);
034
035        /**
036         * Returns if the current job lifecycle has been interrupted by checking if
037         * the current thread is interrupted.
038         */
039        @Override
040        public void checkInterrupted(StepExecution stepExecution) throws JobInterruptedException {
041
042                if (isInterrupted(stepExecution)) {
043                        throw new JobInterruptedException("Job interrupted status detected.");
044                }
045
046        }
047
048        /**
049         * @param stepExecution the current context
050         * @return true if the job has been interrupted
051         */
052        private boolean isInterrupted(StepExecution stepExecution) {
053                boolean interrupted = Thread.currentThread().isInterrupted();
054                if (interrupted) {
055                        logger.info("Step interrupted through Thread API");
056                }
057                else {
058                        interrupted = stepExecution.isTerminateOnly();
059                        if (interrupted) {
060                                logger.info("Step interrupted through StepExecution");
061                        }
062                }
063                return interrupted;
064        }
065
066}