⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 transactionalsupport.java

📁 A Java web application, based on Struts and Hibernate, that serves as an online running log. Users m
💻 JAVA
字号:
/* @LICENSE_COPYRIGHT@ */
package net.sf.irunninglog.transaction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.sf.irunninglog.util.ObjectFactory;

/**
 * Class responsible for managing transactional behavior within the system.
 * This class provides the methods needed to begin, commit, and roll back
 * transactions, and to obtain the unit of work being used by the current
 * transaction to interact with the application's persistent store.
 *
 * <p/>
 *
 * Transactions are managed on a per-thread basis.  As long a single thread is
 * controlling the execution of applicaiton logic, the same transaction and
 * unit of work is shared by any calls made to this class between begin and
 * commit calls.  Only one transaction may be open at a time on a single thread;
 * if an attempt is made ot open more than one transaction at a time a
 * <code>TransactionException</code> will be thrown.
 *
 * @author <a href="mailto:allan_e_lewis@yahoo.com">Allan Lewis</a>
 * @version $Revision: 1.2 $ $Date: 2005/06/30 22:46:38 $
 * @since iRunningLog 1.0
 * @see ITransaction
 * @see IUnitOfWork
 * @see TransactionException
 */
public final class TransactionalSupport {

    /** <code>Log</code> instance for this class. */
    private static final Log LOG;
    /** Thread local variable used to store the current transaction context. */
    private static final ThreadLocal TL;

    static {
        LOG = LogFactory.getLog(TransactionalSupport.class);
        TL = new ThreadLocal();
    }

    /** Utility class - does not provide a constructor. */
    private TransactionalSupport() { }

    /**
     * Create and begin a new transaction on the current thread.  This will
     * create a new <code>ITransaction</code> instance and associate it with
     * the currently executing thread.
     *
     * @return The unit of work associated with the new transaction
     * @throws TransactionException If a transaction already exists on the
     *                              current thread
     */
    public static IUnitOfWork beginTransaction() throws TransactionException {
        ITransaction transaction = getCurrentTransaction();

        if (LOG.isDebugEnabled()) {
            LOG.debug("beginTransaction: Current transaction is "
                      + transaction);
        }

        if (transaction != null) {
            LOG.error("A transaction has already begun");
            throw new TransactionException("A transaction has already begun");
        }

        transaction = createNewTransaction();
        transaction.begin();

        if (LOG.isDebugEnabled()) {
            LOG.debug("beginTransaction: The following transaction has begun "
                      + transaction);
        }

        setCurrentTransaction(transaction);

        return transaction.getUnitOfWork();
    }

    /**
     * Get the unit of work for the transaction that is associated with the
     * current thread.
     *
     * @return The current transaction's unit of work
     * @throws TransactionException If no transaction is present, or if the
     *                              current transaciton is inactive
     */
    public static IUnitOfWork getUnitOfWork() throws TransactionException {
        ITransaction transaction = getCurrentTransaction();

        if (LOG.isDebugEnabled()) {
            LOG.debug("getUnitOfWork: Retrieved the following transaction "
                      + transaction);
        }

        ensureActive(transaction);

        return transaction.getUnitOfWork();
    }

    /**
     * Commit the transaction associated with the current thread.
     *
     * @throws TransactionException If no transaction is present, or if the
     *                              current transaciton is inactive
     */
    public static void commitTransaction() throws TransactionException {
        ITransaction transaction = getCurrentTransaction();

        if (LOG.isDebugEnabled()) {
            LOG.debug("commitTransaction: Retrieved the following transaction "
                      + transaction);
        }

        ensureActive(transaction);

        if (LOG.isDebugEnabled()) {
            LOG.debug("commitTransaction: Commiting this transaction "
                      + transaction);
        }

        transaction.commit();
        clearCurrentTransaction();
    }

    /**
     * Roll back the transaction associated with the current thread.
     *
     * @throws TransactionException If no transaction is present, or if the
     *                              current transaciton is inactive
     */
    public static void rollbackTransaction() throws TransactionException {
        ITransaction transaction = getCurrentTransaction();

        if (LOG.isDebugEnabled()) {
            LOG.debug("rollbackTransaction: Retrieved the following transaction"
                      + " " + transaction);
        }

        ensureActive(transaction);

        if (LOG.isDebugEnabled()) {
            LOG.debug("rollbackTransaction: Commiting this transaction "
                      + transaction);
        }

        transaction.rollback();
        clearCurrentTransaction();
    }

    /**
     * Get the transaction being used by the current thread.
     *
     * @return The thread's transaction
     */
    private static ITransaction getCurrentTransaction() {
        return (ITransaction) TL.get();
    }

    /**
     * Set a transaction onto the currently running thread.
     *
     * @param transaction The transaction to be set
     */
    private static void setCurrentTransaction(ITransaction transaction) {
        TL.set(transaction);
    }

    /**
     * Clear the current transaction from the thread.
     */
    private static void clearCurrentTransaction() {
        TL.set(null);
    }

    /**
     * Ensure that a transaction is active.  This will throw an exception if
     * the transaction parameter is either null or inactive.
     *
     * @param transaction The transaction to be checked
     * @throws TransactionException If the transaction is null or inactive
     */
    private static void ensureActive(ITransaction transaction)
                                                   throws TransactionException {
        if (LOG.isDebugEnabled()) {
            LOG.debug("ensureActive: Ensuring that the following transaction"
                      + " is active " + transaction);
        }

        if (transaction == null) {
            LOG.error("No transaction present");
            throw new TransactionException("No transaction present");
        } else if (!transaction.isActive()) {
            LOG.error("Transaction is inactive");
            throw new TransactionException("Transaction is inactive");
        }
    }

    /**
     * Create a new, inactive transaction instance.
     *
     * @return The new transaction
     * @throws TransactionException If there is an error creating the
     *                              transaction
     */
    private static ITransaction createNewTransaction()
                                                   throws TransactionException {
        String className = ITransaction.class.getName();
        ITransaction transaction = null;

        if (LOG.isDebugEnabled()) {
            LOG.debug("createNewTransaction: Creating a new transaction of"
                      + " class " + className);
        }

        try {
            ObjectFactory factory = ObjectFactory.getInstance();
            transaction = (ITransaction) factory.createObject(className);
        } catch (Exception ex) {
            LOG.error("Unable to create a transaction", ex);
            throw new TransactionException("Unable to create a transaction",
                                           ex);
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("createNewTransaction: Created the following"
                      + " transaction " + transaction);
        }

        return transaction;
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -