001 // Copyright 2009 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
015 package org.tynamo.jpa.internal;
016
017 import org.tynamo.jpa.JPATransactionManager;
018 import org.tynamo.jpa.JPATransactionAdvisor;
019 import org.tynamo.jpa.annotations.CommitAfter;
020 import org.apache.tapestry5.ioc.Invocation;
021 import org.apache.tapestry5.ioc.MethodAdvice;
022 import org.apache.tapestry5.ioc.MethodAdviceReceiver;
023
024 import java.lang.reflect.Method;
025
026 public class JPATransactionAdvisorImpl implements JPATransactionAdvisor {
027 private final JPATransactionManager manager;
028
029 /**
030 * The rules for advice are the same for any method: commit on success or checked exception, abort on thrown
031 * exception ... so we can use a single shared advice object.
032 */
033 private final MethodAdvice advice = new MethodAdvice() {
034 public void advise(Invocation invocation) {
035 try {
036 invocation.proceed();
037 }
038 catch (RuntimeException ex) {
039 manager.abort();
040
041 throw ex;
042 }
043
044 // For success or checked exception, commit the transaction.
045
046 manager.commit();
047 }
048 };
049
050 public JPATransactionAdvisorImpl(JPATransactionManager manager) {
051 this.manager = manager;
052 }
053
054 public void addTransactionCommitAdvice(MethodAdviceReceiver receiver) {
055 for (Method m : receiver.getInterface().getMethods()) {
056 if (m.getAnnotation(CommitAfter.class) != null) {
057 receiver.adviseMethod(m, advice);
058 }
059 }
060 }
061 }