001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Stephane Lacoin
011 */
012package org.nuxeo.ecm.core.test;
013
014import org.apache.log4j.Logger;
015import org.nuxeo.ecm.core.repository.RepositoryFactory;
016import org.nuxeo.ecm.core.storage.sql.ra.PoolingRepositoryFactory;
017import org.nuxeo.ecm.core.test.annotations.Granularity;
018import org.nuxeo.ecm.core.test.annotations.RepositoryConfig;
019import org.nuxeo.ecm.core.test.annotations.TransactionalConfig;
020import org.nuxeo.runtime.test.runner.ContainerFeature;
021import org.nuxeo.runtime.test.runner.Features;
022import org.nuxeo.runtime.test.runner.FeaturesRunner;
023import org.nuxeo.runtime.test.runner.SimpleFeature;
024import org.nuxeo.runtime.transaction.TransactionHelper;
025
026@RepositoryConfig(cleanup = Granularity.METHOD, repositoryFactoryClass = PoolingRepositoryFactory.class)
027@Features(ContainerFeature.class)
028public class TransactionalFeature extends SimpleFeature {
029
030    protected TransactionalConfig config;
031
032    protected String autoactivationValue;
033
034    protected boolean nsOwner;
035
036    protected boolean txStarted;
037
038    protected Class<? extends RepositoryFactory> defaultFactory;
039
040    @Override
041    public void initialize(FeaturesRunner runner) throws Exception {
042        config = runner.getConfig(TransactionalConfig.class);
043    }
044
045    @Override
046    public void beforeSetup(FeaturesRunner runner) throws Exception {
047        if (config.autoStart() == false) {
048            return;
049        }
050        txStarted = TransactionHelper.startTransaction();
051    }
052
053    @Override
054    public void afterTeardown(FeaturesRunner runner) throws Exception {
055        if (txStarted == false) {
056            if (TransactionHelper.isTransactionActive()) {
057                try {
058                    TransactionHelper.setTransactionRollbackOnly();
059                    TransactionHelper.commitOrRollbackTransaction();
060                } finally {
061                    Logger.getLogger(TransactionalFeature.class).warn(
062                            "Committing a transaction for your, please do it yourself");
063                }
064            }
065            return;
066        }
067        TransactionHelper.commitOrRollbackTransaction();
068    }
069
070}