(no commit message)
[utils] / test / enterprise / src / main / java / org / wamblee / test / transactions / TransactionProxyFactory.java
1 /*
2  * Copyright 2005-2010 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 package org.wamblee.test.transactions;
17
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.InvocationTargetException;
20 import java.lang.reflect.Method;
21 import java.lang.reflect.Proxy;
22 import java.util.logging.Level;
23
24 import javax.persistence.EntityManager;
25
26 import org.wamblee.general.ThreadSpecificProxyFactory;
27 import org.wamblee.test.persistence.JpaBuilder;
28 import org.wamblee.test.persistence.LoggingTransactionResultCallback;
29 import org.wamblee.test.persistence.JpaBuilder.JpaUnitOfWork;
30
31 /**
32  * This utility makes sure that each invocation on a certain interface is
33  * carried out within a JPA unit of work. Note that this is equivalent to the
34  * sementics of a requiresNew transaction attribute.
35  * 
36  * Use {@link #getTransactionScopedEntityManager()} to get the transaction
37  * scoped entity manager to pass to services.
38  * 
39  * 
40  * For example:
41  * 
42  * <pre>
43  *     JpaBuilder builder = ...
44  *     TransactionProxyFactory<Service> factory = new TransactionProxyFactory<Service>(
45  *           builder, Service.class);
46  *     Service service = new JpaService(factory.getTransactionScopedEntityManager());
47  *     Service proxy = factory.getProxy(service);
48  *     proxy.executeMethod(...);
49  * </pre>
50  * 
51  * The above example executes the executeMethod() call on the service object
52  * within an active transaction. In the constructor of the service a transaction
53  * scoped entity manager is passed.
54  * 
55  * @param T
56  *            Type of interface to proxy.
57  * 
58  * @author Erik Brakkee
59  */
60 public class TransactionProxyFactory<T> {
61
62     /**
63      * Executes the call on the service within a new transaction.
64      * 
65      * @author Erik Brakkee
66      * 
67      * @param <T>
68      *            Type of the service interface.
69      */
70     private class UnitOfWorkInvocationHandler<T> implements InvocationHandler {
71
72         private T service;
73
74         public UnitOfWorkInvocationHandler(T aService) {
75             service = aService;
76         }
77
78         @Override
79         public Object invoke(Object aProxy, final Method aMethod,
80             final Object[] aArgs) throws Throwable {
81             return TransactionProxyFactory.this.jpaBuilder.execute(
82                 new JpaUnitOfWork<Object>() {
83                     @Override
84                     public Object execute(EntityManager aEm) throws Exception {
85                         EntityManager oldEm = ENTITY_MANAGER.get();
86                         try {
87                             ENTITY_MANAGER.set(aEm);
88                             return aMethod.invoke(service, aArgs);
89                         } catch (InvocationTargetException e) {
90                             Throwable cause = e.getCause();
91                             if (cause instanceof Exception) {
92                                 throw (Exception) cause;
93                             } else if (cause instanceof Error) {
94                                 throw (Error) cause;
95                             }
96                             // last resort.
97                             throw new RuntimeException(e);
98                         } finally {
99                             ENTITY_MANAGER.set(oldEm);
100                         }
101                     }
102                 }, new LoggingTransactionResultCallback(Level.INFO));
103         }
104
105     }
106
107     private static final ThreadSpecificProxyFactory<EntityManager> ENTITY_MANAGER = new ThreadSpecificProxyFactory<EntityManager>(
108         EntityManager.class);
109
110     private JpaBuilder jpaBuilder;
111     private Class<T> clazz;
112
113     /**
114      * Constructs the transaction proxy.
115      * 
116      * @param aJpaBuilder
117      */
118     public TransactionProxyFactory(JpaBuilder aJpaBuilder, Class<T> aClass) {
119         jpaBuilder = aJpaBuilder;
120         clazz = aClass;
121     }
122
123     public EntityManager getTransactionScopedEntityManager() {
124         return ENTITY_MANAGER.getProxy();
125     }
126
127     public T getProxy(T aService) {
128         InvocationHandler handler = new UnitOfWorkInvocationHandler<T>(aService);
129         Class proxyClass = Proxy.getProxyClass(clazz.getClassLoader(),
130             new Class[] { clazz });
131         T proxy;
132         try {
133             proxy = (T) proxyClass.getConstructor(
134                 new Class[] { InvocationHandler.class }).newInstance(
135                 new Object[] { handler });
136             return proxy;
137         } catch (Exception e) {
138             throw new RuntimeException("Could not create proxy for " +
139                 clazz.getName(), e);
140         }
141     }
142 }