01: /*
02: * Copyright 2002-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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.Iterator;
21: import java.util.List;
22:
23: import org.springframework.dao.DataAccessException;
24: import org.springframework.util.Assert;
25:
26: /**
27: * Implementation of PersistenceExceptionTranslator that supports chaining,
28: * allowing the addition of PersistenceExceptionTranslator instances in order.
29: * Returns <code>non-null</code> on the first (if any) match.
30: *
31: * @author Rod Johnson
32: * @author Juergen Hoeller
33: * @since 2.0
34: */
35: public class ChainedPersistenceExceptionTranslator implements
36: PersistenceExceptionTranslator {
37:
38: /** List of PersistenceExceptionTranslators */
39: private final List delegates = new ArrayList(4);
40:
41: /**
42: * Add a PersistenceExceptionTranslator to the chained delegate list.
43: */
44: public final void addDelegate(PersistenceExceptionTranslator pet) {
45: Assert.notNull(pet,
46: "PersistenceExceptionTranslator must not be null");
47: this .delegates.add(pet);
48: }
49:
50: /**
51: * Return all registered PersistenceExceptionTranslator delegates (as array).
52: */
53: public final PersistenceExceptionTranslator[] getDelegates() {
54: return (PersistenceExceptionTranslator[]) this .delegates
55: .toArray(new PersistenceExceptionTranslator[this .delegates
56: .size()]);
57: }
58:
59: public DataAccessException translateExceptionIfPossible(
60: RuntimeException ex) {
61: DataAccessException translatedDex = null;
62: for (Iterator it = this .delegates.iterator(); translatedDex == null
63: && it.hasNext();) {
64: PersistenceExceptionTranslator pet = (PersistenceExceptionTranslator) it
65: .next();
66: translatedDex = pet.translateExceptionIfPossible(ex);
67: }
68: return translatedDex;
69: }
70:
71: }
|