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 */
016
017package org.springframework.batch.sample.support;
018
019import org.springframework.batch.core.UnexpectedJobExecutionException;
020import org.springframework.batch.item.ItemReader;
021
022/**
023 * Hacked {@link ItemReader} that throws exception on a given record number
024 * (useful for testing restart).
025 * 
026 * @author Robert Kasanicky
027 * @author Lucas Ward
028 * 
029 */
030public class ExceptionThrowingItemReaderProxy<T> implements ItemReader<T> {
031
032        private int counter = 0;
033
034        private int throwExceptionOnRecordNumber = 4;
035
036        private ItemReader<T> delegate;
037
038        /**
039         * @param throwExceptionOnRecordNumber The number of record on which
040         * exception should be thrown
041         */
042        public void setThrowExceptionOnRecordNumber(int throwExceptionOnRecordNumber) {
043                this.throwExceptionOnRecordNumber = throwExceptionOnRecordNumber;
044        }
045
046        @Override
047        public T read() throws Exception {
048
049                counter++;
050                if (counter == throwExceptionOnRecordNumber) {
051                        throw new UnexpectedJobExecutionException("Planned failure on count=" + counter);
052                }
053
054                return delegate.read();
055        }
056
057        public void setDelegate(ItemReader<T> delegate) {
058                this.delegate = delegate;
059        }
060
061}