Example usage for javax.transaction Status STATUS_ACTIVE

List of usage examples for javax.transaction Status STATUS_ACTIVE

Introduction

In this page you can find the example usage for javax.transaction Status STATUS_ACTIVE.

Prototype

int STATUS_ACTIVE

To view the source code for javax.transaction Status STATUS_ACTIVE.

Click Source Link

Document

A transaction is associated with the target object and it is in the active state.

Usage

From source file:com.baomidou.hibernateplus.HibernateConfigurableJtaPlatform.java

@Override
public boolean canRegisterSynchronization() {
    try {/*from  ww  w  . j  a  v a  2 s .c o m*/
        return (this.transactionManager.getStatus() == Status.STATUS_ACTIVE);
    } catch (SystemException ex) {
        throw new TransactionException("Could not determine JTA transaction status", ex);
    }
}

From source file:org.alfresco.util.transaction.SpringAwareUserTransactionTest.java

public void testSimpleTxnWithCommit() throws Throwable {
    testNoTxnStatus();//from  w  w w  .j  av  a  2 s. c  o  m
    try {
        txn.begin();
        assertEquals("Transaction status is not correct", Status.STATUS_ACTIVE, txn.getStatus());
        assertEquals("Transaction manager not called correctly", txn.getStatus(),
                transactionManager.getStatus());

        txn.commit();
        assertEquals("Transaction status is not correct", Status.STATUS_COMMITTED, txn.getStatus());
        assertEquals("Transaction manager not called correctly", txn.getStatus(),
                transactionManager.getStatus());
    } catch (Throwable e) {
        // unexpected exception - attempt a cleanup
        try {
            txn.rollback();
        } catch (Throwable ee) {
            e.printStackTrace();
        }
        throw e;
    }
    checkNoStatusOnThread();
}

From source file:org.apache.servicemix.transaction.GeronimoPlatformTransactionManager.java

protected void registerTransactionAssociationListener() {
    addTransactionAssociationListener(new TransactionManagerMonitor() {
        public void threadAssociated(Transaction transaction) {
            try {
                if (transaction.getStatus() == Status.STATUS_ACTIVE) {
                    SuspendedResourcesHolder holder = suspendedResources.remove(transaction);
                    if (holder != null && holder.getSuspendedSynchronizations() != null) {
                        TransactionSynchronizationManager.setActualTransactionActive(true);
                        TransactionSynchronizationManager.setCurrentTransactionReadOnly(holder.isReadOnly());
                        TransactionSynchronizationManager.setCurrentTransactionName(holder.getName());
                        TransactionSynchronizationManager.initSynchronization();
                        for (Iterator<?> it = holder.getSuspendedSynchronizations().iterator(); it.hasNext();) {
                            TransactionSynchronization synchronization = (TransactionSynchronization) it.next();
                            synchronization.resume();
                            TransactionSynchronizationManager.registerSynchronization(synchronization);
                        }/*from w  ww  .j  av a  2 s. co m*/
                    }
                }
            } catch (SystemException e) {
                return;
            }
        }

        public void threadUnassociated(Transaction transaction) {
            try {
                if (transaction.getStatus() == Status.STATUS_ACTIVE) {
                    if (TransactionSynchronizationManager.isSynchronizationActive()) {
                        List<?> suspendedSynchronizations = TransactionSynchronizationManager
                                .getSynchronizations();
                        for (Iterator<?> it = suspendedSynchronizations.iterator(); it.hasNext();) {
                            ((TransactionSynchronization) it.next()).suspend();
                        }
                        TransactionSynchronizationManager.clearSynchronization();
                        String name = TransactionSynchronizationManager.getCurrentTransactionName();
                        TransactionSynchronizationManager.setCurrentTransactionName(null);
                        boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
                        TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
                        TransactionSynchronizationManager.setActualTransactionActive(false);
                        SuspendedResourcesHolder holder = new SuspendedResourcesHolder(null,
                                suspendedSynchronizations, name, readOnly);
                        suspendedResources.put(transaction, holder);
                    }
                }
            } catch (SystemException e) {
                return;
            }
        }
    });
}

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

