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

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

Introduction

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

Prototype

public static boolean isActualTransactionActive() 

Source Link

Document

Return whether there currently is an actual transaction active.

Usage

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

@After
public void verifyTransactionSynchronizationManagerState() {
    assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    assertNull(TransactionSynchronizationManager.getCurrentTransactionName());
    assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
    assertNull(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel());
    assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
}

From source file:org.kbac.spring.scope.TransactionScope.java

private String getCurrentTransactionId() {
    final String currentTransactionId;
    if (TransactionSynchronizationManager.isActualTransactionActive()) {
        NamedTransactionSynchronisation currentSynchronisation = null;
        for (TransactionSynchronization sync : TransactionSynchronizationManager.getSynchronizations()) {
            if (sync instanceof NamedTransactionSynchronisation) {
                currentSynchronisation = (NamedTransactionSynchronisation) sync;
                break;
            }//  ww  w. j av  a2 s .  com
        }

        if (currentSynchronisation != null) {
            currentTransactionId = currentSynchronisation.transactionId;
        } else {
            currentTransactionId = formatTransactionId(
                    TransactionSynchronizationManager.getCurrentTransactionName());
        }
    } else {
        currentTransactionId = null;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("using current transaction name [" + currentTransactionId + "]");
    }

    return currentTransactionId;
}

From source file:org.exitcode.spring.torque.tx.SpringTransactionManagerAdapter.java

private boolean isSpringTxOpened() {
    return TransactionSynchronizationManager.isActualTransactionActive();
}

From source file:de.metas.procurement.webui.event.MFEventBus.java

private final PostAfterCommitCollector getPostAfterCommit() {
    if (!TransactionSynchronizationManager.isActualTransactionActive()) {
        return null;
    }//from w  w w .ja v  a 2s .  com

    PostAfterCommitCollector instance = null;
    for (final TransactionSynchronization sync : TransactionSynchronizationManager.getSynchronizations()) {
        if (sync instanceof PostAfterCommitCollector) {
            instance = (PostAfterCommitCollector) sync;
            logger.debug("Found PostAfterCommitCollector instance: {}", instance);
        }
    }

    if (instance == null) {
        instance = new PostAfterCommitCollector();
        TransactionSynchronizationManager.registerSynchronization(instance);

        logger.debug("Registered synchronization: {}", instance);
    }

    return instance;
}

From source file:org.grails.orm.hibernate.GrailsHibernateTemplate.java

protected boolean shouldPassReadOnlyToHibernate() {
    if ((passReadOnlyToHibernate || osivReadOnly)
            && TransactionSynchronizationManager.hasResource(getSessionFactory())) {
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            return passReadOnlyToHibernate && TransactionSynchronizationManager.isCurrentTransactionReadOnly();
        } else {//w ww .  j a  v a  2  s  .co  m
            return osivReadOnly;
        }
    } else {
        return false;
    }
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

private void doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(final boolean requiresNew,
        boolean notSupported) throws Exception {

    if (notSupported) {
        given(userTransaction.getStatus()).willReturn(Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION,
                Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
        given(transactionManager.suspend()).willReturn(transaction);
    } else {// w w  w.  j a  v a2 s. co  m
        given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
                Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
    }

    final ContentSource contentSource = mock(ContentSource.class);
    final Session session1 = mock(Session.class);
    final Session session2 = mock(Session.class);
    given(contentSource.newSession()).willReturn(session1, session2);

    final JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.setPropagationBehavior(notSupported ? TransactionDefinition.PROPAGATION_NOT_SUPPORTED
            : TransactionDefinition.PROPAGATION_SUPPORTS);

    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            assertSame(session1, ContentSourceUtils.getSession(contentSource));
            assertSame(session1, ContentSourceUtils.getSession(contentSource));

            TransactionTemplate tt2 = new TransactionTemplate(ptm);
            tt2.setPropagationBehavior(requiresNew ? TransactionDefinition.PROPAGATION_REQUIRES_NEW
                    : TransactionDefinition.PROPAGATION_REQUIRED);
            tt2.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
                    assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
                    assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
                    assertSame(session2, ContentSourceUtils.getSession(contentSource));
                    assertSame(session2, ContentSourceUtils.getSession(contentSource));
                }
            });

            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            assertSame(session1, ContentSourceUtils.getSession(contentSource));
        }
    });
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    verify(userTransaction).begin();
    verify(userTransaction).commit();
    if (notSupported) {
        verify(transactionManager).resume(transaction);
    }
    verify(session2).close();
    verify(session1).close();
}

