001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq.util;
018
019import java.io.IOException;
020import org.apache.activemq.broker.ConnectionContext;
021import org.apache.activemq.store.PersistenceAdapter;
022import org.slf4j.Logger;
023import org.slf4j.LoggerFactory;
024
025/**
026 * A helper class for running code with a PersistenceAdapter in a transaction.
027 * 
028 * 
029 */
030public class TransactionTemplate {
031    private static final Logger LOG = LoggerFactory.getLogger(TransactionTemplate.class);
032    private PersistenceAdapter persistenceAdapter;
033    private ConnectionContext context;
034
035    public TransactionTemplate(PersistenceAdapter persistenceAdapter, ConnectionContext context) {
036        this.persistenceAdapter = persistenceAdapter;
037        this.context = context;
038    }
039
040    public void run(Callback task) throws IOException {
041        persistenceAdapter.beginTransaction(context);
042        Throwable throwable = null;
043        try {
044            task.execute();
045        } catch (IOException t) {
046            throwable = t;
047            throw t;
048        } catch (RuntimeException t) {
049            throwable = t;
050            throw t;
051        } catch (Throwable t) {
052            throwable = t;
053            throw IOExceptionSupport.create("Persistence task failed: " + t, t);
054        } finally {
055            if (throwable == null) {
056                persistenceAdapter.commitTransaction(context);
057            } else {
058                LOG.error("Having to Rollback - caught an exception: " + throwable);
059                persistenceAdapter.rollbackTransaction(context);
060            }
061        }
062    }
063
064    public ConnectionContext getContext() {
065        return context;
066    }
067
068    public PersistenceAdapter getPersistenceAdapter() {
069        return persistenceAdapter;
070    }
071}