001/* 002 * Copyright 2002-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.dao.support; 018 019import java.util.ArrayList; 020import java.util.List; 021 022import org.springframework.dao.DataAccessException; 023import org.springframework.util.Assert; 024 025/** 026 * Implementation of {@link PersistenceExceptionTranslator} that supports chaining, 027 * allowing the addition of PersistenceExceptionTranslator instances in order. 028 * Returns {@code non-null} on the first (if any) match. 029 * 030 * @author Rod Johnson 031 * @author Juergen Hoeller 032 * @since 2.0 033 */ 034public class ChainedPersistenceExceptionTranslator implements PersistenceExceptionTranslator { 035 036 /** List of PersistenceExceptionTranslators */ 037 private final List<PersistenceExceptionTranslator> delegates = new ArrayList<PersistenceExceptionTranslator>(4); 038 039 040 /** 041 * Add a PersistenceExceptionTranslator to the chained delegate list. 042 */ 043 public final void addDelegate(PersistenceExceptionTranslator pet) { 044 Assert.notNull(pet, "PersistenceExceptionTranslator must not be null"); 045 this.delegates.add(pet); 046 } 047 048 /** 049 * Return all registered PersistenceExceptionTranslator delegates (as array). 050 */ 051 public final PersistenceExceptionTranslator[] getDelegates() { 052 return this.delegates.toArray(new PersistenceExceptionTranslator[this.delegates.size()]); 053 } 054 055 056 @Override 057 public DataAccessException translateExceptionIfPossible(RuntimeException ex) { 058 for (PersistenceExceptionTranslator pet : this.delegates) { 059 DataAccessException translatedDex = pet.translateExceptionIfPossible(ex); 060 if (translatedDex != null) { 061 return translatedDex; 062 } 063 } 064 return null; 065 } 066 067}