private void doTestJtaTransaction(final boolean rollback) throws Exception {
    if (rollback) {
        given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE);
    } else {//from  w w  w . ja  v a 2 s .  c  o  m
        given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
                Status.STATUS_ACTIVE);
    }

    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(contentSource));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(contentSource));
            assertTrue("JTA synchronizations active",
                    TransactionSynchronizationManager.isSynchronizationActive());
            assertTrue("Is new transaction", status.isNewTransaction());

            Session c = ContentSourceUtils.getSession(contentSource);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(contentSource));
            ContentSourceUtils.releaseSession(c, contentSource);

            c = ContentSourceUtils.getSession(contentSource);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(contentSource));
            ContentSourceUtils.releaseSession(c, contentSource);

            if (rollback) {
                status.setRollbackOnly();
            }
        }
    });

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(contentSource));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
    verify(userTransaction).begin();
    if (rollback) {
        verify(userTransaction).rollback();
    }
    verify(session).close();
}

From source file:fr.ortolang.diffusion.runtime.engine.task.ImportHandlesTask.java

@Override
public void executeTask(DelegateExecution execution) throws RuntimeEngineTaskException {
    checkParameters(execution);/*from w w w . ja  va 2 s .c  o m*/
    String handlespath = execution.getVariable(HANDLES_PATH_PARAM_NAME, String.class);
    if (execution.getVariable(INITIER_PARAM_NAME, String.class)
            .equals(MembershipService.SUPERUSER_IDENTIFIER)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        try {
            if (getUserTransaction().getStatus() == Status.STATUS_NO_TRANSACTION) {
                LOGGER.log(Level.FINE, "starting new user transaction.");
                getUserTransaction().begin();
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "unable to start new user transaction", e);
        }
        try {
            boolean needcommit;
            long tscommit = System.currentTimeMillis();
            List<JsonHandle> handles = Arrays
                    .asList(mapper.readValue(new File(handlespath), JsonHandle[].class));
            LOGGER.log(Level.FINE, "- starting import handles");
            boolean partial = false;
            StringBuilder report = new StringBuilder();
            for (JsonHandle handle : handles) {
                needcommit = false;
                try {
                    getHandleStore().recordHandle(handle.handle, handle.key, handle.url);
                } catch (HandleStoreServiceException e) {
                    partial = true;
                    report.append("unable to import handle [").append(handle.handle).append("] : ")
                            .append(e.getMessage()).append("\r\n");
                }
                if (System.currentTimeMillis() - tscommit > 30000) {
                    LOGGER.log(Level.FINE, "current transaction exceed 30sec, need commit.");
                    needcommit = true;
                }
                try {
                    if (needcommit && getUserTransaction().getStatus() == Status.STATUS_ACTIVE) {
                        LOGGER.log(Level.FINE, "committing active user transaction.");
                        getUserTransaction().commit();
                        tscommit = System.currentTimeMillis();
                        getUserTransaction().begin();
                    }
                } catch (Exception e) {
                    LOGGER.log(Level.SEVERE, "unable to commit active user transaction", e);
                }
            }
            if (partial) {
                throwRuntimeEngineEvent(
                        RuntimeEngineEvent.createProcessLogEvent(execution.getProcessBusinessKey(),
                                "Some handles has not been imported (see trace for detail)"));
                throwRuntimeEngineEvent(RuntimeEngineEvent
                        .createProcessTraceEvent(execution.getProcessBusinessKey(), report.toString(), null));
            }
            throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessLogEvent(execution.getProcessBusinessKey(),
                    "Import Handles done"));
        } catch (IOException e) {
            throw new RuntimeEngineTaskException("error parsing json file: " + e.getMessage());
        }
    } else {
        throw new RuntimeEngineTaskException(
                "only " + MembershipService.SUPERUSER_IDENTIFIER + " can perform this task !!");
    }
}

From source file:com.surevine.alfresco.repo.delete.PerishabilityLogicImpl.java

