001// Copyright 2015 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.lang.reflect.Method;
018import java.util.HashMap;
019import java.util.Map;
020
021import javax.persistence.EntityManager;
022import javax.persistence.PersistenceContext;
023
024import org.apache.tapestry5.ioc.MethodAdviceReceiver;
025import org.apache.tapestry5.jpa.EntityManagerManager;
026import org.apache.tapestry5.jpa.EntityTransactionManager;
027import org.apache.tapestry5.jpa.JpaTransactionAdvisor;
028import org.apache.tapestry5.jpa.annotations.CommitAfter;
029import org.apache.tapestry5.plastic.MethodAdvice;
030
031public class JpaTransactionAdvisorImpl implements JpaTransactionAdvisor
032{
033    private final Map<String, MethodAdvice> methodAdvices;
034
035    public JpaTransactionAdvisorImpl(EntityManagerManager manager,
036            EntityTransactionManager transactionManager)
037    {
038        methodAdvices = new HashMap<>(manager.getEntityManagers().size());
039        for (Map.Entry<String, EntityManager> entry : manager.getEntityManagers().entrySet())
040            methodAdvices.put(entry.getKey(),
041                    new CommitAfterMethodAdvice(transactionManager, entry.getKey()));
042        methodAdvices.put(null, new CommitAfterMethodAdvice(transactionManager, null));
043    }
044
045    @Override
046    public void addTransactionCommitAdvice(MethodAdviceReceiver receiver)
047    {
048        for (final Method m : receiver.getInterface().getMethods())
049        {
050            if (m.getAnnotation(CommitAfter.class) != null)
051            {
052                PersistenceContext annotation = receiver.getMethodAnnotation(m,
053                        PersistenceContext.class);
054
055                receiver.adviseMethod(m,
056                        methodAdvices.get(annotation == null ? null : annotation.unitName()));
057            }
058        }
059    }
060
061}