001/*
002 * Copyright 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.jsr.item;
017
018import java.io.Serializable;
019
020import javax.batch.api.chunk.ItemReader;
021
022import org.springframework.util.Assert;
023import org.springframework.util.ClassUtils;
024
025/**
026 * Adapter that wraps an {@link ItemReader} for use by Spring Batch.  All calls are delegated as appropriate
027 * to the corresponding method on the delegate.
028 *
029 * @author Michael Minella
030 * @since 3.0
031 */
032public class ItemReaderAdapter<T> extends CheckpointSupport implements org.springframework.batch.item.ItemReader<T> {
033
034        private static final String CHECKPOINT_KEY = "reader.checkpoint";
035
036        private ItemReader delegate;
037
038        /**
039         * @param reader the {@link ItemReader} implementation to delegate to
040         */
041        public ItemReaderAdapter(ItemReader reader) {
042                super(CHECKPOINT_KEY);
043                Assert.notNull(reader, "An ItemReader implementation is required");
044                this.delegate = reader;
045                setExecutionContextName(ClassUtils.getShortName(delegate.getClass()));
046        }
047
048        /* (non-Javadoc)
049         * @see org.springframework.batch.item.ItemReader#read()
050         */
051        @SuppressWarnings("unchecked")
052        @Override
053        public T read() throws Exception {
054                return (T) delegate.readItem();
055        }
056
057        /* (non-Javadoc)
058         * @see org.springframework.batch.jsr.item.CheckpointSupport#doClose()
059         */
060        @Override
061        protected void doClose() throws Exception{
062                delegate.close();
063        }
064
065        /* (non-Javadoc)
066         * @see org.springframework.batch.jsr.item.CheckpointSupport#doCheckpoint()
067         */
068        @Override
069        protected Serializable doCheckpoint() throws Exception {
070                return delegate.checkpointInfo();
071        }
072
073        /* (non-Javadoc)
074         * @see org.springframework.batch.jsr.item.CheckpointSupport#doOpen(java.io.Serializable)
075         */
076        @Override
077        protected void doOpen(Serializable checkpoint) throws Exception {
078                delegate.open(checkpoint);
079        }
080}