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 EntityManager proxy = emProxyByName.get(annotation.unitName()); 052 if (proxy == null) 053 synchronized (this) 054 { 055 final PlasticProxyFactory proxyFactory = objectLocator.getService( 056 "PlasticProxyFactory", PlasticProxyFactory.class); 057 058 proxy = proxyFactory.createProxy(EntityManager.class, new ObjectCreator() 059 { 060 @Override 061 public Object createObject() 062 { 063 final EntityManagerManager entityManagerManager = objectLocator 064 .getService(EntityManagerManager.class); 065 066 return JpaInternalUtils.getEntityManager(entityManagerManager, annotation); 067 } 068 }, "<EntityManagerProxy>"); 069 emProxyByName.put(annotation.unitName(), proxy); 070 } 071 072 return proxy; 073 } 074 075}