001: /*
002: * Copyright 2002-2007 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: * http://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:
017: package org.springframework.transaction.interceptor;
018:
019: import java.io.IOException;
020: import java.io.ObjectInputStream;
021: import java.io.ObjectOutputStream;
022: import java.io.Serializable;
023: import java.util.Properties;
024:
025: import org.aopalliance.intercept.MethodInterceptor;
026: import org.aopalliance.intercept.MethodInvocation;
027:
028: import org.springframework.transaction.PlatformTransactionManager;
029: import org.springframework.transaction.TransactionStatus;
030: import org.springframework.transaction.support.CallbackPreferringPlatformTransactionManager;
031: import org.springframework.transaction.support.TransactionCallback;
032:
033: /**
034: * AOP Alliance MethodInterceptor for declarative transaction
035: * management using the common Spring transaction infrastructure
036: * ({@link org.springframework.transaction.PlatformTransactionManager}).
037: *
038: * <p>Derives from the {@link TransactionAspectSupport} class which
039: * contains the integration with Spring's underlying transaction API.
040: * TransactionInterceptor simply calls the relevant superclass methods
041: * such as {@link #createTransactionIfNecessary} in the correct order.
042: *
043: * <p>TransactionInterceptors are thread-safe.
044: *
045: * @author Rod Johnson
046: * @author Juergen Hoeller
047: * @see TransactionProxyFactoryBean
048: * @see org.springframework.aop.framework.ProxyFactoryBean
049: * @see org.springframework.aop.framework.ProxyFactory
050: */
051: public class TransactionInterceptor extends TransactionAspectSupport
052: implements MethodInterceptor, Serializable {
053:
054: /**
055: * Create a new TransactionInterceptor.
056: * <p>Transaction manager and transaction attributes still need to be set.
057: * @see #setTransactionManager
058: * @see #setTransactionAttributes(java.util.Properties)
059: * @see #setTransactionAttributeSource(TransactionAttributeSource)
060: */
061: public TransactionInterceptor() {
062: }
063:
064: /**
065: * Create a new TransactionInterceptor.
066: * @param ptm the transaction manager to perform the actual transaction management
067: * @param attributes the transaction attributes in properties format
068: * @see #setTransactionManager
069: * @see #setTransactionAttributes(java.util.Properties)
070: */
071: public TransactionInterceptor(PlatformTransactionManager ptm,
072: Properties attributes) {
073: setTransactionManager(ptm);
074: setTransactionAttributes(attributes);
075: }
076:
077: /**
078: * Create a new TransactionInterceptor.
079: * @param ptm the transaction manager to perform the actual transaction management
080: * @param tas the attribute source to be used to find transaction attributes
081: * @see #setTransactionManager
082: * @see #setTransactionAttributeSource(TransactionAttributeSource)
083: */
084: public TransactionInterceptor(PlatformTransactionManager ptm,
085: TransactionAttributeSource tas) {
086: setTransactionManager(ptm);
087: setTransactionAttributeSource(tas);
088: }
089:
090: public Object invoke(final MethodInvocation invocation)
091: throws Throwable {
092: // Work out the target class: may be <code>null</code>.
093: // The TransactionAttributeSource should be passed the target class
094: // as well as the method, which may be from an interface.
095: Class targetClass = (invocation.getThis() != null ? invocation
096: .getThis().getClass() : null);
097:
098: // If the transaction attribute is null, the method is non-transactional.
099: final TransactionAttribute txAttr = getTransactionAttributeSource()
100: .getTransactionAttribute(invocation.getMethod(),
101: targetClass);
102: final String joinpointIdentification = methodIdentification(invocation
103: .getMethod());
104:
105: if (txAttr == null
106: || !(getTransactionManager() instanceof CallbackPreferringPlatformTransactionManager)) {
107: // Standard transaction demarcation with getTransaction and commit/rollback calls.
108: TransactionInfo txInfo = createTransactionIfNecessary(
109: txAttr, joinpointIdentification);
110: Object retVal = null;
111: try {
112: // This is an around advice: Invoke the next interceptor in the chain.
113: // This will normally result in a target object being invoked.
114: retVal = invocation.proceed();
115: } catch (Throwable ex) {
116: // target invocation exception
117: completeTransactionAfterThrowing(txInfo, ex);
118: throw ex;
119: } finally {
120: cleanupTransactionInfo(txInfo);
121: }
122: commitTransactionAfterReturning(txInfo);
123: return retVal;
124: }
125:
126: else {
127: // It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
128: try {
129: Object result = ((CallbackPreferringPlatformTransactionManager) getTransactionManager())
130: .execute(txAttr, new TransactionCallback() {
131: public Object doInTransaction(
132: TransactionStatus status) {
133: TransactionInfo txInfo = prepareTransactionInfo(
134: txAttr,
135: joinpointIdentification, status);
136: try {
137: return invocation.proceed();
138: } catch (Throwable ex) {
139: if (txAttr.rollbackOn(ex)) {
140: // A RuntimeException: will lead to a rollback.
141: if (ex instanceof RuntimeException) {
142: throw (RuntimeException) ex;
143: } else {
144: throw new ThrowableHolderException(
145: ex);
146: }
147: } else {
148: // A normal return value: will lead to a commit.
149: return new ThrowableHolder(ex);
150: }
151: } finally {
152: cleanupTransactionInfo(txInfo);
153: }
154: }
155: });
156:
157: // Check result: It might indicate a Throwable to rethrow.
158: if (result instanceof ThrowableHolder) {
159: throw ((ThrowableHolder) result).getThrowable();
160: } else {
161: return result;
162: }
163: } catch (ThrowableHolderException ex) {
164: throw ex.getCause();
165: }
166: }
167: }
168:
169: //---------------------------------------------------------------------
170: // Serialization support
171: //---------------------------------------------------------------------
172:
173: private void readObject(ObjectInputStream ois) throws IOException,
174: ClassNotFoundException {
175: // Rely on default serialization, although this class itself doesn't carry state anyway...
176: ois.defaultReadObject();
177:
178: // Serialize all relevant superclass fields.
179: // Superclass can't implement Serializable because it also serves as base class
180: // for AspectJ aspects (which are not allowed to implement Serializable)!
181: setTransactionManager((PlatformTransactionManager) ois
182: .readObject());
183: setTransactionAttributeSource((TransactionAttributeSource) ois
184: .readObject());
185: }
186:
187: private void writeObject(ObjectOutputStream oos) throws IOException {
188: // Rely on default serialization, although this class itself doesn't carry state anyway...
189: oos.defaultWriteObject();
190:
191: // Deserialize superclass fields.
192: oos.writeObject(getTransactionManager());
193: oos.writeObject(getTransactionAttributeSource());
194: }
195:
196: /**
197: * Internal holder class for a Throwable, used as a return value
198: * from a TransactionCallback (to be subsequently unwrapped again).
199: */
200: private static class ThrowableHolder {
201:
202: private final Throwable throwable;
203:
204: public ThrowableHolder(Throwable throwable) {
205: this .throwable = throwable;
206: }
207:
208: public final Throwable getThrowable() {
209: return this .throwable;
210: }
211: }
212:
213: /**
214: * Internal holder class for a Throwable, used as a RuntimeException to be
215: * thrown from a TransactionCallback (and subsequently unwrapped again).
216: */
217: private static class ThrowableHolderException extends
218: RuntimeException {
219:
220: public ThrowableHolderException(Throwable throwable) {
221: super (throwable);
222: }
223:
224: public String toString() {
225: return getCause().toString();
226: }
227: }
228:
229: }
|