    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 org.apache.tapestry5.ioc.AnnotationProvider;
    018import org.apache.tapestry5.ioc.ObjectCreator;
    019import org.apache.tapestry5.ioc.ObjectLocator;
    020import org.apache.tapestry5.ioc.ObjectProvider;
    021import org.apache.tapestry5.ioc.services.PlasticProxyFactory;
    022import org.apache.tapestry5.jpa.EntityManagerManager;
    023
    024import javax.persistence.EntityManager;
    025import javax.persistence.PersistenceContext;
    026
    027public class EntityManagerObjectProvider implements ObjectProvider
    028{
    029
    030    private EntityManager proxy;
    031
    032    @Override
    033    public <T> T provide(final Class<T> objectType, final AnnotationProvider annotationProvider,
    034                         final ObjectLocator locator)
    035    {
    036        if (objectType.equals(EntityManager.class))
    037            return objectType.cast(getOrCreateProxy(annotationProvider, locator));
    038
    039        return null;
    040    }
    041
    042    private synchronized EntityManager getOrCreateProxy(
    043            final AnnotationProvider annotationProvider, final ObjectLocator objectLocator)
    044    {
    045        if (proxy == null)
    046        {
    047            final PlasticProxyFactory proxyFactory = objectLocator.getService("PlasticProxyFactory",
    048                    PlasticProxyFactory.class);
    049
    050            final PersistenceContext annotation = annotationProvider
    051                    .getAnnotation(PersistenceContext.class);
    052
    053            proxy = proxyFactory.createProxy(EntityManager.class, new ObjectCreator()
    054            {
    055                @Override
    056                public Object createObject()
    057                {
    058                    final EntityManagerManager entityManagerManager = objectLocator
    059                            .getService(EntityManagerManager.class);
    060
    061                    return JpaInternalUtils.getEntityManager(entityManagerManager, annotation);
    062                }
    063            }, "<EntityManagerProxy>");
    064        }
    065
    066        return proxy;
    067    }
    068
    069}