@Test public void evictTransactional() { Cache target = new ConcurrentMapCache("testCache"); Cache cache = new TransactionAwareCacheDecorator(target); Object key = new Object(); cache.put(key, "123"); TransactionStatus status = txManager.getTransaction(new DefaultTransactionAttribute( TransactionDefinition.PROPAGATION_REQUIRED)); cache.evict(key); assertEquals("123", target.get(key, String.class)); txManager.commit(status); assertNull(target.get(key)); }
@Test public void clearTransactional() { Cache target = new ConcurrentMapCache("testCache"); Cache cache = new TransactionAwareCacheDecorator(target); Object key = new Object(); cache.put(key, "123"); TransactionStatus status = txManager.getTransaction(new DefaultTransactionAttribute( TransactionDefinition.PROPAGATION_REQUIRED)); cache.clear(); assertEquals("123", target.get(key, String.class)); txManager.commit(status); assertNull(target.get(key)); }
/** * Permet d'initialiser le TransactionManager utilisé pour l'exécution de la tâche. * Dans la mesure du possible, surcharger plutôt {@link #getTaskExecutionTransactionTemplateConfig()}. */ protected TransactionTemplate newTaskExecutionTransactionTemplate(EntityManagerUtils entityManagerUtils, PlatformTransactionManager transactionManager) { TaskExecutionTransactionTemplateConfig config = getTaskExecutionTransactionTemplateConfig(); TransactionTemplate taskExecutionTransactionTemplate; if (config.isTransactional()) { DefaultTransactionAttribute defaultTransactionAttributes = new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRES_NEW); defaultTransactionAttributes.setReadOnly(config.isReadOnly()); taskExecutionTransactionTemplate = new TransactionTemplate(transactionManager, defaultTransactionAttributes); } else { taskExecutionTransactionTemplate = new OpenEntityManagerWithNoTransactionTransactionTemplate( entityManagerUtils, transactionManager, config.isReadOnly()); } return taskExecutionTransactionTemplate; }
@Autowired private void setTransactionTemplate(PlatformTransactionManager transactionManager) { DefaultTransactionAttribute writeTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRED); writeTransactionAttribute.setReadOnly(false); writeTransactionTemplate = new TransactionTemplate(transactionManager, writeTransactionAttribute); DefaultTransactionAttribute writeRequiresNewTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRES_NEW); writeRequiresNewTransactionAttribute.setReadOnly(false); writeRequiresNewTransactionTemplate = new TransactionTemplate(transactionManager, writeRequiresNewTransactionAttribute); DefaultTransactionAttribute readOnlyTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRED); readOnlyTransactionAttribute.setReadOnly(true); readOnlyTransactionTemplate = new TransactionTemplate(transactionManager, readOnlyTransactionAttribute); }
@Override public TransactionAttributeSource getTransactionAttributeSource() { final TransactionAttributeSource origTxAttrSource = super.getTransactionAttributeSource(); return new TransactionAttributeSource() { @Override public TransactionAttribute getTransactionAttribute(final Method method, final Class<?> targetClass) { TransactionAttribute txAttr = origTxAttrSource.getTransactionAttribute(method, targetClass); if (txAttr instanceof DefaultTransactionAttribute) { ((DefaultTransactionAttribute) txAttr).setQualifier(AuthContextUtils.getDomain()); } return txAttr; } }; }
/** * If the test method of the supplied {@link TestContext test context} is * configured to run within a transaction, this method will run * {@link BeforeTransaction @BeforeTransaction methods} and start a new * transaction. * <p> * Note that if a {@link BeforeTransaction @BeforeTransaction method} * fails, remaining {@link BeforeTransaction @BeforeTransaction * methods} will not be invoked, and a transaction will not be started. * * @see org.springframework.transaction.annotation.Transactional */ @SuppressWarnings("serial") @Override public void beforeTestClass(TestContext testContext) throws Exception { TransactionDefinition transactionDefinition = new DefaultTransactionAttribute(); if (transactionDefinition != null) { PlatformTransactionManager tm = testContext.getApplicationContext() .getBean(PlatformTransactionManager.class); TransactionContext txContext = new TransactionContext(tm, transactionDefinition); startNewTransaction(testContext, txContext); this.transactionContextCache.put(testContext.getTestClass(), txContext); } }
private void addUserToGroup(final User crowdUser, final Group group) { if (crowdUser == null) { log.warn("Cannot add null user to group!"); } else if (group == null) { log.warn("Cannot add user to null group!"); } else { new TransactionTemplate(getTransactionManager(), new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED)).execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { try { getCrowdService().addUserToGroup(crowdUser, group); } catch (Throwable t) { log.error("Failed to add user " + crowdUser.getName() + " to group '" + group.getName() + "'!", t); } return null; } }); } }
private void removeUserFromGroup(final CrowdService crowdService, final User crowdUser, final Group group) { if (crowdUser == null) { log.warn("Cannot remove null user from group!"); } else if (group == null) { log.warn("Cannot remove user from null group!"); } else { new TransactionTemplate(getTransactionManager(), new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED)).execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { try { crowdService.removeUserFromGroup(crowdUser, group); } catch (Throwable t) { log.error("Failed to remove user " + crowdUser.getName() + " from group '" + group.getName() + "'!", t); } return null; } }); } }
private void createUser(final UserAccessor userAccessor, final String username, final String fullName, final String emailAddress) { if (username != null) { new TransactionTemplate(getTransactionManager(), new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED)).execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { try { userAccessor.createUser(new DefaultUser(username, null, null), Credential.NONE); } catch (LicensingException le) { log.error("Cannot create user '" + username + "'!", le); // if you're having licensing issues, this needs to bubble up. // see: https://github.com/chauth/confluence_http_authenticator/issues/33 throw le; } catch (Throwable t) { log.error("Failed to create user '" + username + "'!", t); } return null; } }); } else { log.warn("Cannot add user with null username!"); } }
private void updateUser(final CrowdService crowdService, final User crowdUser) { if (crowdUser != null) { new TransactionTemplate(getTransactionManager(), new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED)).execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { try { crowdService.updateUser(crowdUser); } catch (Throwable t) { log.error("Failed to update user '" + crowdUser.getName() + "'!", t); } return null; } }); } else { log.warn("Cannot update null user!"); } }
@Test public void testApplicationManagedEntityManagerWithTransaction() throws Exception { Object testEntity = new Object(); EntityTransaction mockTx = mock(EntityTransaction.class); // This one's for the tx (shared) EntityManager sharedEm = mock(EntityManager.class); given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction()); // This is the application-specific one EntityManager mockEm = mock(EntityManager.class); given(mockEm.getTransaction()).willReturn(mockTx); given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm); LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit(); JpaTransactionManager jpatm = new JpaTransactionManager(); jpatm.setEntityManagerFactory(cefb.getObject()); TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute()); EntityManagerFactory emf = cefb.getObject(); assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject()); assertNotSame("EMF must be proxied", mockEmf, emf); EntityManager em = emf.createEntityManager(); em.joinTransaction(); assertFalse(em.contains(testEntity)); jpatm.commit(txStatus); cefb.destroy(); verify(mockTx).begin(); verify(mockTx).commit(); verify(mockEm).contains(testEntity); verify(mockEmf).close(); }
@Test public void testApplicationManagedEntityManagerWithJtaTransaction() throws Exception { Object testEntity = new Object(); // This one's for the tx (shared) EntityManager sharedEm = mock(EntityManager.class); given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction()); // This is the application-specific one EntityManager mockEm = mock(EntityManager.class); given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm); LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit(); MutablePersistenceUnitInfo pui = ((MutablePersistenceUnitInfo) cefb.getPersistenceUnitInfo()); pui.setTransactionType(PersistenceUnitTransactionType.JTA); JpaTransactionManager jpatm = new JpaTransactionManager(); jpatm.setEntityManagerFactory(cefb.getObject()); TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute()); EntityManagerFactory emf = cefb.getObject(); assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject()); assertNotSame("EMF must be proxied", mockEmf, emf); EntityManager em = emf.createEntityManager(); em.joinTransaction(); assertFalse(em.contains(testEntity)); jpatm.commit(txStatus); cefb.destroy(); verify(mockEm).joinTransaction(); verify(mockEm).contains(testEntity); verify(mockEmf).close(); }
@Test public void putTransactional() { Cache target = new ConcurrentMapCache("testCache"); Cache cache = new TransactionAwareCacheDecorator(target); TransactionStatus status = txManager.getTransaction(new DefaultTransactionAttribute( TransactionDefinition.PROPAGATION_REQUIRED)); Object key = new Object(); cache.put(key, "123"); assertNull(target.get(key)); txManager.commit(status); assertEquals("123", target.get(key, String.class)); }
@Autowired @Lazy // Mutable properties may require a more complex infrastructure, whose setup may require access to immutable properties public void setPlatformTransactionManager(PlatformTransactionManager transactionManager) { DefaultTransactionAttribute writeTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRED); writeTransactionAttribute.setReadOnly(false); writeTransactionTemplate = new TransactionTemplate(transactionManager, writeTransactionAttribute); }
@Autowired public void setPlatformTransactionManager(PlatformTransactionManager transactionManager) { DefaultTransactionAttribute readOnlyTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRES_NEW); readOnlyTransactionAttribute.setReadOnly(true); readOnlyTransactionTemplate = new TransactionTemplate(transactionManager, readOnlyTransactionAttribute); DefaultTransactionAttribute writeTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRES_NEW); writeTransactionAttribute.setReadOnly(false); writeTransactionTemplate = new TransactionTemplate(transactionManager, writeTransactionAttribute); }
/** * Construit un transactionInterceptor avec une configuration par défaut. */ public static TransactionInterceptor defaultTransactionInterceptor(PlatformTransactionManager transactionManager, List<Class<? extends Exception>> additionalRollbackRuleExceptions) { TransactionInterceptor transactionInterceptor = new TransactionInterceptor(); Properties transactionAttributes = new Properties(); List<RollbackRuleAttribute> rollbackRules = Lists.newArrayList(); rollbackRules.add(new RollbackRuleAttribute(ServiceException.class)); // TODO voir si on ajoute SecurityServiceException.class en fonction de ce que ça donne sur le Wombat // ou voir si on ne la dégage pas carrément en fait... for (Class<? extends Exception> clazz : additionalRollbackRuleExceptions) { rollbackRules.add(new RollbackRuleAttribute(clazz)); } DefaultTransactionAttribute readOnlyTransactionAttributes = new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED); readOnlyTransactionAttributes.setReadOnly(true); RuleBasedTransactionAttribute writeTransactionAttributes = new RuleBasedTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED, rollbackRules); String readOnlyTransactionAttributesDefinition = readOnlyTransactionAttributes.toString(); String writeTransactionAttributesDefinition = writeTransactionAttributes.toString(); // read-only transactionAttributes.setProperty("is*", readOnlyTransactionAttributesDefinition); transactionAttributes.setProperty("has*", readOnlyTransactionAttributesDefinition); transactionAttributes.setProperty("get*", readOnlyTransactionAttributesDefinition); transactionAttributes.setProperty("list*", readOnlyTransactionAttributesDefinition); transactionAttributes.setProperty("search*", readOnlyTransactionAttributesDefinition); transactionAttributes.setProperty("find*", readOnlyTransactionAttributesDefinition); transactionAttributes.setProperty("count*", readOnlyTransactionAttributesDefinition); // write et rollback-rule transactionAttributes.setProperty("*", writeTransactionAttributesDefinition); transactionInterceptor.setTransactionAttributes(transactionAttributes); transactionInterceptor.setTransactionManager(transactionManager); return transactionInterceptor; }
@Autowired public void setPlatformTransactionManager(PlatformTransactionManager transactionManager) { DefaultTransactionAttribute writeRequiredTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRED); writeRequiredTransactionAttribute.setReadOnly(false); writeRequiredTransactionTemplate = new TransactionTemplate(transactionManager, writeRequiredTransactionAttribute); }
@Autowired public void setPlatformTransactionManager(PlatformTransactionManager transactionManager) { DefaultTransactionAttribute readOnlyTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRED); readOnlyTransactionAttribute.setReadOnly(true); readOnlyTransactionTemplate = new TransactionTemplate(transactionManager, readOnlyTransactionAttribute); DefaultTransactionAttribute writeTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRED); writeTransactionAttribute.setReadOnly(false); writeTransactionTemplate = new TransactionTemplate(transactionManager, writeTransactionAttribute); }
@Autowired private void setTransactionManager(EntityManagerUtils entityManagerUtils, PlatformTransactionManager transactionManager) { // Le TransactionTemplate pour la gestion du cycle de vie doit forcément être défini comme cela, // pas besoin de pouvoir le redéfinir. DefaultTransactionAttribute defaultTransactionAttributes = new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRES_NEW); taskManagementTransactionTemplate = new TransactionTemplate(transactionManager, defaultTransactionAttributes); // On donne la main sur l'initialisation du TransactionTemplate pour l'exécution de la tâche. taskExecutionTransactionTemplate = newTaskExecutionTransactionTemplate( entityManagerUtils, transactionManager); }
@Autowired private void setTransactionTemplate(PlatformTransactionManager transactionManager) { DefaultTransactionAttribute writeTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRED); writeTransactionAttribute.setReadOnly(false); writeTransactionTemplate = new TransactionTemplate(transactionManager, writeTransactionAttribute); }
@Override public TransactionAttributeSource getTransactionAttributeSource() { final TransactionAttributeSource origTxAttrSource = super.getTransactionAttributeSource(); return (final Method method, final Class<?> targetClass) -> { TransactionAttribute txAttr = origTxAttrSource.getTransactionAttribute(method, targetClass); if (txAttr instanceof DefaultTransactionAttribute) { ((DefaultTransactionAttribute) txAttr).setQualifier(AuthContextUtils.getDomain()); } return txAttr; }; }
@Bean @Autowired protected Step ccJudgmentImportProcessStep() { TaskletStep step = steps.get("ccJudgmentImportProcessStep") .<RawSourceCcJudgment, JudgmentWithCorrectionList<CommonCourtJudgment>> chunk(20).faultTolerant() .skipPolicy(ccjImportProcessSkipPolicy).listener(ccjImportProcessSkipListener) .reader(ccjImportProcessReader) .processor(ccjImportProcessProcessor) .writer(ccjImportProcessWriter()) .transactionAttribute(new DefaultTransactionAttribute()) .build(); step.setTransactionAttribute(new DefaultTransactionAttribute()); return step; }
@Bean public Job noTransactionJob() { Step step = stepBuilders.get("noTransactionalStep") .tasklet(tasklet()) .transactionAttribute(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_NEVER)) .build(); return jobBuilders.get("noTransactionalJob").start(step).build(); }
@Test public void testApplicationManagedEntityManagerWithTransactionAndCommitException() throws Exception { Object testEntity = new Object(); EntityTransaction mockTx = mock(EntityTransaction.class); willThrow(new OptimisticLockException()).given(mockTx).commit(); // This one's for the tx (shared) EntityManager sharedEm = mock(EntityManager.class); given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction()); // This is the application-specific one EntityManager mockEm = mock(EntityManager.class); given(mockEm.getTransaction()).willReturn(mockTx); given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm); LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit(); JpaTransactionManager jpatm = new JpaTransactionManager(); jpatm.setEntityManagerFactory(cefb.getObject()); TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute()); EntityManagerFactory emf = cefb.getObject(); assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject()); assertNotSame("EMF must be proxied", mockEmf, emf); EntityManager em = emf.createEntityManager(); em.joinTransaction(); assertFalse(em.contains(testEntity)); try { jpatm.commit(txStatus); fail("Should have thrown OptimisticLockingFailureException"); } catch (OptimisticLockingFailureException ex) { // expected } cefb.destroy(); verify(mockTx).begin(); verify(mockEm).contains(testEntity); verify(mockEmf).close(); }
@Autowired private void setTransactionTemplate(PlatformTransactionManager transactionManager) { DefaultTransactionAttribute transactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRES_NEW); transactionTemplate = new TransactionTemplate(transactionManager, transactionAttribute); }
public TransactionTemplate newTransactionTemplate(Writeability writeability, int propagation) { DefaultTransactionAttribute transactionAttribute = new DefaultTransactionAttribute(propagation); transactionAttribute.setReadOnly(Writeability.READ_ONLY.equals(writeability)); return new TransactionTemplate(transactionManager, transactionAttribute); }
/** * Using the default transaction attribute for the job will cause the * TaskLauncher not to see the latest state in the database but rather * what is in its transaction. By setting isolation to READ_COMMITTED * The task launcher can see latest state of the db. Since the changes * to the task execution are done by the tasks. * @return DefaultTransactionAttribute with isolation set to READ_COMMITTED. */ private TransactionAttribute getTransactionAttribute() { DefaultTransactionAttribute defaultTransactionAttribute = new DefaultTransactionAttribute(); defaultTransactionAttribute.setIsolationLevel( Isolation.READ_COMMITTED.value()); return defaultTransactionAttribute; }