List of usage examples for javax.transaction UserTransaction commit
void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException;
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.// w ww .ja va 2 s. c o m * <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.RetryingTransactionHelperTest.java
/** * Check that the transaction state can be fetched in and around the transaction. * This also checks that any mischievous attempts to manipulate the transaction * (other than setRollback) are detected. *///from w w w . j a va2s .c om public void testUserTransactionStatus() { UserTransaction txnBefore = RetryingTransactionHelper.getActiveUserTransaction(); assertNull("Did not expect to get an active UserTransaction", txnBefore); RetryingTransactionCallback<Long> callbackOuter = new RetryingTransactionCallback<Long>() { public Long execute() throws Throwable { final UserTransaction txnOuter = RetryingTransactionHelper.getActiveUserTransaction(); assertNotNull("Expected an active UserTransaction", txnOuter); assertEquals("Should be read-write txn", TxnReadState.TXN_READ_WRITE, AlfrescoTransactionSupport.getTransactionReadState()); assertEquals("Expected state is active", Status.STATUS_ACTIVE, txnOuter.getStatus()); RetryingTransactionCallback<Long> callbackInner = new RetryingTransactionCallback<Long>() { public Long execute() throws Throwable { UserTransaction txnInner = RetryingTransactionHelper.getActiveUserTransaction(); assertNotNull("Expected an active UserTransaction", txnInner); assertEquals("Should be read-only txn", TxnReadState.TXN_READ_ONLY, AlfrescoTransactionSupport.getTransactionReadState()); assertEquals("Expected state is active", Status.STATUS_ACTIVE, txnInner.getStatus()); // Check blow up try { txnInner.commit(); fail("Should not be able to commit the UserTransaction. It is for info only."); } catch (Throwable e) { // Expected } // Force a rollback txnInner.setRollbackOnly(); // Done return null; } }; return txnHelper.doInTransaction(callbackInner, true, true); } }; txnHelper.doInTransaction(callbackOuter); UserTransaction txnAfter = RetryingTransactionHelper.getActiveUserTransaction(); assertNull("Did not expect to get an active UserTransaction", txnAfter); }
From source file:org.alfresco.repo.transaction.TransactionUtil.java
/** * Execute the transaction work in a user transaction of a specified type * //from w ww . java2s . 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.transfer.fsr.FileTransferReceiverMain.java
/** * @param args String[]/*from www .j a v a 2s. co m*/ */ public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("alfresco/fsr-bootstrap-context.xml"); RetryingTransactionHelper ts = (RetryingTransactionHelper) context.getBean("retryingTransactionHelper"); FileTransferReceiverTransactionServiceImpl transactionService = (FileTransferReceiverTransactionServiceImpl) context .getBean("transactionService"); //TransferReceiver ftTransferReceiver = (TransferReceiver) context.getBean("transferReceiver"); try { UserTransaction ut = transactionService.getUserTransaction(); ut.begin(); //ftTransferReceiver.start("1234", false, ftTransferReceiver.getVersion()); QNameDAO qNameDAO = (QNameDAO) context.getBean("qnameDAO"); //qNameDAO.getOrCreateNamespace("test2"); //Pair<Long, String> pair = qNameDAO.getNamespace(1L); //System.out.println("Pair:" + pair.getSecond()); //Pair<Long, String> pair = qNameDAO.getNamespace("test2"); //System.out.println("Pair first:" + pair.getFirst()); //System.out.println("Pair second:" + pair.getSecond()); FileTransferInfoDAO fileTransferInfoDAO = (FileTransferInfoDAO) context.getBean("fileTransferInfoDAO"); //fileTransferInfoDAO.createFileTransferInfo("nodeRef", "Parent", "/a/b/c", "tot.txt","contentUrl"); FileTransferInfoEntity fti = fileTransferInfoDAO.findFileTransferInfoByNodeRef("nodeRef"); if (fti == null) { System.out.println("FTI is null!!!"); } else { System.out.println("FTI ID:" + fti.getId()); System.out.println("FTI path:" + fti.getPath()); System.out.println("FTI contentName:" + fti.getContentName()); System.out.println("FTI content Url:" + fti.getContentUrl()); } ut.commit(); } catch (Exception e) { e.printStackTrace(); } ((ClassPathXmlApplicationContext) context).close(); System.exit(0); }
From source file:org.alfresco.repo.transfer.TransferServiceImpl2.java
/** * Transfer async.//from ww w . ja v a2 s .co m * * @param targetName String * @param definition TransferDefinition * */ public void transferAsync(String targetName, TransferDefinition definition, Collection<TransferCallback> callbacks) { /** * Event processor for this transfer instance */ final TransferEventProcessor eventProcessor = new TransferEventProcessor(); if (callbacks != null) { eventProcessor.observers.addAll(callbacks); } /* * Note: * callback should be Serializable to be passed through the action API * However Serializable is not used so it does not matter. Perhaps the action API should be * changed? Or we could add a Serializable proxy here. */ Map<String, Serializable> params = new HashMap<String, Serializable>(); params.put("targetName", targetName); params.put("definition", definition); params.put("callbacks", (Serializable) callbacks); Action transferAction = actionService.createAction("transfer-async", params); /** * Execute transfer async in its own transaction. * The action service only runs actions in the post commit which is why there's * a separate transaction here. */ boolean success = false; UserTransaction trx = transactionService.getNonPropagatingUserTransaction(); try { trx.begin(); logger.debug("calling action service to execute action"); actionService.executeAction(transferAction, null, false, true); trx.commit(); logger.debug("committed successfully"); success = true; } catch (Exception error) { logger.error("unexpected exception", error); throw new AlfrescoRuntimeException(MSG_ERR_TRANSFER_ASYNC, error); } finally { if (!success) { try { logger.debug("rolling back after error"); trx.rollback(); } catch (Exception error) { logger.error("unexpected exception during rollback", error); // There's nothing much we can do here } } } }
From source file:org.alfresco.repo.web.scripts.discussion.DiscussionRestApiTest.java
/** * Monkeys with the created and published dates on a topic+posts *///from ww w.j a v a 2 s .c o m private void pushCreatedDateBack(NodeRef node, int daysAgo) throws Exception { Date created = (Date) nodeService.getProperty(node, ContentModel.PROP_CREATED); Date newCreated = new Date(created.getTime() - daysAgo * 24 * 60 * 60 * 1000); Date published = (Date) nodeService.getProperty(node, ContentModel.PROP_PUBLISHED); if (published == null) published = created; Date newPublished = new Date(published.getTime() - daysAgo * 24 * 60 * 60 * 1000); UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); this.policyBehaviourFilter.disableBehaviour(ContentModel.ASPECT_AUDITABLE); internalNodeService.setProperty(node, ContentModel.PROP_CREATED, newCreated); internalNodeService.setProperty(node, ContentModel.PROP_MODIFIED, newCreated); internalNodeService.setProperty(node, ContentModel.PROP_PUBLISHED, newPublished); this.policyBehaviourFilter.enableBehaviour(ContentModel.ASPECT_AUDITABLE); txn.commit(); // Now chance something else on the node to have it re-indexed nodeService.setProperty(node, ContentModel.PROP_CREATED, newCreated); nodeService.setProperty(node, ContentModel.PROP_MODIFIED, newCreated); nodeService.setProperty(node, ContentModel.PROP_PUBLISHED, newPublished); nodeService.setProperty(node, ContentModel.PROP_DESCRIPTION, "Forced change"); // Finally change any children (eg if updating a topic, do the posts) for (ChildAssociationRef ref : nodeService.getChildAssocs(node)) { pushCreatedDateBack(ref.getChildRef(), daysAgo); } }
From source file:org.alfresco.repo.web.scripts.links.LinksRestApiTest.java
/** * Monkeys with the created date on a link *///from www .j a v a 2 s.c om private void pushLinkCreatedDateBack(String name, int daysAgo) throws Exception { NodeRef container = siteService.getContainer(SITE_SHORT_NAME_LINKS, "links"); NodeRef node = nodeService.getChildByName(container, ContentModel.ASSOC_CONTAINS, name); Date created = (Date) nodeService.getProperty(node, ContentModel.PROP_CREATED); Date newCreated = new Date(created.getTime() - daysAgo * 24 * 60 * 60 * 1000); UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); this.policyBehaviourFilter.disableBehaviour(ContentModel.ASPECT_AUDITABLE); internalNodeService.setProperty(node, ContentModel.PROP_CREATED, newCreated); this.policyBehaviourFilter.enableBehaviour(ContentModel.ASPECT_AUDITABLE); txn.commit(); // Now chance something else on the node to have it re-indexed nodeService.setProperty(node, ContentModel.PROP_CREATED, newCreated); nodeService.setProperty(node, ContentModel.PROP_DESCRIPTION, "Forced change"); }
From source file:org.alfresco.repo.web.scripts.wiki.WikiRestApiTest.java
/** * Monkeys with the created date on a wiki page *//*from w w w. ja v a 2 s . co m*/ private void pushPageCreatedDateBack(String name, int daysAgo) throws Exception { NodeRef container = siteService.getContainer(SITE_SHORT_NAME_WIKI, "wiki"); NodeRef node = nodeService.getChildByName(container, ContentModel.ASSOC_CONTAINS, name); Date created = (Date) nodeService.getProperty(node, ContentModel.PROP_CREATED); Date newCreated = new Date(created.getTime() - daysAgo * 24 * 60 * 60 * 1000); UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); this.policyBehaviourFilter.disableBehaviour(ContentModel.ASPECT_AUDITABLE); internalNodeService.setProperty(node, ContentModel.PROP_CREATED, newCreated); this.policyBehaviourFilter.enableBehaviour(ContentModel.ASPECT_AUDITABLE); txn.commit(); // Now chance something else on the node to have it re-indexed nodeService.setProperty(node, ContentModel.PROP_CREATED, newCreated); nodeService.setProperty(node, ContentModel.PROP_DESCRIPTION, "Forced change"); }
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 * //from w w w .j a va2 s . co 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.WebDAVServlet.java
/** * @param storeValue String//w ww. ja v a 2s. c o m * @param rootPath String * @param context WebApplicationContext * @param nodeService NodeService * @param searchService SearchService * @param namespaceService NamespaceService * @param tenantService TenantService * @param m_transactionService TransactionService */ private void initializeRootNode(String storeValue, String rootPath, WebApplicationContext context, NodeService nodeService, SearchService searchService, NamespaceService namespaceService, TenantService tenantService, TransactionService m_transactionService) { // Use the system user as the authenticated context for the filesystem initialization AuthenticationContext authComponent = (AuthenticationContext) context.getBean("authenticationContext"); authComponent.setSystemUserAsCurrentUser(); // Wrap the initialization in a transaction UserTransaction tx = m_transactionService.getUserTransaction(true); try { // Start the transaction if (tx != null) tx.begin(); StoreRef storeRef = new StoreRef(storeValue); if (nodeService.exists(storeRef) == false) { throw new RuntimeException("No store for path: " + storeRef); } NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef); List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, rootPath, null, namespaceService, false); if (nodeRefs.size() > 1) { throw new RuntimeException("Multiple possible children for : \n" + " path: " + rootPath + "\n" + " results: " + nodeRefs); } else if (nodeRefs.size() == 0) { throw new RuntimeException("Node is not found for : \n" + " root path: " + rootPath); } defaultRootNode = nodeRefs.get(0); // Commit the transaction if (tx != null) tx.commit(); } catch (Exception ex) { logger.error(ex); } finally { // Clear the current system user authComponent.clearCurrentSecurityContext(); } }