Example usage for javax.transaction Status STATUS_NO_TRANSACTION

List of usage examples for javax.transaction Status STATUS_NO_TRANSACTION

Introduction

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

Prototype

int STATUS_NO_TRANSACTION

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

Click Source Link

Document

No transaction is currently associated with the target object.

Usage

From source file:com.mg.framework.service.DatabaseAuditServiceImpl.java

public void loadAuditSetup() {
    boolean startTran = false;
    try {//  www. j  a v a  2 s  .  c o  m
        logger.info("load audit setup");

        startTran = ServerUtils.getTransactionManager().getStatus() == Status.STATUS_NO_TRANSACTION;
        if (startTran)
            ServerUtils.getTransactionManager().begin();

        List<PersistentObject> list = OrmTemplate.getInstance()
                .findByCriteria(OrmTemplate.createCriteria("com.mg.merp.core.model.DatabaseAuditSetup"));

        Lock lock = entityAuditSetupLock.writeLock();
        lock.lock();
        try {
            if (entityAuditSetup != null)
                entityAuditSetup.clear();

            for (PersistentObject item : list) {
                String entityName = (String) item.getAttribute("AuditedEntityName");
                EntityAuditSetup auditSetup = entityAuditSetup.get(entityName);
                if (auditSetup == null)
                    entityAuditSetup.put(entityName, new EntityAuditSetup(item));
                else
                    auditSetup.setAudit(item);
            }
        } finally {
            lock.unlock();
        }

        if (startTran)
            ServerUtils.getTransactionManager().commit();
    } catch (Exception e) {
        logger.error("load audit setup failed", e);
        try {
            if (startTran)
                ServerUtils.getTransactionManager().rollback();
        } catch (Exception ee) {
            logger.error("transaction rollback failed", ee);
        }
    }
}

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

public void testNoTxnStatus() throws Exception {
    checkNoStatusOnThread();//from  ww w  .j  av a 2s  .  co  m
    assertEquals("Transaction status is not correct", Status.STATUS_NO_TRANSACTION, txn.getStatus());
    assertEquals("Transaction manager not set up correctly", txn.getStatus(), transactionManager.getStatus());
}

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  va2 s  . co 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.impetus.kundera.persistence.jta.KunderaJTAUserTransaction.java

@Override
public int getStatus() throws SystemException {
    Transaction tx = threadLocal.get();//w  w  w  . j  a  v  a2  s. c  o  m
    if (tx == null) {
        return Status.STATUS_NO_TRANSACTION;
    }
    return tx.getStatus();
}

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 {/*w  ww  .  j  a v a  2  s .c  om*/
        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:gwap.game.quiz.PlayNCommunicationResource.java

/**
 * Sets up a new Quiz Game Session/*  ww  w.j  a v a2s .com*/
 * 
 * @return gameArray Array for JSON
 */
private JSONObject createJSONObjectForNewGame() {

    try {
        /*
         * setting up dummy JSF FacesContext
         */
        if (Transaction.instance().getStatus() == Status.STATUS_NO_TRANSACTION) {
            Transaction.instance().begin();
        }
        // Conversation.instance().begin();
        FacesContext facesContext = new FacesContextBuilder().getFacesContext(request, response,
                request.getSession());
        this.elc = facesContext.getELContext();

        this.elFactory = facesContext.getApplication().getExpressionFactory();

        ValueExpression mexp = elFactory.createValueExpression(elc, "#{quizSession}", QuizSessionBean.class);
        this.quizSessionBean = (QuizSessionBean) mexp.getValue(elc);
        ses.setAttribute("quizSession", quizSessionBean);

        JSONObject jsonResult = quizSessionBean.getJSONResult();

        facesContext.release();
        Transaction.instance().commit();

        return jsonResult;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

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

/**
 * Implementation required for {@link UserTransaction}.
 *///from  ww  w. j  a v a 2 s  . c o  m
public void setTransactionTimeout(int timeout) throws SystemException {
    if (internalStatus != Status.STATUS_NO_TRANSACTION) {
        throw new RuntimeException("Can only set the timeout before begin");
    }
    this.timeout = timeout;
}

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  w w w  .j a va2s .  co  m*/
        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   w  w w .  j  a v  a2s  .  co  m
 * 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;
}

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

public synchronized void setRollbackOnly() throws IllegalStateException, SystemException {
    // just a check
    TransactionInfo txnInfo = getTransactionInfo();

    int status = getStatus();
    // check the status
    if (status == Status.STATUS_MARKED_ROLLBACK) {
        // this is acceptable
    } else if (status == Status.STATUS_NO_TRANSACTION) {
        throw new IllegalStateException("The transaction has not been started yet");
    } else if (status == Status.STATUS_ROLLING_BACK || status == Status.STATUS_ROLLEDBACK) {
        throw new IllegalStateException("The transaction has already been rolled back");
    } else if (status == Status.STATUS_COMMITTING || status == Status.STATUS_COMMITTED) {
        throw new IllegalStateException("The transaction has already been committed");
    } else if (status != Status.STATUS_ACTIVE) {
        throw new IllegalStateException("The transaction is not active: " + status);
    }//from  w  w w . jav  a 2 s. c  o m

    // mark for rollback
    txnInfo.getTransactionStatus().setRollbackOnly();
    // make sure that we record the fact that we have been marked for rollback
    internalStatus = Status.STATUS_MARKED_ROLLBACK;
    // done
    if (logger.isDebugEnabled()) {
        logger.debug("Set transaction status to rollback only: " + this);
    }
}