/** 
 * 
 * Copyright 2004 Protique Ltd
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/
package org.activemq.util;

import org.activemq.store.PersistenceAdapter;

import javax.jms.JMSException;

/**
 * A helper class for running code with a PersistenceAdapter
 * in a transaction.
 *
 * @version $Revision: 1.1.1.1 $
 */
public class TransactionTemplate {
    private PersistenceAdapter persistenceAdapter;

    public TransactionTemplate(PersistenceAdapter persistenceAdapter) {
        this.persistenceAdapter = persistenceAdapter;
    }

    public void run(Callback task) throws JMSException {
        persistenceAdapter.beginTransaction();
        Throwable throwable = null;
        try {
            task.execute();
        }
        catch (JMSException t) {
            throwable = t;
            throw t;
        }
        catch (RuntimeException t) {
            throwable = t;
            throw t;
        }
        catch (Throwable t) {
            throwable = t;
            throw JMSExceptionHelper.newJMSException("Persistence task failed: "+t, t);
        } finally {
            if (throwable == null) {
                persistenceAdapter.commitTransaction();
            }
            else {
                persistenceAdapter.rollbackTransaction();
            }            
        }
    }
}
