1 /*
2  * Copyright 2002-2008 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package org.springframework.dao.support;
18 
19 import java.util.ArrayList;
20 import java.util.List;
21 
22 import org.springframework.dao.DataAccessException;
23 import org.springframework.util.Assert;
24 
25 /**
26  * Implementation of {@link PersistenceExceptionTranslator} that supports chaining,
27  * allowing the addition of PersistenceExceptionTranslator instances in order.
28  * Returns <code>non-null</code> on the first (if any) match.
29  *
30  * @author Rod Johnson
31  * @author Juergen Hoeller
32  * @since 2.0
33  */
34 public class ChainedPersistenceExceptionTranslator implements PersistenceExceptionTranslator {
35 
36 	/** List of PersistenceExceptionTranslators */
37 	private final List<PersistenceExceptionTranslator> delegates = new ArrayList<PersistenceExceptionTranslator>(4);
38 
39 
40 	/**
41 	 * Add a PersistenceExceptionTranslator to the chained delegate list.
42 	 */
addDelegate(PersistenceExceptionTranslator pet)43 	public final void addDelegate(PersistenceExceptionTranslator pet) {
44 		Assert.notNull(pet, "PersistenceExceptionTranslator must not be null");
45 		this.delegates.add(pet);
46 	}
47 
48 	/**
49 	 * Return all registered PersistenceExceptionTranslator delegates (as array).
50 	 */
getDelegates()51 	public final PersistenceExceptionTranslator[] getDelegates() {
52 		return this.delegates.toArray(new PersistenceExceptionTranslator[this.delegates.size()]);
53 	}
54 
55 
translateExceptionIfPossible(RuntimeException ex)56 	public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
57 		for (PersistenceExceptionTranslator pet : this.delegates) {
58 			DataAccessException translatedDex = pet.translateExceptionIfPossible(ex);
59 			if (translatedDex != null) {
60 				return translatedDex;
61 			}
62 		}
63 		return null;
64 	}
65 
66 }
67