2 * Copyright 2005-2010 the original author or authors.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.wamblee.support.persistence;
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.InvocationTargetException;
20 import java.lang.reflect.Method;
21 import java.lang.reflect.Proxy;
23 import javax.management.RuntimeErrorException;
24 import javax.persistence.EntityManager;
26 import org.wamblee.support.ThreadSpecificProxyFactory;
27 import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
30 * This utility makes sure that each invocation on a certain interface is
31 * carried out within a JPA unit of work.
33 * Use {@link #getTransactionScopedEntityManager()} to get the transaction
34 * scoped entity manager to pass to services.
37 * Type of interface to proxy.
39 * @author Erik Brakkee
41 public class TransactionProxyFactory<T> {
43 private class UnitOfWorkInvocationHandler<T> implements InvocationHandler {
47 public UnitOfWorkInvocationHandler(T aService) {
52 public Object invoke(Object aProxy, final Method aMethod,
53 final Object[] aArgs) throws Throwable {
54 return TransactionProxyFactory.this.jpaBuilder
55 .execute(new JpaUnitOfWork<Object>() {
57 public Object execute(EntityManager aEm) throws Exception {
59 ENTITY_MANAGER.set(aEm);
60 return aMethod.invoke(service, aArgs);
61 } catch (InvocationTargetException e) {
62 Throwable cause = e.getCause();
63 if (cause instanceof Exception) {
64 throw (Exception) cause;
65 } else if (cause instanceof Error) {
69 throw new RuntimeException(e);
71 ENTITY_MANAGER.set(null);
79 private static final ThreadSpecificProxyFactory<EntityManager> ENTITY_MANAGER = new ThreadSpecificProxyFactory<EntityManager>(
82 private JpaBuilder jpaBuilder;
83 private Class<T> clazz;
86 * Constructs the transaction proxy.
90 public TransactionProxyFactory(JpaBuilder aJpaBuilder, Class<T> aClass) {
91 jpaBuilder = aJpaBuilder;
95 public EntityManager getTransactionScopedEntityManager() {
96 return ENTITY_MANAGER.getProxy();
99 public T getProxy(T aService) {
100 InvocationHandler handler = new UnitOfWorkInvocationHandler<T>(aService);
101 Class proxyClass = Proxy.getProxyClass(clazz.getClassLoader(),
102 new Class[] { clazz });
105 proxy = (T) proxyClass.getConstructor(
106 new Class[] { InvocationHandler.class }).newInstance(
107 new Object[] { handler });
109 } catch (Exception e) {
110 throw new RuntimeException("Could not create proxy for " +