/**
 * 
 */
package jp.terasoluna.batch.functionsample.b001;

import jp.terasoluna.fw.batch.exception.BatchException;
import jp.terasoluna.fw.batch.util.BatchUtil;
import jp.terasoluna.fw.dao.UpdateDAO;
import jp.terasoluna.fw.dao.event.DataRowHandler;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * DB関連ジョブのサンプル<br>
 * <br>
 * RowHandler内でREQUIRES_NEWを利用し1件ずつコミットするサンプル。<br>
 * 70件以上は実行例外をスローし、ロールバックする。
 */
public class B001008DataRowHandler implements DataRowHandler {

	private Log log = LogFactory.getLog(B001008DataRowHandler.class);

	@Autowired
	@Qualifier("updateDAO")
	private UpdateDAO updateDAO = null;

	@Autowired
	@Qualifier("transactionManager")
	private PlatformTransactionManager transactionManager = null;

	public void handleRow(Object arg) {

		TransactionStatus stat = null;
		B001008Param param = null;

		if (arg instanceof B001008Param) {
			param = (B001008Param) arg;
		}

		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def
				.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
		stat = BatchUtil.startTransaction(transactionManager, def);

		try {

			param.setFamilyName("鈴木");
			param.setFirstName("次郎");

			if (param.getId() >= 70) {
				log.error("70件以上は実行例外をスローする");
				throw new BatchException();
			}

			updateDAO.execute("B001008.updateEmployee", param);
			BatchUtil.commitTransaction(transactionManager, stat);

		} catch (BatchException e) {
			BatchUtil.rollbackTransaction(transactionManager, stat);
			log.error(e);
			throw new BatchException(e);
		} finally {
			BatchUtil.endTransaction(transactionManager, stat);
		}
	}
}
