List of usage examples for javax.transaction Status STATUS_MARKED_ROLLBACK
int STATUS_MARKED_ROLLBACK
To view the source code for javax.transaction Status STATUS_MARKED_ROLLBACK.
Click Source Link
From source file:org.alfresco.repo.transaction.RetryingTransactionHelper.java
/** * Execute a callback in a transaction until it succeeds, fails * because of an error not the result of an optimistic locking failure, * or a deadlock loser failure, or until a maximum number of retries have * been attempted./* ww w .jav a 2s . c om*/ * <p> * It is possible to force a new transaction to be created or to partake in * any existing transaction. * * @param cb The callback containing the unit of work. * @param readOnly Whether this is a read only transaction. * @param requiresNew <tt>true</tt> to force a new transaction or * <tt>false</tt> to partake in any existing transaction. * @return Returns the result of the unit of work. * @throws RuntimeException all checked exceptions are converted */ public <R> R doInTransaction(RetryingTransactionCallback<R> cb, boolean readOnly, boolean requiresNew) { // First validate the requiresNew setting if (!requiresNew) { TxnReadState readState = AlfrescoTransactionSupport.getTransactionReadState(); switch (readState) { case TXN_READ_ONLY: if (!readOnly) { // The current transaction is read-only, but a writable transaction is requested throw new AlfrescoRuntimeException( "Read-Write transaction started within read-only transaction"); } // We are in a read-only transaction and this is what we require so continue with it. break; case TXN_READ_WRITE: // We are in a read-write transaction. It cannot be downgraded so just continue with it. break; case TXN_NONE: // There is no current transaction so we need a new one. requiresNew = true; break; default: throw new RuntimeException("Unknown transaction state: " + readState); } } // If we need a new transaction, then we have to check that the read-write request can be served if (requiresNew) { if (this.readOnly && !readOnly) { throw new AccessDeniedException(MSG_READ_ONLY); } } // If we are time limiting, set ourselves a time limit and maintain the count of concurrent transactions long startTime = 0; Throwable stackTrace = null; if (requiresNew && maxExecutionMs > 0) { startTime = System.currentTimeMillis(); synchronized (this) { if (txnCount > 0) { // If this transaction would take us above our ceiling, reject it long oldestStart = txnsInProgress.firstKey(); long oldestDuration = startTime - oldestStart; if (oldestDuration > maxExecutionMs) { throw new TooBusyException("Too busy: " + txnCount + " transactions. Oldest " + oldestDuration + " milliseconds", txnsInProgress.get(oldestStart).get(0)); } } // Record the start time and stack trace of the starting thread List<Throwable> traces = txnsInProgress.get(startTime); if (traces == null) { traces = new LinkedList<Throwable>(); txnsInProgress.put(startTime, traces); } stackTrace = new Exception("Stack trace"); traces.add(stackTrace); ++txnCount; } } try { // Track the last exception caught, so that we // can throw it if we run out of retries. RuntimeException lastException = null; for (int count = 0; count == 0 || count < maxRetries; count++) { UserTransaction txn = null; try { if (requiresNew) { txn = txnService.getNonPropagatingUserTransaction(readOnly, forceWritable); txn.begin(); // Wrap it to protect it UserTransactionProtectionAdvise advise = new UserTransactionProtectionAdvise(); ProxyFactory proxyFactory = new ProxyFactory(txn); proxyFactory.addAdvice(advise); UserTransaction wrappedTxn = (UserTransaction) proxyFactory.getProxy(); // Store the UserTransaction for static retrieval. There is no need to unbind it // because the transaction management will do that for us. AlfrescoTransactionSupport.bindResource(KEY_ACTIVE_TRANSACTION, wrappedTxn); } // Do the work. R result = cb.execute(); // Only commit if we 'own' the transaction. if (txn != null) { if (txn.getStatus() == Status.STATUS_MARKED_ROLLBACK) { if (logger.isDebugEnabled()) { logger.debug("\n" + "Transaction marked for rollback: \n" + " Thread: " + Thread.currentThread().getName() + "\n" + " Txn: " + txn + "\n" + " Iteration: " + count); } // Something caused the transaction to be marked for rollback // There is no recovery or retrying with this txn.rollback(); } else { // The transaction hasn't been flagged for failure so the commit // sould still be good. txn.commit(); } } if (logger.isDebugEnabled()) { if (count != 0) { logger.debug("\n" + "Transaction succeeded: \n" + " Thread: " + Thread.currentThread().getName() + "\n" + " Txn: " + txn + "\n" + " Iteration: " + count); } } return result; } catch (Throwable e) { // Somebody else 'owns' the transaction, so just rethrow. if (txn == null) { RuntimeException ee = AlfrescoRuntimeException.makeRuntimeException(e, "Exception from transactional callback: " + cb); throw ee; } if (logger.isDebugEnabled()) { logger.debug("\n" + "Transaction commit failed: \n" + " Thread: " + Thread.currentThread().getName() + "\n" + " Txn: " + txn + "\n" + " Iteration: " + count + "\n" + " Exception follows:", e); } // Rollback if we can. if (txn != null) { try { int txnStatus = txn.getStatus(); // We can only rollback if a transaction was started (NOT NO_TRANSACTION) and // if that transaction has not been rolled back (NOT ROLLEDBACK). // If an exception occurs while the transaction is being created (e.g. no database connection) // then the status will be NO_TRANSACTION. if (txnStatus != Status.STATUS_NO_TRANSACTION && txnStatus != Status.STATUS_ROLLEDBACK) { txn.rollback(); } } catch (Throwable e1) { // A rollback failure should not preclude a retry, but logging of the rollback failure is required logger.error("Rollback failure. Normal retry behaviour will resume.", e1); } } if (e instanceof RollbackException) { lastException = (e.getCause() instanceof RuntimeException) ? (RuntimeException) e.getCause() : new AlfrescoRuntimeException("Exception in Transaction.", e.getCause()); } else { lastException = (e instanceof RuntimeException) ? (RuntimeException) e : new AlfrescoRuntimeException("Exception in Transaction.", e); } // Check if there is a cause for retrying Throwable retryCause = extractRetryCause(e); // ALF-17361 fix, also check for configured extra exceptions if (retryCause == null && extraExceptions != null && !extraExceptions.isEmpty()) { retryCause = ExceptionStackUtil.getCause(e, extraExceptions.toArray(new Class[] {})); } if (retryCause != null) { // Sleep a random amount of time before retrying. // The sleep interval increases with the number of retries. int sleepIntervalRandom = (count > 0 && retryWaitIncrementMs > 0) ? random.nextInt(count * retryWaitIncrementMs) : minRetryWaitMs; int sleepInterval = Math.min(maxRetryWaitMs, sleepIntervalRandom); sleepInterval = Math.max(sleepInterval, minRetryWaitMs); if (logger.isInfoEnabled() && !logger.isDebugEnabled()) { String msg = String.format( "Retrying %s: count %2d; wait: %1.1fs; msg: \"%s\"; exception: (%s)", Thread.currentThread().getName(), count, (double) sleepInterval / 1000D, retryCause.getMessage(), retryCause.getClass().getName()); logger.info(msg); } try { Thread.sleep(sleepInterval); } catch (InterruptedException ie) { // Do nothing. } // Try again continue; } else { // It was a 'bad' exception. throw lastException; } } } // We've worn out our welcome and retried the maximum number of times. // So, fail. throw lastException; } finally { if (requiresNew && maxExecutionMs > 0) { synchronized (this) { txnCount--; List<Throwable> traces = txnsInProgress.get(startTime); if (traces != null) { if (traces.size() == 1) { txnsInProgress.remove(startTime); } else { traces.remove(stackTrace); } } } } } }
From source file:org.alfresco.repo.transaction.TransactionUtil.java
/** * Execute the transaction work in a user transaction of a specified type * /*from w w w . ja v a 2 s . com*/ * @param transactionService the transaction service * @param transactionWork the transaction work * @param nonPropagatingUserTransaction indicates whether the transaction * should be non propigating or not * @param readOnly true if the transaction should be read-only * * @throws java.lang.RuntimeException if the transaction was rolled back */ private static <R> R executeInTransaction(TransactionService transactionService, TransactionWork<R> transactionWork, boolean nonPropagatingUserTransaction, boolean readOnly) { ParameterCheck.mandatory("transactionWork", transactionWork); R result = null; // Get the right type of user transaction UserTransaction txn = null; if (nonPropagatingUserTransaction == true) { txn = transactionService.getNonPropagatingUserTransaction(); } else { txn = transactionService.getUserTransaction(readOnly); } try { // Begin the transaction, do the work and then commit the // transaction txn.begin(); result = transactionWork.doWork(); // rollback or commit if (txn.getStatus() == Status.STATUS_MARKED_ROLLBACK) { // something caused the transaction to be marked for rollback txn.rollback(); } else { // transaction should still commit txn.commit(); } } catch (RollbackException exception) { // commit failed throw new AlfrescoRuntimeException("Unexpected rollback exception: \n" + exception.getMessage(), exception); } catch (Throwable exception) { try { // Roll back the exception txn.rollback(); } catch (Throwable rollbackException) { // just dump the exception - we are already in a failure state logger.error("Error rolling back transaction", rollbackException); } // Re-throw the exception if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new RuntimeException("Error during execution of transaction.", exception); } } return result; }
From source file:org.alfresco.repo.web.scripts.RepositoryContainer.java
/** * Execute script within required level of transaction * //w w w . ja va 2 s.c o m * @param script WebScript * @param scriptReq WebScriptRequest * @param scriptRes WebScriptResponse * @throws IOException */ protected void transactionedExecute(final WebScript script, final WebScriptRequest scriptReq, final WebScriptResponse scriptRes) throws IOException { try { final Description description = script.getDescription(); if (description.getRequiredTransaction() == RequiredTransaction.none) { script.execute(scriptReq, scriptRes); } else { final BufferedRequest bufferedReq; final BufferedResponse bufferedRes; RequiredTransactionParameters trxParams = description.getRequiredTransactionParameters(); if (trxParams.getCapability() == TransactionCapability.readwrite) { if (trxParams.getBufferSize() > 0) { if (logger.isDebugEnabled()) logger.debug("Creating Transactional Response for ReadWrite transaction; buffersize=" + trxParams.getBufferSize()); // create buffered request and response that allow transaction retrying bufferedReq = new BufferedRequest(scriptReq, streamFactory); bufferedRes = new BufferedResponse(scriptRes, trxParams.getBufferSize()); } else { if (logger.isDebugEnabled()) logger.debug("Transactional Response bypassed for ReadWrite - buffersize=0"); bufferedReq = null; bufferedRes = null; } } else { bufferedReq = null; bufferedRes = null; } // encapsulate script within transaction RetryingTransactionCallback<Object> work = new RetryingTransactionCallback<Object>() { public Object execute() throws Exception { try { if (logger.isDebugEnabled()) logger.debug("Begin retry transaction block: " + description.getRequiredTransaction() + "," + description.getRequiredTransactionParameters().getCapability()); if (bufferedRes == null) { script.execute(scriptReq, scriptRes); } else { // Reset the request and response in case of a transaction retry bufferedReq.reset(); bufferedRes.reset(); script.execute(bufferedReq, bufferedRes); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Transaction exception: " + description.getRequiredTransaction() + ": " + e.getMessage()); // Note: user transaction shouldn't be null, but just in case inside this exception handler UserTransaction userTrx = RetryingTransactionHelper.getActiveUserTransaction(); if (userTrx != null) { logger.debug("Transaction status: " + userTrx.getStatus()); } } UserTransaction userTrx = RetryingTransactionHelper.getActiveUserTransaction(); if (userTrx != null) { if (userTrx.getStatus() != Status.STATUS_MARKED_ROLLBACK) { if (logger.isDebugEnabled()) logger.debug("Marking web script transaction for rollback"); try { userTrx.setRollbackOnly(); } catch (Throwable re) { if (logger.isDebugEnabled()) logger.debug( "Caught and ignoring exception during marking for rollback: " + re.getMessage()); } } } // re-throw original exception for retry throw e; } finally { if (logger.isDebugEnabled()) logger.debug("End retry transaction block: " + description.getRequiredTransaction() + "," + description.getRequiredTransactionParameters().getCapability()); } return null; } }; boolean readonly = description.getRequiredTransactionParameters() .getCapability() == TransactionCapability.readonly; boolean requiresNew = description.getRequiredTransaction() == RequiredTransaction.requiresnew; // log a warning if we detect a GET webscript being run in a readwrite transaction, GET calls should // NOT have any side effects so this scenario as a warning sign something maybe amiss, see ALF-10179. if (logger.isDebugEnabled() && !readonly && "GET".equalsIgnoreCase(description.getMethod())) { logger.debug("Webscript with URL '" + scriptReq.getURL() + "' is a GET request but it's descriptor has declared a readwrite transaction is required"); } try { RetryingTransactionHelper transactionHelper = transactionService.getRetryingTransactionHelper(); if (script instanceof LoginPost) { //login script requires read-write transaction because of authorization intercepter transactionHelper.setForceWritable(true); } transactionHelper.doInTransaction(work, readonly, requiresNew); } catch (TooBusyException e) { // Map TooBusyException to a 503 status code throw new WebScriptException(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage(), e); } finally { // Get rid of any temporary files if (bufferedReq != null) { bufferedReq.close(); } } // Ensure a response is always flushed after successful execution if (bufferedRes != null) { bufferedRes.writeResponse(); } } } catch (IOException ioe) { Throwable socketException = ExceptionStackUtil.getCause(ioe, SocketException.class); Class<?> clientAbortException = null; try { clientAbortException = Class.forName("org.apache.catalina.connector.ClientAbortException"); } catch (ClassNotFoundException e) { // do nothing } // Note: if you need to look for more exceptions in the stack, then create a static array and pass it in if ((socketException != null && socketException.getMessage().contains("Broken pipe")) || (clientAbortException != null && ExceptionStackUtil.getCause(ioe, clientAbortException) != null)) { if (logger.isDebugEnabled()) { logger.warn("Client has cut off communication", ioe); } else { logger.info("Client has cut off communication"); } } else { throw ioe; } } }
From source file:org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter.java
/** * Get the stored MD4 hashed password for the user, or null if the user does not exist * /* www. j av a 2s .c o m*/ * @param userName String * * @return MD4 hash or null */ protected String getMD4Hash(String userName) { String md4hash = null; // Wrap the auth component calls in a transaction UserTransaction tx = transactionService.getUserTransaction(); try { tx.begin(); // Get the stored MD4 hashed password for the user, or null if the user does not exist md4hash = nltmAuthenticator.getMD4HashedPassword(userName); } catch (Throwable ex) { if (getLogger().isDebugEnabled()) getLogger().debug(ex); } finally { // Rollback/commit the transaction if still valid if (tx != null) { try { // Commit or rollback the transaction if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK || tx.getStatus() == Status.STATUS_ROLLEDBACK || tx.getStatus() == Status.STATUS_ROLLING_BACK) { // Transaction is marked for rollback tx.rollback(); } else { // Commit the transaction tx.commit(); } } catch (Throwable ex) { if (getLogger().isDebugEnabled()) getLogger().debug(ex); } } } return md4hash; }
From source file:org.alfresco.repo.webdav.DeleteMethodTest.java
@After public void tearDown() throws Exception { method = null;/*from w w w . ja v a2 s .co m*/ request = null; response = null; if (txn.getStatus() == Status.STATUS_MARKED_ROLLBACK) { txn.rollback(); } else { txn.commit(); } AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser(); nodeService.deleteNode(versionableDoc); // As per MNT-10037 try to create a node and delete it in the next txn txn = transactionService.getUserTransaction(); txn.begin(); Map<QName, Serializable> properties = new HashMap<QName, Serializable>(); String nodeName = "leak-session-doc-" + GUID.generate(); properties.put(ContentModel.PROP_NAME, nodeName); NodeRef nodeRef = nodeService.createNode(companyHomeNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName(ContentModel.USER_MODEL_URI, nodeName), ContentModel.TYPE_CONTENT, properties) .getChildRef(); contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true).putContent("WebDAVTestContent"); txn.commit(); txn = transactionService.getUserTransaction(); txn.begin(); nodeService.deleteNode(nodeRef); txn.commit(); AuthenticationUtil.clearCurrentSecurityContext(); }
From source file:org.alfresco.repo.webdav.PutMethodTest.java
@After public void tearDown() throws Exception { method = null;//www.j a v a 2 s. c o m request = null; response = null; testDataFile = null; davLockInfoAdminFile = null; if (txn.getStatus() == Status.STATUS_MARKED_ROLLBACK) { txn.rollback(); } else { txn.commit(); } AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser(); deleteUser(USER1_NAME); deleteUser(USER2_NAME); nodeService.deleteNode(versionableDoc); // As per MNT-10037 try to create a node and delete it in the next txn txn = transactionService.getUserTransaction(); txn.begin(); Map<QName, Serializable> properties = new HashMap<QName, Serializable>(); String nodeName = "leak-session-doc-" + GUID.generate(); properties.put(ContentModel.PROP_NAME, nodeName); NodeRef nodeRef = nodeService.createNode(companyHomeNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName(ContentModel.USER_MODEL_URI, nodeName), ContentModel.TYPE_CONTENT, properties) .getChildRef(); contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true).putContent("WebDAVTestContent"); txn.commit(); txn = transactionService.getUserTransaction(); txn.begin(); nodeService.deleteNode(nodeRef); txn.commit(); AuthenticationUtil.clearCurrentSecurityContext(); }
From source file:org.apache.ode.bpel.engine.Contexts.java
public <T> T execTransaction(Callable<T> transaction) throws Exception { try {// ww w . jav a 2s. c om txManager.begin(); } catch (Exception ex) { String errmsg = "Internal Error, could not begin transaction."; throw new BpelEngineException(errmsg, ex); } boolean success = false; try { T retval = transaction.call(); success = (txManager.getStatus() != Status.STATUS_MARKED_ROLLBACK); return retval; } catch (Exception ex) { throw ex; } finally { if (success) try { txManager.commit(); } catch (Exception ex) { __log.error("Commit failed.", ex); throw new BpelEngineException("Commit failed.", ex); } else try { txManager.rollback(); } catch (Exception ex) { __log.error("Transaction rollback failed.", ex); } } }
From source file:org.apache.ofbiz.entity.transaction.TransactionUtil.java
/** Begins a transaction in the current thread IF transactions are available; only * tries if the current transaction status is ACTIVE, if not active it returns false. * If and on only if it begins a transaction it will return true. In other words, if * a transaction is already in place it will return false and do nothing. *//* w w w. j av a 2 s . co m*/ public static boolean begin(int timeout) throws GenericTransactionException { UserTransaction ut = TransactionFactoryLoader.getInstance().getUserTransaction(); if (ut != null) { try { int currentStatus = ut.getStatus(); if (Debug.verboseOn()) { Debug.logVerbose("Current status : " + getTransactionStateString(currentStatus), module); } if (currentStatus == Status.STATUS_ACTIVE) { if (Debug.verboseOn()) { Debug.logVerbose("Active transaction in place, so no transaction begun", module); } return false; } else if (currentStatus == Status.STATUS_MARKED_ROLLBACK) { Exception e = getTransactionBeginStack(); if (e != null) { Debug.logWarning(e, "Active transaction marked for rollback in place, so no transaction begun; this stack trace shows when the exception began: ", module); } else { Debug.logWarning("Active transaction marked for rollback in place, so no transaction begun", module); } RollbackOnlyCause roc = getSetRollbackOnlyCause(); // do we have a cause? if so, throw special exception if (UtilValidate.isNotEmpty(roc)) { throw new GenericTransactionException( "The current transaction is marked for rollback, not beginning a new transaction and aborting current operation; the rollbackOnly was caused by: " + roc.getCauseMessage(), roc.getCauseThrowable()); } else { return false; } } internalBegin(ut, timeout); // reset the transaction stamps, just in case... clearTransactionStamps(); // initialize the start stamp getTransactionStartStamp(); // set the tx begin stack placeholder setTransactionBeginStack(); // initialize the debug resource if (debugResources()) { DebugXaResource dxa = new DebugXaResource(); try { dxa.enlist(); } catch (XAException e) { Debug.logError(e, module); } } return true; } catch (NotSupportedException e) { throw new GenericTransactionException( "Not Supported error, could not begin transaction (probably a nesting problem)", e); } catch (SystemException e) { throw new GenericTransactionException("System error, could not begin transaction", e); } } else { if (Debug.infoOn()) Debug.logInfo("No user transaction, so no transaction begun", module); return false; } }
From source file:org.apache.ofbiz.entity.transaction.TransactionUtil.java
public static String getTransactionStateString(int state) { /*//from www .j a v a2 s . c o m * javax.transaction.Status * STATUS_ACTIVE 0 * STATUS_MARKED_ROLLBACK 1 * STATUS_PREPARED 2 * STATUS_COMMITTED 3 * STATUS_ROLLEDBACK 4 * STATUS_UNKNOWN 5 * STATUS_NO_TRANSACTION 6 * STATUS_PREPARING 7 * STATUS_COMMITTING 8 * STATUS_ROLLING_BACK 9 */ switch (state) { case Status.STATUS_ACTIVE: return "Transaction Active (" + state + ")"; case Status.STATUS_COMMITTED: return "Transaction Committed (" + state + ")"; case Status.STATUS_COMMITTING: return "Transaction Committing (" + state + ")"; case Status.STATUS_MARKED_ROLLBACK: return "Transaction Marked Rollback (" + state + ")"; case Status.STATUS_NO_TRANSACTION: return "No Transaction (" + state + ")"; case Status.STATUS_PREPARED: return "Transaction Prepared (" + state + ")"; case Status.STATUS_PREPARING: return "Transaction Preparing (" + state + ")"; case Status.STATUS_ROLLEDBACK: return "Transaction Rolledback (" + state + ")"; case Status.STATUS_ROLLING_BACK: return "Transaction Rolling Back (" + state + ")"; case Status.STATUS_UNKNOWN: return "Transaction Status Unknown (" + state + ")"; default: return "Not a valid state code (" + state + ")"; } }
From source file:org.apache.ojb.odmg.JTATxManager.java
private static String getStatusString(int status) { switch (status) { case Status.STATUS_ACTIVE: return "STATUS_ACTIVE"; case Status.STATUS_COMMITTED: return "STATUS_COMMITTED"; case Status.STATUS_COMMITTING: return "STATUS_COMMITTING"; case Status.STATUS_MARKED_ROLLBACK: return "STATUS_MARKED_ROLLBACK"; case Status.STATUS_NO_TRANSACTION: return "STATUS_NO_TRANSACTION"; case Status.STATUS_PREPARED: return "STATUS_PREPARED"; case Status.STATUS_PREPARING: return "STATUS_PREPARING"; case Status.STATUS_ROLLEDBACK: return "STATUS_ROLLEDBACK"; case Status.STATUS_ROLLING_BACK: return "STATUS_ROLLING_BACK"; case Status.STATUS_UNKNOWN: return "STATUS_UNKNOWN"; default:/*www . j a va 2s . c o m*/ return "NO STATUS FOUND"; } }