001/* 002 * Copyright 2013-2014 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.jsr; 017 018import javax.batch.operations.BatchRuntimeException; 019 020import org.springframework.batch.core.ChunkListener; 021import org.springframework.batch.core.scope.context.ChunkContext; 022import org.springframework.batch.core.step.tasklet.UncheckedTransactionException; 023import org.springframework.util.Assert; 024 025/** 026 * Wrapper class to adapt the {@link javax.batch.api.chunk.listener.ChunkListener} to 027 * a {@link ChunkListener}. 028 * 029 * @author Michael Minella 030 * @since 3.0 031 */ 032public class ChunkListenerAdapter implements ChunkListener { 033 034 private final javax.batch.api.chunk.listener.ChunkListener delegate; 035 036 /** 037 * @param delegate to be called within the step chunk lifecycle 038 */ 039 public ChunkListenerAdapter(javax.batch.api.chunk.listener.ChunkListener delegate) { 040 Assert.notNull(delegate, "A ChunkListener is required"); 041 this.delegate = delegate; 042 } 043 044 @Override 045 public void beforeChunk(ChunkContext context) { 046 try { 047 delegate.beforeChunk(); 048 } catch (Exception e) { 049 throw new UncheckedTransactionException(e); 050 } 051 } 052 053 @Override 054 public void afterChunk(ChunkContext context) { 055 try { 056 delegate.afterChunk(); 057 } catch (Exception e) { 058 throw new UncheckedTransactionException(e); 059 } 060 } 061 062 @Override 063 public void afterChunkError(ChunkContext context) { 064 if(context != null) { 065 try { 066 delegate.onError((Exception) context.getAttribute(ChunkListener.ROLLBACK_EXCEPTION_KEY)); 067 } catch (Exception e) { 068 throw new UncheckedTransactionException(e); 069 } 070 } else { 071 throw new BatchRuntimeException("Unable to retrieve causing exception due to null ChunkContext"); 072 } 073 } 074}