001// Copyright 2011 The Apache Software Foundation 002// 003// Licensed under the Apache License, Version 2.0 (the "License"); 004// you may not use this file except in compliance with the License. 005// You may obtain a copy of the License at 006// 007// http://www.apache.org/licenses/LICENSE-2.0 008// 009// Unless required by applicable law or agreed to in writing, software 010// distributed under the License is distributed on an "AS IS" BASIS, 011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012// See the License for the specific language governing permissions and 013// limitations under the License. 014 015package org.apache.tapestry5.internal.jpa; 016 017import java.util.HashMap; 018import java.util.Map; 019 020import javax.persistence.EntityManager; 021import javax.persistence.PersistenceContext; 022 023import org.apache.tapestry5.ioc.AnnotationProvider; 024import org.apache.tapestry5.ioc.ObjectCreator; 025import org.apache.tapestry5.ioc.ObjectLocator; 026import org.apache.tapestry5.ioc.ObjectProvider; 027import org.apache.tapestry5.ioc.services.PlasticProxyFactory; 028import org.apache.tapestry5.jpa.EntityManagerManager; 029 030public class EntityManagerObjectProvider implements ObjectProvider 031{ 032 private Map<String, EntityManager> emProxyByName = new HashMap<String, EntityManager>(); 033 034 @Override 035 public <T> T provide(final Class<T> objectType, final AnnotationProvider annotationProvider, 036 final ObjectLocator locator) 037 { 038 if (objectType.equals(EntityManager.class)) 039 return objectType.cast(getOrCreateProxy(annotationProvider, locator)); 040 041 return null; 042 } 043 044 @SuppressWarnings( 045 { "unchecked", "rawtypes" }) 046 private EntityManager getOrCreateProxy(final AnnotationProvider annotationProvider, 047 final ObjectLocator objectLocator) 048 { 049 final PersistenceContext annotation = annotationProvider 050 .getAnnotation(PersistenceContext.class); 051 final String unitName = annotation == null ? null : annotation.unitName(); 052 EntityManager proxy = emProxyByName.get(unitName); 053 if (proxy == null) 054 synchronized (this) 055 { 056 final PlasticProxyFactory proxyFactory = objectLocator.getService( 057 "PlasticProxyFactory", PlasticProxyFactory.class); 058 059 proxy = proxyFactory.createProxy(EntityManager.class, new ObjectCreator() 060 { 061 @Override 062 public Object createObject() 063 { 064 final EntityManagerManager entityManagerManager = objectLocator 065 .getService(EntityManagerManager.class); 066 067 return JpaInternalUtils.getEntityManager(entityManagerManager, annotation); 068 } 069 }, "<EntityManagerProxy>"); 070 emProxyByName.put(unitName, proxy); 071 } 072 073 return proxy; 074 } 075 076}