List of usage examples for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRES_NEW
int PROPAGATION_REQUIRES_NEW
To view the source code for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRES_NEW.
Click Source Link
From source file:nl.nn.adapterframework.receivers.ReceiverBase.java
public void configure() throws ConfigurationException { configurationSucceeded = false;/* w w w.j av a 2 s. c o m*/ try { if (StringUtils.isEmpty(getName())) { if (getListener() != null) { setName(ClassUtils.nameOf(getListener())); } else { setName(ClassUtils.nameOf(this)); } } eventHandler = MonitorManager.getEventHandler(); registerEvent(RCV_CONFIGURED_MONITOR_EVENT); registerEvent(RCV_CONFIGURATIONEXCEPTION_MONITOR_EVENT); registerEvent(RCV_STARTED_RUNNING_MONITOR_EVENT); registerEvent(RCV_SHUTDOWN_MONITOR_EVENT); registerEvent(RCV_SUSPENDED_MONITOR_EVENT); registerEvent(RCV_RESUMED_MONITOR_EVENT); registerEvent(RCV_THREAD_EXIT_MONITOR_EVENT); TXNEW_PROC = SpringTxManagerProxy.getTransactionDefinition( TransactionDefinition.PROPAGATION_REQUIRES_NEW, getTransactionTimeout()); // Check if we need to use the in-process storage as // error-storage. // In-process storage is no longer used, but is often // still configured to be used as error-storage. // The rule is: // 1. if error-storage is configured, use it. // 2. If error-storage is not configure but an error-sender is, // then use the error-sender. // 3. If neither error-storage nor error-sender are configured, // but the in-process storage is, then use the in-process storage // for error-storage. // Member variables are accessed directly, to avoid any possible // aliasing-effects applied by getter methods. (These have been // removed for now, but since the getter-methods were not // straightforward in the earlier versions, I felt it was safer // to use direct member variables). if (this.tmpInProcessStorage != null) { if (this.errorSender == null && this.errorStorage == null) { this.errorStorage = this.tmpInProcessStorage; info(getLogPrefix() + "has errorStorage in inProcessStorage, setting inProcessStorage's type to 'errorStorage'. Please update the configuration to change the inProcessStorage element to an errorStorage element, since the inProcessStorage is no longer used."); errorStorage.setType(JdbcTransactionalStorage.TYPE_ERRORSTORAGE); } else { info(getLogPrefix() + "has inProcessStorage defined but also has an errorStorage or errorSender. InProcessStorage is not used and can be removed from the configuration."); } // Set temporary in-process storage pointer to null this.tmpInProcessStorage = null; } // Do propagate-name AFTER changing the errorStorage! propagateName(); if (getListener() == null) { throw new ConfigurationException(getLogPrefix() + "has no listener"); } if (!StringUtils.isEmpty(getElementToMove()) && !StringUtils.isEmpty(getElementToMoveChain())) { throw new ConfigurationException( "cannot have both an elementToMove and an elementToMoveChain specified"); } if (!(getHideMethod().equalsIgnoreCase("all")) && (!(getHideMethod().equalsIgnoreCase("firstHalf")))) { throw new ConfigurationException(getLogPrefix() + "invalid value for hideMethod [" + getHideMethod() + "], must be 'all' or 'firstHalf'"); } if (getListener() instanceof IPushingListener) { IPushingListener pl = (IPushingListener) getListener(); pl.setHandler(this); pl.setExceptionListener(this); } if (getListener() instanceof IPortConnectedListener) { IPortConnectedListener pcl = (IPortConnectedListener) getListener(); pcl.setReceiver(this); } if (getListener() instanceof IPullingListener) { setListenerContainer(createListenerContainer()); } if (getListener() instanceof JdbcFacade) { ((JdbcFacade) getListener()).setTransacted(isTransacted()); } if (getListener() instanceof JMSFacade) { ((JMSFacade) getListener()).setTransacted(isTransacted()); } getListener().configure(); if (getListener() instanceof HasPhysicalDestination) { info(getLogPrefix() + "has listener on " + ((HasPhysicalDestination) getListener()).getPhysicalDestinationName()); } if (getListener() instanceof HasSender) { // only informational ISender sender = ((HasSender) getListener()).getSender(); if (sender instanceof HasPhysicalDestination) { info("Listener of receiver [" + getName() + "] has answer-sender on " + ((HasPhysicalDestination) sender).getPhysicalDestinationName()); } } if (getListener() instanceof ITransactionRequirements) { ITransactionRequirements tr = (ITransactionRequirements) getListener(); if (tr.transactionalRequired() && !isTransacted()) { String msg = getLogPrefix() + "listener type [" + ClassUtils.nameOf(getListener()) + "] requires transactional processing"; ConfigurationWarnings.getInstance().add(msg); //throw new ConfigurationException(msg); } } ISender sender = getSender(); if (sender != null) { sender.configure(); if (sender instanceof HasPhysicalDestination) { info(getLogPrefix() + "has answer-sender on " + ((HasPhysicalDestination) sender).getPhysicalDestinationName()); } } ISender errorSender = getErrorSender(); if (errorSender != null) { errorSender.configure(); if (errorSender instanceof HasPhysicalDestination) { info(getLogPrefix() + "has errorSender to " + ((HasPhysicalDestination) errorSender).getPhysicalDestinationName()); } } ITransactionalStorage errorStorage = getErrorStorage(); if (errorStorage != null) { errorStorage.configure(); if (errorStorage instanceof HasPhysicalDestination) { info(getLogPrefix() + "has errorStorage to " + ((HasPhysicalDestination) errorStorage).getPhysicalDestinationName()); } registerEvent(RCV_MESSAGE_TO_ERRORSTORE_EVENT); } ITransactionalStorage messageLog = getMessageLog(); if (messageLog != null) { messageLog.configure(); if (messageLog instanceof HasPhysicalDestination) { info(getLogPrefix() + "has messageLog in " + ((HasPhysicalDestination) messageLog).getPhysicalDestinationName()); } if (StringUtils.isNotEmpty(getLabelXPath()) || StringUtils.isNotEmpty(getLabelStyleSheet())) { labelTp = TransformerPool.configureTransformer0(getLogPrefix(), classLoader, getLabelNamespaceDefs(), getLabelXPath(), getLabelStyleSheet(), "text", false, null, isXslt2()); } } if (isTransacted()) { // if (!(getListener() instanceof IXAEnabled && ((IXAEnabled)getListener()).isTransacted())) { // warn(getLogPrefix()+"sets transacted=true, but listener not. Transactional integrity is not guaranteed"); // } if (errorSender == null && errorStorage == null) { ConfigurationWarnings configWarnings = ConfigurationWarnings.getInstance(); String msg = getLogPrefix() + "sets transactionAttribute=" + getTransactionAttribute() + ", but has no errorSender or errorStorage. Messages processed with errors will be lost"; configWarnings.add(log, msg); } else { // if (errorSender!=null && !(errorSender instanceof IXAEnabled && ((IXAEnabled)errorSender).isTransacted())) { // warn(getLogPrefix()+"sets transacted=true, but errorSender is not. Transactional integrity is not guaranteed"); // } // if (errorStorage!=null && !(errorStorage instanceof IXAEnabled && ((IXAEnabled)errorStorage).isTransacted())) { // warn(getLogPrefix()+"sets transacted=true, but errorStorage is not. Transactional integrity is not guaranteed"); // } } if (getTransactionTimeout() > 0) { String systemTransactionTimeout = Misc.getSystemTransactionTimeout(); if (systemTransactionTimeout != null && StringUtils.isNumeric(systemTransactionTimeout)) { int stt = Integer.parseInt(systemTransactionTimeout); if (getTransactionTimeout() > stt) { ConfigurationWarnings configWarnings = ConfigurationWarnings.getInstance(); String msg = getLogPrefix() + "has a transaction timeout [" + getTransactionTimeout() + "] which exceeds the system transaction timeout [" + stt + "]"; configWarnings.add(log, msg); } } } } if (StringUtils.isNotEmpty(getCorrelationIDXPath()) || StringUtils.isNotEmpty(getCorrelationIDStyleSheet())) { correlationIDTp = TransformerPool.configureTransformer0(getLogPrefix(), classLoader, getCorrelationIDNamespaceDefs(), getCorrelationIDXPath(), getCorrelationIDStyleSheet(), "text", false, null, isXslt2()); } if (adapter != null) { adapter.getMessageKeeper().add(getLogPrefix() + "initialization complete"); } throwEvent(RCV_CONFIGURED_MONITOR_EVENT); configurationSucceeded = true; } catch (Throwable t) { ConfigurationException e = null; if (t instanceof ConfigurationException) { e = (ConfigurationException) t; } else { e = new ConfigurationException("Exception configuring receiver [" + getName() + "]", t); } throwEvent(RCV_CONFIGURATIONEXCEPTION_MONITOR_EVENT); log.debug(getLogPrefix() + "Errors occured during configuration, setting runstate to ERROR"); runState.setRunState(RunStateEnum.ERROR); throw e; } }
From source file:org.alfresco.repo.transaction.TransactionServiceImpl.java
/** * @see org.springframework.transaction.TransactionDefinition#PROPAGATION_REQUIRES_NEW */// w w w . ja va 2 s .c o m @Override public UserTransaction getNonPropagatingUserTransaction(boolean readOnly, boolean ignoreSystemReadOnly) { if (ignoreSystemReadOnly) { SpringAwareUserTransaction txn = new SpringAwareUserTransaction(transactionManager, (readOnly), TransactionDefinition.ISOLATION_DEFAULT, TransactionDefinition.PROPAGATION_REQUIRES_NEW, TransactionDefinition.TIMEOUT_DEFAULT); return txn; } else { SpringAwareUserTransaction txn = new SpringAwareUserTransaction(transactionManager, (readOnly | isReadOnly()), TransactionDefinition.ISOLATION_DEFAULT, TransactionDefinition.PROPAGATION_REQUIRES_NEW, TransactionDefinition.TIMEOUT_DEFAULT); return txn; } }
From source file:org.alfresco.repo.transfer.RepoTransferReceiverImplTest.java
/** * Called during the transaction setup//from w ww.j av a 2 s . c o m */ protected void onSetUp() throws Exception { super.onSetUp(); System.out.println("java.io.tmpdir == " + System.getProperty("java.io.tmpdir")); // Get the required services this.nodeService = (NodeService) this.applicationContext.getBean("nodeService"); this.contentService = (ContentService) this.applicationContext.getBean("contentService"); this.authenticationService = (MutableAuthenticationService) this.applicationContext .getBean("authenticationService"); this.actionService = (ActionService) this.applicationContext.getBean("actionService"); this.transactionService = (TransactionService) this.applicationContext.getBean("transactionComponent"); this.authenticationComponent = (AuthenticationComponent) this.applicationContext .getBean("authenticationComponent"); this.receiver = (RepoTransferReceiverImpl) this.getApplicationContext().getBean("transferReceiver"); this.policyComponent = (PolicyComponent) this.getApplicationContext().getBean("policyComponent"); this.searchService = (SearchService) this.getApplicationContext().getBean("searchService"); this.dummyContent = "This is some dummy content."; this.dummyContentBytes = dummyContent.getBytes("UTF-8"); setTransactionDefinition(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW)); authenticationComponent.setSystemUserAsCurrentUser(); startNewTransaction(); String guestHomeQuery = "/app:company_home/app:guest_home"; ResultSet guestHomeResult = searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_XPATH, guestHomeQuery); assertEquals("", 1, guestHomeResult.length()); guestHome = guestHomeResult.getNodeRef(0); endTransaction(); }
From source file:org.apache.ctakes.ytex.uima.mapper.DocumentMapperServiceImpl.java
public Integer saveDocument(final JCas jcas, final String analysisBatch, final boolean bStoreDocText, final boolean bStoreCAS, final boolean bInsertAnnotationContainmentLinks, final Set<String> setTypesToIgnore) { if (log.isTraceEnabled()) log.trace("begin saveDocument"); // communicate options to mappers using thread local variable final DefaultTransactionDefinition txDef = new DefaultTransactionDefinition( TransactionDefinition.PROPAGATION_REQUIRES_NEW); txDef.setIsolationLevel("orcl".equals(this.dbType) ? TransactionDefinition.ISOLATION_READ_COMMITTED : TransactionDefinition.ISOLATION_READ_UNCOMMITTED); final TransactionTemplate txTemplate = new TransactionTemplate(this.getTransactionManager(), txDef); final int documentId = txTemplate.execute(new TransactionCallback<Integer>() { @Override/*from w ww . ja va2s . com*/ public Integer doInTransaction(TransactionStatus arg0) { Document doc = createDocument(jcas, analysisBatch, bStoreDocText, bStoreCAS); sessionFactory.getCurrentSession().save(doc); // make sure the document has been saved getSessionFactory().getCurrentSession().flush(); saveAnnotationsHib(jcas, bInsertAnnotationContainmentLinks, setTypesToIgnore, doc); extractAndSaveDocKey(jcas, doc); return doc.getDocumentID(); } }); if (log.isTraceEnabled()) log.trace("end saveDocument"); return documentId; }
From source file:org.apache.ranger.common.db.RangerTransactionSynchronizationAdapter.java
@Override public void afterCompletion(int status) { if (LOG.isDebugEnabled()) { LOG.debug("Transaction completed with status {" + (status == STATUS_COMMITTED ? "COMMITTED" : "ROLLED_BACK") + "}"); }/* w w w .j a v a2 s . c om*/ /* Thread runnables are expected to be executed only when the status is STATUS_ROLLED_BACK. Currently, executeOnTransactionCompletion() * is called only for those changes that are going to be rolled-back by TransactionSynchronizationManager - such * as when the operation returns HttpServletResponse.SC_NOT_MODIFIED status. */ //if (status == STATUS_ROLLED_BACK) { final List<Runnable> threadRunnables = RUNNABLES.get(); if (LOG.isDebugEnabled()) { LOG.debug("Transaction completed, executing {" + threadRunnables.size() + "} runnables"); } if (threadRunnables != null) { try { //Create new transaction TransactionTemplate txTemplate = new TransactionTemplate(txManager); txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); txTemplate.execute(new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus status) { for (Runnable runnable : threadRunnables) { if (LOG.isDebugEnabled()) { LOG.debug("Executing runnable {" + runnable + "}"); } try { runnable.run(); } catch (RuntimeException e) { LOG.error("Failed to execute runnable " + runnable, e); break; } } return null; } }); } catch (Exception e) { LOG.error("Failed to commit TransactionService transaction", e); LOG.error("Ignoring..."); } } //} RUNNABLES.remove(); }
From source file:org.apache.ranger.service.RangerTransactionService.java
public void executeAfterTransactionComplete(final Runnable task) { try {// w ww. jav a2 s . c o m scheduler.schedule(new Runnable() { @Override public void run() { if (task != null) { try { //Create new transaction TransactionTemplate txTemplate = new TransactionTemplate(txManager); txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); txTemplate.execute(new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus status) { task.run(); return null; } }); } catch (Exception e) { LOG.error("Failed to commit TransactionService transaction", e); LOG.error("Ignoring..."); } } } }, 1000L, MILLISECONDS); } catch (Exception e) { LOG.error("Failed to schedule TransactionService transaction:", e); LOG.error("Ignroing..."); } }
From source file:org.broadleafcommerce.common.util.tenant.IdentityExecutionUtils.java
private static TransactionContainer establishTransaction(PlatformTransactionManager transactionManager) { Map<Object, Object> usedResources = new HashMap<Object, Object>(); Map<Object, Object> resources = TransactionSynchronizationManager.getResourceMap(); for (Map.Entry<Object, Object> entry : resources.entrySet()) { if ((entry.getKey() instanceof EntityManagerFactory || entry.getKey() instanceof DataSource) && TransactionSynchronizationManager.hasResource(entry.getKey())) { usedResources.put(entry.getKey(), entry.getValue()); }// w w w . j a v a2 s . c o m } for (Map.Entry<Object, Object> entry : usedResources.entrySet()) { TransactionSynchronizationManager.unbindResource(entry.getKey()); } TransactionStatus status; try { status = TransactionUtils.createTransaction(TransactionDefinition.PROPAGATION_REQUIRES_NEW, transactionManager, false); } catch (RuntimeException e) { throw e; } return new TransactionContainer(status, usedResources); }
From source file:org.broadleafcommerce.openadmin.server.service.persistence.entitymanager.HibernateCleaner.java
protected void performConvert(Object originalBean, Object targetBean, Field[] fields, Method method, HibernateEntityManager em, PlatformTransactionManager txManager) throws Throwable { SessionFactory sessionFactory = em.getSession().getSessionFactory(); ClassMetadata metadata = sessionFactory.getClassMetadata(originalBean.getClass()); String idProperty = metadata.getIdentifierPropertyName(); if (!typePool.containsKey(originalBean.getClass().getName())) { List<String> propertyNames = new ArrayList<String>(); for (String propertyName : metadata.getPropertyNames()) { propertyNames.add(propertyName); }//w w w . j a v a 2 s . com propertyNames.add(idProperty); List<Type> propertyTypes = new ArrayList<Type>(); Type idType = metadata.getIdentifierType(); for (Type propertyType : metadata.getPropertyTypes()) { propertyTypes.add(propertyType); } propertyTypes.add(idType); Map<String, Type> types = new HashMap<String, Type>(); int j = 0; for (String propertyName : propertyNames) { types.put(propertyName, propertyTypes.get(j)); j++; } typePool.put(originalBean.getClass().getName(), types); } Map<String, Type> types = (Map<String, Type>) typePool.get(originalBean.getClass().getName()); Field idField = null; for (Field field : fields) { if (types.containsKey(field.getName())) { field.setAccessible(true); Type fieldType = types.get(field.getName()); if (fieldType.isCollectionType() || fieldType.isAnyType()) { //field.set(targetBean, null); //do nothing } else if (fieldType.isEntityType()) { Object newOriginalBean = field.get(originalBean); if (newOriginalBean == null) { field.set(targetBean, null); } else { Object newTargetBean = newOriginalBean.getClass().newInstance(); field.set(targetBean, newTargetBean); Field[] newFields = getFields(newOriginalBean.getClass()); performConvert(newOriginalBean, newTargetBean, newFields, method, em, txManager); } } else { field.set(targetBean, field.get(originalBean)); } if (field.getName().equals(idProperty)) { idField = field; } } } if (txManager != null) { Object temp = null; if (idField == null) { throw new Exception( "Unable to find an identity field for the entity: " + originalBean.getClass().getName()); } final Serializable primaryKey = (Serializable) idField.get(originalBean); if (primaryKey != null) { temp = em.find(originalBean.getClass(), primaryKey); } DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); TransactionStatus status = txManager.getTransaction(def); try { if (primaryKey != null) { if (temp != null && method.getName().equals("merge")) { targetBean = em.merge(targetBean); } else { SessionImplementor session = (SessionImplementor) em.getDelegate(); EntityPersister persister = session.getEntityPersister(targetBean.getClass().getName(), targetBean); IdentifierProperty ip = persister.getEntityMetamodel().getIdentifierProperty(); synchronized (ip) { IdentifierValue backupUnsavedValue = setUnsavedValue(ip, IdentifierValue.ANY); em.persist(targetBean); setUnsavedValue(ip, backupUnsavedValue); } } } else { targetBean = method.invoke(em, targetBean); } } catch (Throwable ex) { txManager.rollback(status); throw ex; } txManager.commit(status); } }
From source file:org.hyperic.hibernate.id.HQMultipleHiLoPerTableGenerator.java
private synchronized Number _generate(final SessionImplementor session, Object obj) throws HibernateException { TransactionTemplate transactionTemplate = null; if (Bootstrap.hasAppContext()) { // We are running in Spring-managed server environment. Suspend the // existing Spring-managed transaction and work in a new one. transactionTemplate = new TransactionTemplate( (PlatformTransactionManager) Bootstrap.getBean("transactionManager")); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); }/* w ww . ja v a 2s.c o m*/ if (maxLo < 1) { // keep the behavior consistent even for boundary usages int val = executeInNewTransaction(transactionTemplate, session); if (val == 0) { val = executeInNewTransaction(transactionTemplate, session); } Number num = IdentifierGeneratorFactory.createNumber(val, returnClass); if (log.isTraceEnabled()) { log.trace(this + " created seq: " + keyValue + " / " + num); } return num; } else if (lo > maxLo) { int hival = executeInNewTransaction(transactionTemplate, session); lo = (hival == 0) ? 1 : 0; hi = hival * (maxLo + 1); log.debug("new hi value: " + hival); } Number num = IdentifierGeneratorFactory.createNumber(hi + lo++, returnClass); if (log.isTraceEnabled()) { log.trace(this + " created seq: " + keyValue + " / " + num); } return num; }
From source file:org.lexevs.dao.database.operation.DefaultLexEvsDatabaseOperations.java
protected void doDropCodingSchemeTables(final String codingSchemeUri, final String version, final String prefix) { TransactionTemplate template = new TransactionTemplate(this.getTransactionManager()); template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); template.execute(new TransactionCallback() { @Override/* w w w . j a va 2s .c o m*/ public Object doInTransaction(TransactionStatus status) { if (!getSystemVariables().isSingleTableMode()) { dropCodingSchemeHistoryTables(codingSchemeUri, version); } doExecuteSql(codingSchemeXmlDdl, new DropSchemaPlatformActor(), prefix); return null; } }); }