001/*
002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Stephane Lacoin
018 */
019package org.nuxeo.ecm.core.test;
020
021import org.apache.log4j.Logger;
022import org.nuxeo.ecm.core.repository.RepositoryFactory;
023import org.nuxeo.ecm.core.test.annotations.Granularity;
024import org.nuxeo.ecm.core.test.annotations.RepositoryConfig;
025import org.nuxeo.ecm.core.test.annotations.TransactionalConfig;
026import org.nuxeo.runtime.test.runner.ContainerFeature;
027import org.nuxeo.runtime.test.runner.Features;
028import org.nuxeo.runtime.test.runner.FeaturesRunner;
029import org.nuxeo.runtime.test.runner.SimpleFeature;
030import org.nuxeo.runtime.transaction.TransactionHelper;
031
032@RepositoryConfig(cleanup = Granularity.METHOD)
033@Features(ContainerFeature.class)
034public class TransactionalFeature extends SimpleFeature {
035
036    protected TransactionalConfig config;
037
038    protected String autoactivationValue;
039
040    protected boolean nsOwner;
041
042    protected boolean txStarted;
043
044    protected Class<? extends RepositoryFactory> defaultFactory;
045
046    @Override
047    public void initialize(FeaturesRunner runner) throws Exception {
048        config = runner.getConfig(TransactionalConfig.class);
049    }
050
051    @Override
052    public void beforeSetup(FeaturesRunner runner) throws Exception {
053        if (config.autoStart() == false) {
054            return;
055        }
056        txStarted = TransactionHelper.startTransaction();
057    }
058
059    @Override
060    public void afterTeardown(FeaturesRunner runner) throws Exception {
061        if (txStarted == false) {
062            if (TransactionHelper.isTransactionActive()) {
063                try {
064                    TransactionHelper.setTransactionRollbackOnly();
065                    TransactionHelper.commitOrRollbackTransaction();
066                } finally {
067                    Logger.getLogger(TransactionalFeature.class).warn(
068                            "Committing a transaction for your, please do it yourself");
069                }
070            }
071            return;
072        }
073        TransactionHelper.commitOrRollbackTransaction();
074    }
075
076}