001/* 002 * Copyright 2006-2013 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.Iterator; 020 021import org.springframework.batch.core.ExitStatus; 022import org.springframework.batch.core.StepExecution; 023import org.springframework.batch.core.StepExecutionListener; 024import org.springframework.core.Ordered; 025 026/** 027 * @author Lucas Ward 028 * @author Dave Syer 029 * 030 */ 031public class CompositeStepExecutionListener implements StepExecutionListener { 032 033 private OrderedComposite<StepExecutionListener> list = new OrderedComposite<StepExecutionListener>(); 034 035 /** 036 * Public setter for the listeners. 037 * 038 * @param listeners list of {@link StepExecutionListener}s to be called when step execution events occur. 039 */ 040 public void setListeners(StepExecutionListener[] listeners) { 041 list.setItems(Arrays.asList(listeners)); 042 } 043 044 /** 045 * Register additional listener. 046 * 047 * @param stepExecutionListener instance of {@link StepExecutionListener} to be registered. 048 */ 049 public void register(StepExecutionListener stepExecutionListener) { 050 list.add(stepExecutionListener); 051 } 052 053 /** 054 * Call the registered listeners in reverse order, respecting and 055 * prioritizing those that implement {@link Ordered}. 056 * @see org.springframework.batch.core.StepExecutionListener#afterStep(StepExecution) 057 */ 058 @Override 059 public ExitStatus afterStep(StepExecution stepExecution) { 060 for (Iterator<StepExecutionListener> iterator = list.reverse(); iterator.hasNext();) { 061 StepExecutionListener listener = iterator.next(); 062 ExitStatus close = listener.afterStep(stepExecution); 063 stepExecution.setExitStatus(stepExecution.getExitStatus().and(close)); 064 } 065 return stepExecution.getExitStatus(); 066 } 067 068 /** 069 * Call the registered listeners in order, respecting and prioritizing those 070 * that implement {@link Ordered}. 071 * @see org.springframework.batch.core.StepExecutionListener#beforeStep(StepExecution) 072 */ 073 @Override 074 public void beforeStep(StepExecution stepExecution) { 075 for (Iterator<StepExecutionListener> iterator = list.iterator(); iterator.hasNext();) { 076 StepExecutionListener listener = iterator.next(); 077 listener.beforeStep(stepExecution); 078 } 079 } 080 081}