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