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    public <T> T provide(final Class<T> objectType, final AnnotationProvider annotationProvider,
033                         final ObjectLocator locator)
034    {
035        if (objectType.equals(EntityManager.class))
036            return objectType.cast(getOrCreateProxy(annotationProvider, locator));
037
038        return null;
039    }
040
041    private synchronized EntityManager getOrCreateProxy(
042            final AnnotationProvider annotationProvider, final ObjectLocator objectLocator)
043    {
044        if (proxy == null)
045        {
046            final PlasticProxyFactory proxyFactory = objectLocator.getService("PlasticProxyFactory",
047                    PlasticProxyFactory.class);
048
049            final PersistenceContext annotation = annotationProvider
050                    .getAnnotation(PersistenceContext.class);
051
052            proxy = proxyFactory.createProxy(EntityManager.class, new ObjectCreator()
053            {
054                public Object createObject()
055                {
056                    final EntityManagerManager entityManagerManager = objectLocator
057                            .getService(EntityManagerManager.class);
058
059                    return JpaInternalUtils.getEntityManager(entityManagerManager, annotation);
060                }
061            }, "<EntityManagerProxy>");
062        }
063
064        return proxy;
065    }
066
067}