001// Copyright 2011, 2014 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.jpa.EntityManagerManager; 024import org.apache.tapestry5.jpa.EntityTransactionManager; 025import org.apache.tapestry5.jpa.annotations.CommitAfter; 026import org.apache.tapestry5.model.MutableComponentModel; 027import org.apache.tapestry5.plastic.MethodAdvice; 028import org.apache.tapestry5.plastic.PlasticClass; 029import org.apache.tapestry5.plastic.PlasticMethod; 030import org.apache.tapestry5.services.transform.ComponentClassTransformWorker2; 031import org.apache.tapestry5.services.transform.TransformationSupport; 032 033public class CommitAfterWorker implements ComponentClassTransformWorker2 034{ 035 private final Map<String, MethodAdvice> methodAdvices; 036 037 public CommitAfterWorker(EntityManagerManager manager, 038 EntityTransactionManager transactionManager) 039 { 040 methodAdvices = new HashMap<>(manager.getEntityManagers().size()); 041 for (Map.Entry<String, EntityManager> entry : manager.getEntityManagers().entrySet()) 042 methodAdvices.put(entry.getKey(), 043 new CommitAfterMethodAdvice(transactionManager, entry.getKey())); 044 methodAdvices.put(null, new CommitAfterMethodAdvice(transactionManager, null)); 045 } 046 047 @Override 048 public void transform(PlasticClass plasticClass, TransformationSupport support, 049 MutableComponentModel model) 050 { 051 for (final PlasticMethod method : plasticClass.getMethodsWithAnnotation(CommitAfter.class)) 052 { 053 PersistenceContext annotation = method.getAnnotation(PersistenceContext.class); 054 055 method.addAdvice(methodAdvices.get(annotation == null ? null : annotation.unitName())); 056 } 057 } 058}