Now setting connection autocommit to false before
[utils] / test / enterprise / src / main / java / org / wamblee / support / persistence / 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.support.persistence;
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
23 import javax.persistence.EntityManager;
24
25 import org.wamblee.support.ThreadSpecificProxyFactory;
26 import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
27
28 /**
29  * This utility makes sure that each invocation on a certain interface is
30  * carried out within a JPA unit of work.
31  * 
32  * Use {@link #getTransactionScopedEntityManager()} to get the transaction
33  * scoped entity manager to pass to services.
34  * 
35  * @param T
36  *            Type of interface to proxy.
37  * 
38  * @author Erik Brakkee
39  */
40 public class TransactionProxyFactory<T> {
41
42     private class UnitOfWorkInvocationHandler<T> implements InvocationHandler {
43
44         private T service;
45
46         public UnitOfWorkInvocationHandler(T aService) {
47             service = aService;
48         }
49
50         @Override
51         public Object invoke(Object aProxy, final Method aMethod,
52             final Object[] aArgs) throws Throwable {
53             return TransactionProxyFactory.this.jpaBuilder
54                 .execute(new JpaUnitOfWork<Object>() {
55                     @Override
56                     public Object execute(EntityManager aEm) throws Exception {
57                         try {
58                             ENTITY_MANAGER.set(aEm);
59                             return aMethod.invoke(service, aArgs);
60                         } catch (InvocationTargetException e) {
61                             Throwable cause = e.getCause();
62                             if (cause instanceof Exception) {
63                                 throw (Exception) cause;
64                             } else if (cause instanceof Error) {
65                                 throw (Error) cause;
66                             }
67                             // last resort.
68                             throw new RuntimeException(e);
69                         } finally {
70                             ENTITY_MANAGER.set(null);
71                         }
72                     }
73                 });
74         }
75
76     }
77
78     private static final ThreadSpecificProxyFactory<EntityManager> ENTITY_MANAGER = new ThreadSpecificProxyFactory<EntityManager>(
79         EntityManager.class);
80
81     private JpaBuilder jpaBuilder;
82     private Class<T> clazz;
83
84     /**
85      * Constructs the transaction proxy.
86      * 
87      * @param aJpaBuilder
88      */
89     public TransactionProxyFactory(JpaBuilder aJpaBuilder, Class<T> aClass) {
90         jpaBuilder = aJpaBuilder;
91         clazz = aClass;
92     }
93
94     public EntityManager getTransactionScopedEntityManager() {
95         return ENTITY_MANAGER.getProxy();
96     }
97
98     public T getProxy(T aService) {
99         InvocationHandler handler = new UnitOfWorkInvocationHandler<T>(aService);
100         Class proxyClass = Proxy.getProxyClass(clazz.getClassLoader(),
101             new Class[] { clazz });
102         T proxy;
103         try {
104             proxy = (T) proxyClass.getConstructor(
105                 new Class[] { InvocationHandler.class }).newInstance(
106                 new Object[] { handler });
107             return proxy;
108         } catch (Exception e) {
109             throw new RuntimeException("Could not create proxy for " +
110                 clazz.getName(), e);
111         }
112     }
113 }