Example usage for org.springframework.transaction.support TransactionSynchronizationManager isSynchronizationActive

List of usage examples for org.springframework.transaction.support TransactionSynchronizationManager isSynchronizationActive

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionSynchronizationManager isSynchronizationActive.

Prototype

public static boolean isSynchronizationActive() 

Source Link

Document

Return if transaction synchronization is active for the current thread.

Usage

From source file:de.codecentric.batch.metrics.BatchMetricsImpl.java

@Override
public void decrement(String metricName, Long value) {
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        initializeMetricContainerAndRegisterTransactionSynchronizationIfNecessary();
        metricContainer.get().metrics.add(Pair.of(metricName, -value));
    } else {//from  ww  w .j  a v  a  2  s  .  c o  m
        decrementNonTransactional(metricName, value);
    }
}

From source file:org.vader.common.spring.TransactionScope.java

@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
    LOG.debug("Get bean={} from transaction scope", name);
    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
        switch (nonTransactionalBehaviour) {
        case PROTOTYPE:
            return objectFactory.getObject();
        case NOT_ALLOWED:
        default:/*from  w ww.  j  ava  2s .co m*/
            throw new IllegalStateException(String.format(
                    "Unable to create bean=%s within transaction scope. No active transaction found", name));
        }
    }
    final ScopeEntry entry = getOrCreateScopeEntry(name);
    if (entry.getBean() != null) {
        LOG.debug("Returns existing bean={} from transaction scope", name);
        return entry.getBean();
    }
    LOG.debug("Creates new bean={} from transaction scope", name);
    final Object newBean = objectFactory.getObject();
    getCurrentScope().get(name).setBean(newBean);
    return newBean;
}

From source file:de.codecentric.batch.metrics.BatchMetricsImpl.java

@Override
public void reset(String metricName) {
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        initializeMetricContainerAndRegisterTransactionSynchronizationIfNecessary();
        metricContainer.get().metrics.add(Pair.of(metricName, (Number) null));
    } else {/* w w  w.  j ava 2 s  .  co  m*/
        resetNonTransactional(metricName);
    }
}

From source file:org.springextensions.neodatis.NeoDatisTransactionManagerTest.java

@Test
public void testTransactionRollback() {
    final ODB odb = Mockito.mock(ODB.class);
    Mockito.when(odb.store(Mockito.isNull())).thenThrow(new RuntimeException());
    PlatformTransactionManager tm = new NeoDatisTransactionManager(odb);
    TransactionTemplate tmpl = new TransactionTemplate(tm);

    Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb));
    Assert.assertFalse("There should no active synchronizations",
            TransactionSynchronizationManager.isSynchronizationActive());

    try {/*from w  ww  .  j  a va  2  s . co m*/
        tmpl.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                Assert.assertTrue(TransactionSynchronizationManager.hasResource(odb));
                NeoDatisTemplate neoDatisTemplate = new NeoDatisTemplate(odb);
                neoDatisTemplate.store(null);
            }
        });
    } catch (RuntimeException e) {
        // is ok
    }

    Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb));
    Assert.assertFalse("There should no active synchronizations",
            TransactionSynchronizationManager.isSynchronizationActive());

    Mockito.verify(odb, Mockito.times(1)).rollback();
}

From source file:de.codecentric.batch.metrics.BatchMetricsImpl.java

@Override
public void submit(String metricName, double value) {
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        initializeMetricContainerAndRegisterTransactionSynchronizationIfNecessary();
        metricContainer.get().metrics.add(Pair.of(metricName, value));
    } else {/*  w  ww . j a va 2s  . c  o  m*/
        set(metricName, value);
    }
}

From source file:com.github.rholder.spring.transaction.TransactionBindingSupport.java

/**
 * Get a unique identifier associated with each transaction of each thread.  Null is returned if
 * no transaction is currently active.//  w w w.j  av  a2  s  .c o  m
 * 
 * @return Returns the transaction ID, or null if no transaction is present
 */