private synchronized void loadPerishReasons()
        throws JSONException, SecurityException, IllegalStateException, RollbackException,
        HeuristicMixedException, HeuristicRollbackException, SystemException, NotSupportedException {
    UserTransaction transaction = null;//from w w  w.  j  a v  a  2  s . c  o m
    ResultSet rs = null;

    try {
        StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
        rs = _searchService.query(storeRef, SearchService.LANGUAGE_LUCENE,
                "PATH:\"/app:company_home/app:dictionary/cm:perishableReasons.json\"");
        NodeRef nodeRef = null;
        transaction = _transactionService.getUserTransaction(true);

        transaction.begin();

        if (rs.length() == 0) {
            _logger.error(
                    "Unable to load perishable reasons: Didn't find perishableReasons.json in the Data Dictionary.");
            perishReasons = Collections.emptyList();
            perishReasonsByCode = Collections.emptyMap();
            perishReasonsBySite = Collections.emptyMap();
            return;
        }
        nodeRef = rs.getNodeRef(0);

        ContentReader reader = _contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);

        JSONObject obj = new JSONObject(reader.getContentString());

        JSONArray perishableReasons = obj.getJSONArray("perishableReasons");

        perishReasons = new ArrayList<PerishReason>(perishableReasons.length());
        perishReasonsByCode = new HashMap<String, PerishReason>();
        perishReasonsBySite = new HashMap<String, List<PerishReason>>();

        for (int i = 0; i < perishableReasons.length(); ++i) {
            PerishReason reason = PerishReason.fromJSON(perishableReasons.getJSONObject(i));
            perishReasons.add(reason);
            perishReasonsByCode.put(reason.getCode(), reason);
            addPerishReasonBySite(reason);
        }

        transaction.commit();
    } finally {
        if (rs != null) {
            rs.close();
        }

        if ((transaction != null) && (transaction.getStatus() == Status.STATUS_ACTIVE)) {
            transaction.rollback();
        }
    }
}

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

protected void registerJtaSynchronization(Session session, SessionHolder sessionHolder) {

    // JTA synchronization is only possible with a javax.transaction.TransactionManager.
    // We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified
    // in Hibernate configuration, it will contain a TransactionManager reference.
    TransactionManager jtaTm = getJtaTransactionManager(session);
    if (jtaTm == null) {
        return;//from   w  w  w .  j a  v  a2s  .co m
    }

    try {
        Transaction jtaTx = jtaTm.getTransaction();
        if (jtaTx == null) {
            return;
        }

        int jtaStatus = jtaTx.getStatus();
        if (jtaStatus != Status.STATUS_ACTIVE && jtaStatus != Status.STATUS_MARKED_ROLLBACK) {
            return;
        }

        LOG.debug("Registering JTA transaction synchronization for new Hibernate Session");
        SessionHolder holderToUse = sessionHolder;
        // Register JTA Transaction with existing SessionHolder.
        // Create a new SessionHolder if none existed before.
        if (holderToUse == null) {
            holderToUse = new SessionHolder(session);
        } else {
            // it's up to the caller to manage concurrent sessions
            // holderToUse.addSession(session);
        }
        jtaTx.registerSynchronization(
                new SpringJtaSynchronizationAdapter(createSpringSessionSynchronization(holderToUse), jtaTm));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != sessionHolder) {
            TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse);
        }
    } catch (Throwable ex) {
        throw new DataAccessResourceFailureException(
                "Could not register synchronization with JTA TransactionManager", ex);
    }
}

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

