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.sample.common;
018
019import javax.sql.DataSource;
020
021import org.springframework.batch.core.listener.StepListenerSupport;
022import org.springframework.batch.item.ItemReader;
023import org.springframework.beans.factory.InitializingBean;
024import org.springframework.dao.OptimisticLockingFailureException;
025import org.springframework.jdbc.core.JdbcOperations;
026import org.springframework.jdbc.core.JdbcTemplate;
027import org.springframework.util.Assert;
028
029/**
030 * Thread-safe database {@link ItemReader} implementing the process indicator
031 * pattern.
032 */
033public class StagingItemListener extends StepListenerSupport<Long, Long> implements InitializingBean {
034
035        private JdbcOperations jdbcTemplate;
036
037        public void setDataSource(DataSource dataSource) {
038                jdbcTemplate = new JdbcTemplate(dataSource);
039        }
040
041        @Override
042        public final void afterPropertiesSet() throws Exception {
043                Assert.notNull(jdbcTemplate, "You must provide a DataSource.");
044        }
045
046        @Override
047        public void afterRead(Long id) {
048                int count = jdbcTemplate.update("UPDATE BATCH_STAGING SET PROCESSED=? WHERE ID=? AND PROCESSED=?",
049                                StagingItemWriter.DONE, id, StagingItemWriter.NEW);
050                if (count != 1) {
051                        throw new OptimisticLockingFailureException("The staging record with ID=" + id
052                                        + " was updated concurrently when trying to mark as complete (updated " + count + " records.");
053                }
054        }
055
056}