public static String getTransactionId() {
    /*
     * Go direct to the synchronizations as we don't want to register a resource if one doesn't exist.
     * This method is heavily used, so the simple Map lookup on the ThreadLocal is the fastest.
     */

    TransactionSynchronizationImpl txnSynch = (TransactionSynchronizationImpl) TransactionSynchronizationManager
            .getResource(RESOURCE_KEY_TXN_SYNCH);
    if (txnSynch == null) {
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            // need to lazily register synchronizations
            return registerSynchronizations().getTransactionId();
        } else {
            return null; // not in a transaction
        }
    } else {
        return txnSynch.getTransactionId();
    }
}

From source file:org.springextensions.db4o.Db4oTransactionManagerTest.java

@Test
public void testTransactionRollback() throws Exception {
    final ExtObjectContainer container = mock(ExtObjectContainer.class);
    when(container.identity()).thenReturn(null);
    when(container.ext()).thenReturn(container);

    PlatformTransactionManager tm = new Db4oTransactionManager(container);
    TransactionTemplate tt = new TransactionTemplate(tm);

    Assert.assertTrue(!TransactionSynchronizationManager.hasResource(container), "Has no container");
    Assert.assertTrue(!TransactionSynchronizationManager.isSynchronizationActive(),
            "JTA synchronizations not active");

    try {//  ww w  .j  a  v a 2 s.c o  m
        tt.execute(new TransactionCallbackWithoutResult() {
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                Assert.assertTrue(TransactionSynchronizationManager.hasResource(container),
                        "Has thread session");
                Db4oTemplate template = new Db4oTemplate(container);
                template.execute(new Db4oCallback() {
                    public Object doInDb4o(ObjectContainer cont) {
                        cont.ext().identity();
                        throw new RuntimeException();
                    }

                });
            }
        });
    } catch (RuntimeException e) {
        // it's okay
    }

    Assert.assertTrue(!TransactionSynchronizationManager.hasResource(container), "Has no container");
    Assert.assertTrue(!TransactionSynchronizationManager.isSynchronizationActive(),
            "JTA synchronizations not active");

    verify(container).rollback();
}

From source file:org.motechproject.server.omod.advice.PatientAdvice.java

/**
 * @see org.springframework.aop.AfterReturningAdvice#afterReturning(java.lang.Object,
 *      java.lang.reflect.Method, java.lang.Object[], java.lang.Object)
 *///from  w w w . j  a v  a  2  s.co  m
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
    log.debug("intercepting method invocation" + method.getName());
    Patient patient = (Patient) returnValue;
    ScheduleMaintService schedService = contextService.getScheduleMaintService();

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        schedService.addAffectedPatient(patient.getId());
        schedService.requestSynch();
    } else {
        // FIXME: Remove this when advice can exec in tx
        schedService.updateSchedule(patient.getId());
    }
}

From source file:org.motechproject.server.omod.advice.EncounterAdvice.java

/**
 * @see org.springframework.aop.AfterReturningAdvice#afterReturning(java.lang.Object,
 *      java.lang.reflect.Method, java.lang.Object[], java.lang.Object)
 *///from   w  w w .  ja  v a2s .  c  o  m
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
    log.debug("intercepting method invocation: " + method.getName());
    Encounter encounter = (Encounter) returnValue;
    Patient patient = encounter.getPatient();
    ScheduleMaintService scheduleService = contextService.getScheduleMaintService();

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        scheduleService.addAffectedPatient(patient.getId());
        scheduleService.requestSynch();
    } else {
        // FIXME: Remove this when advice can exec in tx
        scheduleService.updateSchedule(patient.getId());
    }
}

From source file:org.vader.common.spring.TransactionScope.java

@Override
public Object remove(String name) {
    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
        switch (nonTransactionalBehaviour) {
        case PROTOTYPE:
            break;
        case NOT_ALLOWED:
        default://from ww  w.j a  va  2 s .c o  m
            throw new IllegalStateException(String.format(
                    "Unable to remove bean=%s within transaction scope. No active transaction found", name));
        }
    }
    return getCurrentScope().remove(name);
}