From 4c4b45259c4af24c2551c40df72ad776dd037cbe Mon Sep 17 00:00:00 2001 From: Erik Brakkee Date: Sun, 25 Apr 2010 21:31:31 +0000 Subject: [PATCH] Support classes for testing with services that require a transaction scoped transaction manager. --- .../support/ThreadSpecificProxyFactory.java | 89 +++++++++++++++ .../persistence/TransactionProxyFactory.java | 105 +++++++++++++++++ .../ThreadSpecificProxyFactoryTest.java | 106 ++++++++++++++++++ .../TransactionProxyFactoryTestBase.java | 102 +++++++++++++++++ 4 files changed, 402 insertions(+) create mode 100644 test/enterprise/src/main/java/org/wamblee/support/ThreadSpecificProxyFactory.java create mode 100644 test/enterprise/src/main/java/org/wamblee/support/persistence/TransactionProxyFactory.java create mode 100644 test/enterprise/src/test/java/org/wamblee/support/ThreadSpecificProxyFactoryTest.java create mode 100644 test/enterprise/src/test/java/org/wamblee/support/persistence/TransactionProxyFactoryTestBase.java diff --git a/test/enterprise/src/main/java/org/wamblee/support/ThreadSpecificProxyFactory.java b/test/enterprise/src/main/java/org/wamblee/support/ThreadSpecificProxyFactory.java new file mode 100644 index 00000000..1e9c3468 --- /dev/null +++ b/test/enterprise/src/main/java/org/wamblee/support/ThreadSpecificProxyFactory.java @@ -0,0 +1,89 @@ +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.support; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +/** + * Thread-specific proxy is used to create implementations of interfaces that + * delegate to a thread-specific implementation of the service. + * + * It is used for instance to pass a transaction scoped entity manager around. + * + * @param T + * Interface to proxy. + * @author Erik Brakkee + * + */ +public class ThreadSpecificProxyFactory { + private class ThreadSpecificInvocationHandler implements InvocationHandler { + + @Override + public Object invoke(Object aProxy, Method aMethod, Object[] aArgs) + throws Throwable { + try { + return aMethod.invoke(svc.get(), aArgs); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } + } + + private ThreadLocal svc = new ThreadLocal(); + private Class clazz; + + /** + * Constructs the factory. + * @param aClass Interface class of the service to proxy. + */ + public ThreadSpecificProxyFactory(Class aClass) { + if ( !aClass.isInterface() ) { + throw new IllegalArgumentException("Class " + aClass.getName() + " is not an interface"); + } + clazz = aClass; + } + + /** + * Sets the thread-specific service. + * @param aService Service, use null value to reset. + */ + public void set(T aService) { + svc.set(aService); + } + + /** + * Gets the proxy that delegates to the thread-specific instance set by + * {@link #set(Object)} + * @return Proxy. + */ + public T getProxy() { + InvocationHandler handler = new ThreadSpecificInvocationHandler(); + Class proxyClass = Proxy.getProxyClass(clazz.getClassLoader(), + new Class[] { clazz }); + T proxy; + try { + proxy = (T) proxyClass.getConstructor( + new Class[] { InvocationHandler.class }).newInstance( + new Object[] { handler }); + return proxy; + } catch (Exception e) { + throw new RuntimeException("Could not create proxy for " + clazz.getName(), e); + } + } +} diff --git a/test/enterprise/src/main/java/org/wamblee/support/persistence/TransactionProxyFactory.java b/test/enterprise/src/main/java/org/wamblee/support/persistence/TransactionProxyFactory.java new file mode 100644 index 00000000..4e72f484 --- /dev/null +++ b/test/enterprise/src/main/java/org/wamblee/support/persistence/TransactionProxyFactory.java @@ -0,0 +1,105 @@ +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.support.persistence; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +import javax.persistence.EntityManager; + +import org.wamblee.support.ThreadSpecificProxyFactory; +import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork; + +/** + * This utility makes sure that each invocation on a certain interface is + * carried out within a JPA unit of work. + * + * Use {@link #getTransactionScopedEntityManager()} to get the transaction scoped + * entity manager to pass to services. + * + * @param T + * Type of interface to proxy. + * + * @author Erik Brakkee + */ +public class TransactionProxyFactory { + + private class UnitOfWorkInvocationHandler implements InvocationHandler { + + private T service; + + public UnitOfWorkInvocationHandler(T aService) { + service = aService; + } + + @Override + public Object invoke(Object aProxy, final Method aMethod, + final Object[] aArgs) throws Throwable { + return TransactionProxyFactory.this.jpaBuilder + .execute(new JpaUnitOfWork() { + @Override + public Object execute(EntityManager aEm) throws Exception { + try { + ENTITY_MANAGER.set(aEm); + return aMethod.invoke(service, aArgs); + } catch (InvocationTargetException e) { + throw (Exception)e.getCause(); + } finally { + ENTITY_MANAGER.set(null); + } + } + }); + } + + } + + private static final ThreadSpecificProxyFactory ENTITY_MANAGER = + new ThreadSpecificProxyFactory(EntityManager.class); + + private JpaBuilder jpaBuilder; + private Class clazz; + + /** + * Constructs the transaction proxy. + * + * @param aJpaBuilder + */ + public TransactionProxyFactory(JpaBuilder aJpaBuilder, Class aClass) { + jpaBuilder = aJpaBuilder; + clazz = aClass; + } + + public EntityManager getTransactionScopedEntityManager() { + return ENTITY_MANAGER.getProxy(); + } + + public T getProxy(T aService) { + InvocationHandler handler = new UnitOfWorkInvocationHandler(aService); + Class proxyClass = Proxy.getProxyClass(clazz.getClassLoader(), + new Class[] { clazz }); + T proxy; + try { + proxy = (T) proxyClass.getConstructor( + new Class[] { InvocationHandler.class }).newInstance( + new Object[] { handler }); + return proxy; + } catch (Exception e) { + throw new RuntimeException("Could not create proxy for " + clazz.getName(), e); + } + } +} diff --git a/test/enterprise/src/test/java/org/wamblee/support/ThreadSpecificProxyFactoryTest.java b/test/enterprise/src/test/java/org/wamblee/support/ThreadSpecificProxyFactoryTest.java new file mode 100644 index 00000000..cb03843a --- /dev/null +++ b/test/enterprise/src/test/java/org/wamblee/support/ThreadSpecificProxyFactoryTest.java @@ -0,0 +1,106 @@ +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.support; + +import javax.xml.ws.Holder; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import static junit.framework.TestCase.*; +import static org.mockito.Mockito.*; + +public class ThreadSpecificProxyFactoryTest { + + private static interface Service { + int execute(int aX) throws Exception; + } + + private ThreadSpecificProxyFactory factory; + private Service proxy; + + @Before + public void setUp() { + factory = new ThreadSpecificProxyFactory(Service.class); + proxy = factory.getProxy(); + } + + @After + public void tearDown() { + // Empty. + } + + @Test(expected = NullPointerException.class) + public void testNoSvcDefined() throws Exception { + proxy.execute(10); + } + + @Test + public void testInvokeThroughProxy() throws Exception { + Service svc = mock(Service.class); + when(svc.execute(anyInt())).thenReturn(50); + factory.set(svc); + assertEquals(50, proxy.execute(10)); + verify(svc).execute(10); + } + + @Test + public void testInvokeThroughProxyWithException() throws Exception { + Service svc = mock(Service.class); + try { + when(svc.execute(anyInt())).thenThrow( + new RuntimeException("exception thrown")); + factory.set(svc); + svc.execute(10); + fail(); + } catch (RuntimeException e) { + assertEquals("exception thrown", e.getMessage()); + } + } + + private int returnFromThread; + + @Test + public void testVerifyThreadSpecificUsingTwoThreads() throws Exception { + Service svc1 = mock(Service.class); + final Service svc2 = mock(Service.class); + when(svc1.execute(anyInt())).thenReturn(10); + when(svc2.execute(anyInt())).thenReturn(20); + + factory.set(svc1); + assertEquals(10, svc1.execute(10)); + Thread t = new Thread() { + public void run() { + factory.set(svc2); + try { + returnFromThread = proxy.execute(100); + } catch (Exception e) { + returnFromThread = 100000; + } + }; + }; + t.start(); + t.join(); + assertEquals(20, returnFromThread); + assertEquals(10, proxy.execute(100)); + + } + + @Test(expected = IllegalArgumentException.class) + public void testNotAnInterface() { + ThreadSpecificProxyFactory f = new ThreadSpecificProxyFactory(String.class); + } +} diff --git a/test/enterprise/src/test/java/org/wamblee/support/persistence/TransactionProxyFactoryTestBase.java b/test/enterprise/src/test/java/org/wamblee/support/persistence/TransactionProxyFactoryTestBase.java new file mode 100644 index 00000000..286c8757 --- /dev/null +++ b/test/enterprise/src/test/java/org/wamblee/support/persistence/TransactionProxyFactoryTestBase.java @@ -0,0 +1,102 @@ +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.support.persistence; + +import javax.persistence.EntityManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork; + +import static junit.framework.TestCase.*; +import static org.mockito.Mockito.*; + +public class TransactionProxyFactoryTestBase { + + public static interface Service { + int execute(int aValue) throws Exception; + } + + private JpaTester jpaTester; + + @Before + public void setUp() throws Exception { + jpaTester = new JpaTester(new MyPersistenceUnit()); + jpaTester.start(); + } + + @After + public void tearDown() throws Exception { + jpaTester.stop(); + } + + @Test + public void testServiceIsInvoked() throws Exception { + TransactionProxyFactory factory = new TransactionProxyFactory( + jpaTester.getJpaBuilder(), Service.class); + Service service = mock(Service.class); + when(service.execute(10)).thenReturn(200); + Service proxy = factory.getProxy(service); + int res = proxy.execute(10); + assertEquals(200, res); + verify(service).execute(10); + } + + @Test + public void testServiceThrowsException() throws Exception { + TransactionProxyFactory factory = new TransactionProxyFactory( + jpaTester.getJpaBuilder(), Service.class); + Service service = mock(Service.class); + when(service.execute(10)).thenThrow(new RuntimeException("xyz")); + Service proxy = factory.getProxy(service); + try { + int res = proxy.execute(10); + fail(); + } catch (RuntimeException e) { + assertEquals("xyz", e.getMessage()); + } + } + + @Test + public void testEntityManagerIsPassed() throws Exception { + + + final TransactionProxyFactory factory = new TransactionProxyFactory( + jpaTester.getJpaBuilder(), Service.class); + Service service = new Service() { + private EntityManager em = factory.getTransactionScopedEntityManager(); + + @Override + public int execute(int aValue) throws Exception { + assertNotNull(em); + assertTrue(em.isOpen()); + return 0; + } + }; + + final Service proxy = factory.getProxy(service); + jpaTester.getJpaBuilder().execute(new JpaUnitOfWork() { + @Override + public Void execute(EntityManager aEm) throws Exception { + assert(aEm != null); + proxy.execute(10); + return null; + } + }); + } + +} -- 2.31.1