From source file:de.metas.procurement.webui.sync.ServerSyncService.java

@Override
public ISyncAfterCommitCollector syncAfterCommit() {
    if (!TransactionSynchronizationManager.isActualTransactionActive()) {
        throw new RuntimeException("Not in transaction");
    }//  ww w . j av  a 2s  .c om

    SyncAfterCommit instance = null;
    for (final TransactionSynchronization sync : TransactionSynchronizationManager.getSynchronizations()) {
        if (sync instanceof SyncAfterCommit) {
            instance = (SyncAfterCommit) sync;
            logger.debug("Found SyncAfterCommit instance: {}", instance);
        }
    }

    if (instance == null) {
        instance = new SyncAfterCommit();
        TransactionSynchronizationManager.registerSynchronization(instance);

        logger.debug("Registered synchronization: {}", instance);
    }

    return instance;
}

From source file:org.openvpms.component.business.dao.hibernate.im.lookup.LookupReplacer.java

/**
 * Executes an update query.//from w  ww  .  j a v a2  s . c  om
 * <p/>
 * If any updates are made, the second level caches associated with the persisent classes are also cleared.
 * <p/>
 * <strong>NOTE</strong>: There is a small window where the second level cache will not reflect the state of the
 * database.
 *
 * @param query             the update query
 * @param session           the hibernate session
 * @param persistentClasses the persistent classes affected by the update
 */
private void executeUpdate(Query query, final Session session, final Class... persistentClasses) {
    int updates = query.executeUpdate();
    if (updates != 0) {
        final SessionFactory factory = session.getSessionFactory();
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            // clear the cache when the transaction commits
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCompletion(int status) {
                    if (status == STATUS_COMMITTED) {
                        clearCaches(persistentClasses, factory);
                    }
                }
            });
        } else {
            clearCaches(persistentClasses, factory);
        }
    }
}

From source file:org.openvpms.component.business.service.archetype.ArchetypeService.java

/**
 * Updates the descriptor cache. If a transaction is in progress, the
 * cache will only be updated on transaction commit. This means that the
 * descriptor will only be available via the <em>get*Descriptor</em> methods
 * on successful commit./*from   ww w. j ava 2  s.co  m*/
 *
 * @param object the object to add to the cache
 */
private void updateCache(final IMObject object) {
    if (TransactionSynchronizationManager.isActualTransactionActive()) {
        // update the cache when the transaction commits
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCompletion(int status) {
                if (status == STATUS_COMMITTED) {
                    addToCache(object);
                }
            }
        });
    } else {
        addToCache(object);
    }
}

From source file:nl.nn.adapterframework.receivers.ReceiverBase.java