private void doTestJtaTransactionWithPropagationRequiresNew(final boolean rollback,
        final boolean openOuterConnection, final boolean accessAfterResume,
        final boolean useTransactionAwareContentSource) throws Exception {

    given(transactionManager.suspend()).willReturn(transaction);
    if (rollback) {
        given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE);
    } else {//from   ww  w. jav  a  2s  .  c  om
        given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
                Status.STATUS_ACTIVE);
    }

    given(session.getTransactionMode()).willReturn(Session.TransactionMode.QUERY);

    final ContentSource dsToUse = useTransactionAwareContentSource
            ? new TransactionAwareContentSourceProxy(contentSource)
            : contentSource;

    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
    final TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(dsToUse));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(dsToUse));
            assertTrue("JTA synchronizations active",
                    TransactionSynchronizationManager.isSynchronizationActive());
            assertTrue("Is new transaction", status.isNewTransaction());

            Session s = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            s.getTransactionMode();
            ContentSourceUtils.releaseSession(s, dsToUse);

            s = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            if (!openOuterConnection) {
                ContentSourceUtils.releaseSession(s, dsToUse);
            }

            for (int i = 0; i < 5; i++) {

                tt.execute(new TransactionCallbackWithoutResult() {
                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus status)
                            throws RuntimeException {
                        assertTrue("Hasn't thread session",
                                !TransactionSynchronizationManager.hasResource(dsToUse));
                        assertTrue("JTA synchronizations active",
                                TransactionSynchronizationManager.isSynchronizationActive());
                        assertTrue("Is new transaction", status.isNewTransaction());

                        Session s = ContentSourceUtils.getSession(dsToUse);
                        s.getTransactionMode();
                        assertTrue("Has thread session",
                                TransactionSynchronizationManager.hasResource(dsToUse));
                        ContentSourceUtils.releaseSession(s, dsToUse);

                        s = ContentSourceUtils.getSession(dsToUse);
                        assertTrue("Has thread session",
                                TransactionSynchronizationManager.hasResource(dsToUse));
                        ContentSourceUtils.releaseSession(s, dsToUse);
                    }
                });

            }

            if (rollback) {
                status.setRollbackOnly();
            }

            if (accessAfterResume) {
                if (!openOuterConnection) {
                    s = ContentSourceUtils.getSession(dsToUse);
                }
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
                s.getTransactionMode();
                ContentSourceUtils.releaseSession(s, dsToUse);

                s = ContentSourceUtils.getSession(dsToUse);
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
                ContentSourceUtils.releaseSession(s, dsToUse);
            } else {
                if (openOuterConnection) {
                    ContentSourceUtils.releaseSession(s, dsToUse);
                }
            }
        }
    });

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(dsToUse));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
    verify(userTransaction, times(6)).begin();
    verify(transactionManager, times(5)).resume(transaction);
    if (rollback) {
        verify(userTransaction, times(5)).commit();
        verify(userTransaction).rollback();
    } else {
        verify(userTransaction, times(6)).commit();
    }
    if (accessAfterResume && !openOuterConnection) {
        verify(session, times(7)).close();
    } else {
        verify(session, times(6)).close();
    }
}

From source file:org.alfresco.util.transaction.SpringAwareUserTransaction.java

/**
 * Gets the current transaction info, or null if none exists.
 * <p>/*from   www  .  java2s  .  c  om*/
 * A check is done to ensure that the transaction info on the stack is exactly
 * the same instance used when this transaction was started.
 * The internal status is also checked against the transaction info.
 * These checks ensure that the transaction demarcation is done correctly and that
 * thread safety is adhered to.
 * 
 * @return Returns the current transaction
 */
private TransactionInfo getTransactionInfo() {
    // a few quick self-checks
    if (threadId < 0 && internalStatus != Status.STATUS_NO_TRANSACTION) {
        throw new RuntimeException("Transaction has been started but there is no thread ID");
    } else if (threadId >= 0 && internalStatus == Status.STATUS_NO_TRANSACTION) {
        throw new RuntimeException("Transaction has not been started but a thread ID has been recorded");
    }

    TransactionInfo txnInfo = null;
    try {
        txnInfo = TransactionAspectSupport.currentTransactionInfo();
        // we are in a transaction
    } catch (NoTransactionException e) {
        // No transaction.  It is possible that the transaction threw an exception during commit.
    }
    // perform checks for active transactions
    if (internalStatus == Status.STATUS_ACTIVE) {
        if (Thread.currentThread().getId() != threadId) {
            // the internally stored transaction info (retrieved in begin()) should match the info
            // on the thread
            throw new RuntimeException("UserTransaction may not be accessed by multiple threads");
        } else if (txnInfo == null) {
            // internally we recorded a transaction starting, but there is nothing on the thread
            throw new RuntimeException("Transaction boundaries have been made to overlap in the stack");
        } else if (txnInfo != internalTxnInfo) {
            // the transaction info on the stack isn't the one we started with
            throw new RuntimeException("UserTransaction begin/commit mismatch");
        }
    }
    return txnInfo;
}