private String processMessageInAdapter(IListener origin, Object rawMessage, String message, String messageId,
        String technicalCorrelationId, Map threadContext, long waitingDuration, boolean manualRetry)
        throws ListenerException {
    String result = null;/* ww w  .j a v  a 2  s.com*/
    PipeLineResult pipeLineResult = null;
    long startProcessingTimestamp = System.currentTimeMillis();
    //      if (message==null) {
    //         requestSizeStatistics.addValue(0);
    //      } else {
    //         requestSizeStatistics.addValue(message.length());
    //      }
    lastMessageDate = startProcessingTimestamp;
    log.debug(getLogPrefix() + "received message with messageId [" + messageId + "] (technical) correlationId ["
            + technicalCorrelationId + "]");

    if (StringUtils.isEmpty(messageId)) {
        messageId = Misc.createSimpleUUID();
        if (log.isDebugEnabled())
            log.debug(getLogPrefix() + "generated messageId [" + messageId + "]");
    }

    if (getChompCharSize() != null || getElementToMove() != null || getElementToMoveChain() != null) {
        log.debug(getLogPrefix() + "compact received message");
        try {
            InputStream xmlInput = IOUtils.toInputStream(message, "UTF-8");
            CompactSaxHandler handler = new CompactSaxHandler();
            handler.setChompCharSize(getChompCharSize());
            handler.setElementToMove(getElementToMove());
            handler.setElementToMoveChain(getElementToMoveChain());
            handler.setElementToMoveSessionKey(getElementToMoveSessionKey());
            handler.setRemoveCompactMsgNamespaces(isRemoveCompactMsgNamespaces());
            if (threadContext != null) {
                handler.setContext(threadContext);
            }
            SAXParserFactory parserFactory = XmlUtils.getSAXParserFactory();
            parserFactory.setNamespaceAware(true);
            SAXParser saxParser = parserFactory.newSAXParser();
            try {
                saxParser.parse(xmlInput, handler);
                message = handler.getXmlString();
            } catch (Exception e) {
                warn("received message could not be compacted: " + e.getMessage());
            }
            handler = null;
        } catch (Exception e) {
            throw new ListenerException(
                    "error during compacting received message to more compact format: " + e.getMessage());
        }
    }

    String businessCorrelationId = null;
    if (correlationIDTp != null) {
        try {
            businessCorrelationId = correlationIDTp.transform(message, null);
        } catch (Exception e) {
            //throw new ListenerException(getLogPrefix()+"could not extract businessCorrelationId",e);
            log.warn(getLogPrefix() + "could not extract businessCorrelationId");
        }
        if (StringUtils.isEmpty(businessCorrelationId)) {
            String cidText;
            if (StringUtils.isNotEmpty(getCorrelationIDXPath())) {
                cidText = "xpathExpression [" + getCorrelationIDXPath() + "]";
            } else {
                cidText = "styleSheet [" + getCorrelationIDStyleSheet() + "]";
            }
            if (StringUtils.isNotEmpty(technicalCorrelationId)) {
                log.info(getLogPrefix() + "did not find correlationId using " + cidText
                        + ", reverting to correlationId of transfer [" + technicalCorrelationId + "]");
                businessCorrelationId = technicalCorrelationId;
            }
        }
    } else {
        businessCorrelationId = technicalCorrelationId;
    }
    if (StringUtils.isEmpty(businessCorrelationId)) {
        if (StringUtils.isNotEmpty(messageId)) {
            log.info(getLogPrefix() + "did not find (technical) correlationId, reverting to messageId ["
                    + messageId + "]");
            businessCorrelationId = messageId;
        }
    }
    log.info(getLogPrefix() + "messageId [" + messageId + "] technicalCorrelationId [" + technicalCorrelationId
            + "] businessCorrelationId [" + businessCorrelationId + "]");
    threadContext.put(IPipeLineSession.businessCorrelationIdKey, businessCorrelationId);
    String label = null;
    if (labelTp != null) {
        try {
            label = labelTp.transform(message, null);
        } catch (Exception e) {
            //throw new ListenerException(getLogPrefix()+"could not extract label",e);
            log.warn(getLogPrefix() + "could not extract label: (" + ClassUtils.nameOf(e) + ") "
                    + e.getMessage());
        }
    }
    if (hasProblematicHistory(messageId, manualRetry, rawMessage, message, threadContext,
            businessCorrelationId)) {
        if (!isTransacted()) {
            log.warn(getLogPrefix() + "received message with messageId [" + messageId
                    + "] which has a problematic history; aborting processing");
        }
        numRejected.increase();
        return result;
    }
    if (isDuplicateAndSkip(getMessageLog(), messageId, businessCorrelationId)) {
        numRejected.increase();
        return result;
    }
    if (getCachedProcessResult(messageId) != null) {
        numRetried.increase();
    }

    int txOption = this.getTransactionAttributeNum();
    TransactionDefinition txDef = SpringTxManagerProxy.getTransactionDefinition(txOption,
            getTransactionTimeout());
    //TransactionStatus txStatus = txManager.getTransaction(txDef);
    IbisTransaction itx = new IbisTransaction(txManager, txDef, "receiver [" + getName() + "]");
    TransactionStatus txStatus = itx.getStatus();

    // update processing statistics
    // count in processing statistics includes messages that are rolled back to input
    startProcessingMessage(waitingDuration);

    IPipeLineSession pipelineSession = null;
    String errorMessage = "";
    boolean messageInError = false;
    try {
        String pipelineMessage;
        if (origin instanceof IBulkDataListener) {
            try {
                IBulkDataListener bdl = (IBulkDataListener) origin;
                pipelineMessage = bdl.retrieveBulkData(rawMessage, message, threadContext);
            } catch (Throwable t) {
                errorMessage = t.getMessage();
                messageInError = true;
                ListenerException l = wrapExceptionAsListenerException(t);
                throw l;
            }
        } else {
            pipelineMessage = message;
        }

        numReceived.increase();
        // Note: errorMessage is used to pass value from catch-clause to finally-clause!
        pipelineSession = createProcessingContext(businessCorrelationId, threadContext, messageId);
        //         threadContext=pipelineSession; // this is to enable Listeners to use session variables, for instance in afterProcessMessage()
        try {
            if (getMessageLog() != null) {
                getMessageLog().storeMessage(messageId, businessCorrelationId, new Date(),
                        RCV_MESSAGE_LOG_COMMENTS, label, pipelineMessage);
            }
            log.debug(getLogPrefix() + "preparing TimeoutGuard");
            TimeoutGuard tg = new TimeoutGuard("Receiver " + getName());
            try {
                if (log.isDebugEnabled())
                    log.debug(getLogPrefix() + "activating TimeoutGuard with transactionTimeout ["
                            + transactionTimeout + "]s");
                tg.activateGuard(getTransactionTimeout());
                pipeLineResult = adapter.processMessageWithExceptions(businessCorrelationId, pipelineMessage,
                        pipelineSession);
                pipelineSession.put("exitcode", "" + pipeLineResult.getExitCode());
                result = pipeLineResult.getResult();
                errorMessage = "exitState [" + pipeLineResult.getState() + "], result [" + result + "]";
                if (log.isDebugEnabled()) {
                    log.debug(getLogPrefix() + "received result: " + errorMessage);
                }
                messageInError = txStatus.isRollbackOnly();
            } finally {
                log.debug(getLogPrefix() + "canceling TimeoutGuard, isInterrupted ["
                        + Thread.currentThread().isInterrupted() + "]");
                if (tg.cancel()) {
                    errorMessage = "timeout exceeded";
                    if (StringUtils.isEmpty(result)) {
                        result = "<timeout/>";
                    }
                    messageInError = true;
                }
            }
            if (!messageInError && !isTransacted()) {
                String commitOnState = ((Adapter) adapter).getPipeLine().getCommitOnState();

                if (StringUtils.isNotEmpty(commitOnState)
                        && !commitOnState.equalsIgnoreCase(pipeLineResult.getState())) {
                    messageInError = true;
                }
            }
        } catch (Throwable t) {
            if (TransactionSynchronizationManager.isActualTransactionActive()) {
                log.debug("<*>" + getLogPrefix() + "TX Update: Received failure, transaction "
                        + (txStatus.isRollbackOnly() ? "already" : "not yet") + " marked for rollback-only");
            }
            errorMessage = t.getMessage();
            messageInError = true;
            if (pipeLineResult == null) {
                pipeLineResult = new PipeLineResult();
            }
            if (StringUtils.isEmpty(pipeLineResult.getResult())) {
                String formattedErrorMessage = adapter.formatErrorMessage("exception caught", t, message,
                        messageId, this, startProcessingTimestamp);
                pipeLineResult.setResult(formattedErrorMessage);
            }
            ListenerException l = wrapExceptionAsListenerException(t);
            throw l;
        } finally {
            putSessionKeysIntoThreadContext(threadContext, pipelineSession);
        }
        //         if (result==null) {
        //            responseSizeStatistics.addValue(0);
        //         } else {
        //            responseSizeStatistics.addValue(result.length());
        //         }
        if (getSender() != null) {
            String sendMsg = sendResultToSender(technicalCorrelationId, result);
            if (sendMsg != null) {
                errorMessage = sendMsg;
            }
        }
    } finally {
        cacheProcessResult(messageId, businessCorrelationId, errorMessage, new Date(startProcessingTimestamp));
        if (!isTransacted() && messageInError) {
            if (!manualRetry) {
                moveInProcessToError(messageId, businessCorrelationId, message,
                        new Date(startProcessingTimestamp), errorMessage, rawMessage, TXNEW_CTRL);
            }
        }
        try {
            Map afterMessageProcessedMap;
            if (threadContext != null) {
                afterMessageProcessedMap = threadContext;
                if (pipelineSession != null) {
                    threadContext.putAll(pipelineSession);
                }
            } else {
                afterMessageProcessedMap = pipelineSession;
            }
            origin.afterMessageProcessed(pipeLineResult, rawMessage, afterMessageProcessedMap);
        } finally {
            long finishProcessingTimestamp = System.currentTimeMillis();
            finishProcessingMessage(finishProcessingTimestamp - startProcessingTimestamp);
            if (!txStatus.isCompleted()) {
                // NB: Spring will take care of executing a commit or a rollback;
                // Spring will also ONLY commit the transaction if it was newly created
                // by the above call to txManager.getTransaction().
                //txManager.commit(txStatus);
                itx.commit();
            } else {
                throw new ListenerException(
                        getLogPrefix() + "Transaction already completed; we didn't expect this");
            }
        }
    }
    if (log.isDebugEnabled())
        log.debug(getLogPrefix() + "messageId [" + messageId + "] correlationId [" + businessCorrelationId
                + "] returning result [" + result + "]");
    return result;
}