下面列出了org.springframework.test.context.transaction.TestTransaction#end ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void commitTxButDoNotStartNewTx() {
assertInTransaction(true);
assertTrue(TestTransaction.isActive());
assertUsers("Dilbert");
deleteFromTables("user");
assertUsers();
// Commit
TestTransaction.flagForCommit();
assertFalse(TestTransaction.isFlaggedForRollback());
TestTransaction.end();
assertFalse(TestTransaction.isActive());
assertInTransaction(false);
assertUsers();
executeSqlScript("classpath:/org/springframework/test/context/jdbc/data-add-dogbert.sql", false);
assertUsers("Dogbert");
}
@Test
public void rollbackTxAndStartNewTx() {
assertInTransaction(true);
assertTrue(TestTransaction.isActive());
assertUsers("Dilbert");
deleteFromTables("user");
assertUsers();
// Rollback (automatically)
assertTrue(TestTransaction.isFlaggedForRollback());
TestTransaction.end();
assertFalse(TestTransaction.isActive());
assertInTransaction(false);
assertUsers("Dilbert");
// Start new transaction with default rollback semantics
TestTransaction.start();
assertInTransaction(true);
assertTrue(TestTransaction.isFlaggedForRollback());
assertTrue(TestTransaction.isActive());
executeSqlScript("classpath:/org/springframework/test/context/jdbc/data-add-dogbert.sql", false);
assertUsers("Dilbert", "Dogbert");
}
@Test
@Commit
public void rollbackTxAndStartNewTxWithDefaultCommitSemantics() {
assertInTransaction(true);
assertTrue(TestTransaction.isActive());
assertUsers("Dilbert");
deleteFromTables("user");
assertUsers();
// Rollback
TestTransaction.flagForRollback();
assertTrue(TestTransaction.isFlaggedForRollback());
TestTransaction.end();
assertFalse(TestTransaction.isActive());
assertInTransaction(false);
assertUsers("Dilbert");
// Start new transaction with default commit semantics
TestTransaction.start();
assertInTransaction(true);
assertFalse(TestTransaction.isFlaggedForRollback());
assertTrue(TestTransaction.isActive());
executeSqlScript("classpath:/org/springframework/test/context/jdbc/data-add-dogbert.sql", false);
assertUsers("Dilbert", "Dogbert");
}
@Test
public void commitTxAndStartNewTx() {
assertInTransaction(true);
assertTrue(TestTransaction.isActive());
assertUsers("Dilbert");
deleteFromTables("user");
assertUsers();
// Commit
TestTransaction.flagForCommit();
assertFalse(TestTransaction.isFlaggedForRollback());
TestTransaction.end();
assertInTransaction(false);
assertFalse(TestTransaction.isActive());
assertUsers();
executeSqlScript("classpath:/org/springframework/test/context/jdbc/data-add-dogbert.sql", false);
assertUsers("Dogbert");
TestTransaction.start();
assertInTransaction(true);
assertTrue(TestTransaction.isActive());
}
@Test
public void rollbackTxAndStartNewTx() {
assertInTransaction(true);
assertTrue(TestTransaction.isActive());
assertUsers("Dilbert");
deleteFromTables("user");
assertUsers();
// Rollback (automatically)
assertTrue(TestTransaction.isFlaggedForRollback());
TestTransaction.end();
assertFalse(TestTransaction.isActive());
assertInTransaction(false);
assertUsers("Dilbert");
// Start new transaction with default rollback semantics
TestTransaction.start();
assertInTransaction(true);
assertTrue(TestTransaction.isFlaggedForRollback());
assertTrue(TestTransaction.isActive());
executeSqlScript("classpath:/org/springframework/test/context/jdbc/data-add-dogbert.sql", false);
assertUsers("Dilbert", "Dogbert");
}
@Test
@Commit
public void rollbackTxAndStartNewTxWithDefaultCommitSemantics() {
assertInTransaction(true);
assertTrue(TestTransaction.isActive());
assertUsers("Dilbert");
deleteFromTables("user");
assertUsers();
// Rollback
TestTransaction.flagForRollback();
assertTrue(TestTransaction.isFlaggedForRollback());
TestTransaction.end();
assertFalse(TestTransaction.isActive());
assertInTransaction(false);
assertUsers("Dilbert");
// Start new transaction with default commit semantics
TestTransaction.start();
assertInTransaction(true);
assertFalse(TestTransaction.isFlaggedForRollback());
assertTrue(TestTransaction.isActive());
executeSqlScript("classpath:/org/springframework/test/context/jdbc/data-add-dogbert.sql", false);
assertUsers("Dilbert", "Dogbert");
}
public void xtestAsyncLoadTest()
{
// TODO this is very weak .. how do we improve this ???
Action action = this.actionService.createAction(AddFeaturesActionExecuter.NAME);
action.setParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_VERSIONABLE);
action.setExecuteAsynchronously(true);
for (int i = 0; i < 1000; i++)
{
this.actionService.executeAction(action, this.nodeRef);
}
TestTransaction.flagForCommit();
TestTransaction.end();
// TODO how do we assess whether the large number of actions stacked cause a problem ??
}
@Test
public void test() {
assertEquals(4, countRowsInTable("permission"));
assertEquals(4, permissionRepository.count());
jdbcTemplate.execute("insert into permission (name) values ('foo');");
assertEquals(5, countRowsInTable("permission"));
assertEquals(5, permissionRepository.count());
Permission p = permissionRepository.findOne(1);
assertNotNull(p);
assertEquals("CREATE_USER", p.getName());
jdbcTemplate.execute("update permission set name = 'BAR' where id = 1;");
// This does not execute select
p = permissionRepository.findOne(1);
assertNotNull(p);
assertEquals("CREATE_USER", p.getName()); // OMG!
TestTransaction.flagForCommit();
TestTransaction.end();
// Transaction has been committed, so we can get the new result
p = permissionRepository.findOne(1);
assertEquals("BAR", p.getName()); // This is the really expected result
}
public void testLockRevertedOnRollback() throws NotSupportedException, SystemException
{
// Preconditions of test
assertEquals(LockStatus.NO_LOCK, lockService.getLockStatus(noAspectNode));
assertFalse(lockService.isLocked(noAspectNode));
assertEquals(LockStatus.NO_LOCK, lockService.getLockStatus(rootNodeRef));
assertFalse(lockService.isLocked(rootNodeRef));
// Lock noAspectNode
lockService.lock(noAspectNode, LockType.WRITE_LOCK, 0, Lifetime.EPHEMERAL);
// Lock rootNodeRef
lockService.lock(rootNodeRef, LockType.NODE_LOCK, 0, Lifetime.EPHEMERAL);
// Sometime later, a refresh occurs (so this should not be reverted to unlocked, but to this state)
lockService.lock(rootNodeRef, LockType.NODE_LOCK, 3600, Lifetime.EPHEMERAL);
// Rollback
TestTransaction.end();
// This lock should not be present.
assertEquals(LockStatus.NO_LOCK, lockService.getLockStatus(noAspectNode));
assertFalse(lockService.isLocked(noAspectNode));
// This lock should still be present.
assertEquals(LockStatus.LOCK_OWNER, lockService.getLockStatus(rootNodeRef));
assertTrue(lockService.isLocked(rootNodeRef));
}
@Test
public void testAddVersionableAspectWithMajorVersionType()
{
// MAJOR version-type specified when adding the aspect
NodeRef nodeRef = createNodeWithVersionType(VersionType.MAJOR);
TestTransaction.flagForCommit();
TestTransaction.end();
assertCorrectVersionLabel(nodeRef, "1.0");
}
@Test
public void testAutoVersionOff()
{
// Create a versionable node
final NodeRef versionableNode = createNewVersionableNode();
this.dbNodeService.setProperty(versionableNode, ContentModel.PROP_AUTO_VERSION, false);
TestTransaction.flagForCommit();
TestTransaction.end();
// The initial version should have been created now
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Object>()
{
public Object execute() throws Exception
{
// Add some content
ContentWriter contentWriter = contentService.getWriter(versionableNode, ContentModel.PROP_CONTENT, true);
assertNotNull(contentWriter);
contentWriter.putContent(UPDATED_CONTENT_1);
return null;
}
});
// Now lets have a look and make sure we have the correct number of entries in the version history
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Object>()
{
public Object execute() throws Exception
{
VersionHistory versionHistory = versionService.getVersionHistory(versionableNode);
assertNotNull(versionHistory);
assertEquals(1, versionHistory.getAllVersions().size());
return null;
}
});
}
/**
* MNT-2641: The {@link ContentModel#ASPECT_WORKING_COPY} aspect cannot be removed from a working copy
*/
@Test
public void testDeleteWorkingCopyAspect()
{
// Create a FolderA
final NodeRef folderA = createFolder("DeleteCopiedFromAspectFromWorkingCopy_" + GUID.generate());
// Create content in FolderA
final NodeRef orig = createContent("original_" + GUID.generate(), folderA);
// Check out the document
NodeRef workingCopy = this.cociService.checkout(orig);
assertNotNull(workingCopy);
assertTrue("cm:workingCopy aspect not found on working copy.",
nodeService.hasAspect(workingCopy, ContentModel.ASPECT_WORKING_COPY));
assertTrue("cm:copiedFrom aspect not found on working copy.",
nodeService.hasAspect(workingCopy, ContentModel.ASPECT_COPIEDFROM));
TestTransaction.flagForCommit();
TestTransaction.end();
// try to delete cm:copiedfrom aspect from working copy - must be allowed
nodeService.removeAspect(workingCopy, ContentModel.ASPECT_COPIEDFROM);
// Try to delete cm:workingcopy aspect from working copy - must be denied
try
{
nodeService.removeAspect(workingCopy, ContentModel.ASPECT_WORKING_COPY);
fail("Should not be able to remove cm:workingcopy");
}
catch (UnsupportedOperationException e)
{
// Expected
}
}
/**
* Ensure that transactionless calls are handled
*/
public void testCallWithoutTxn()
{
TestTransaction.flagForCommit();
TestTransaction.end();
nodeService.getAllRootNodes(rootNodeRef.getStoreRef());
}
@Test(expected = IllegalStateException.class)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void endTxWithNonExistentTransactionContext() {
TestTransaction.end();
}
/**
* From 4.0.1 we support 'transient' thumbnail failure. This occurs when the ContentTransformer
* cannot attempt to perform the transformation for some reason (e.g. process/service unavailable) and wishes
* to decline the request. Such 'failures' should not lead to the addition of the {@link ContentModel#ASPECT_FAILED_THUMBNAIL_SOURCE}
* aspect.
*
* @since 4.0.1
*/
@Test
public void testCreateTransientlyFailingThumbnail() throws Exception
{
Map<QName, Serializable> props = new HashMap<QName, Serializable>();
props.put(ContentModel.PROP_NAME, "transientThumbnail.transientThumbnail");
final NodeRef testNode = this.secureNodeService.createNode(folder, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "transientThumbnail.transientThumbnail"),
ContentModel.TYPE_CONTENT, props).getChildRef();
// Modified test to add content. Having no content was failing to find a transformer with Legacy, but now
// does not with both Legacy and Local transforms. As a result the test was passing for the wrong reason.
secureNodeService.setProperty(testNode, ContentModel.PROP_CONTENT,
new ContentData(null, TEST_FAILING_MIME_TYPE, 0L, null));
File testFile = AbstractContentTransformerTest.loadNamedQuickTestFile("quick.pdf");
assertNotNull("Failed to load required test file.", testFile);
ContentWriter writer = contentService.getWriter(testNode, ContentModel.PROP_CONTENT, true);
writer.setMimetype(TEST_FAILING_MIME_TYPE);
writer.setEncoding("UTF-8");
writer.putContent(testFile);
logger.debug("Running failing thumbnail on " + testNode);
// Make sure the source node is correctly set up before we start
// It should not be renditioned and should not be marked as having any failed thumbnails.
assertFalse(secureNodeService.hasAspect(testNode, RenditionModel.ASPECT_RENDITIONED));
assertFalse(secureNodeService.hasAspect(testNode, ContentModel.ASPECT_FAILED_THUMBNAIL_SOURCE));
TestTransaction.flagForCommit();
TestTransaction.end();
// Attempt to perform a thumbnail that we know will fail.
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
ThumbnailDefinition thumbnailDef = thumbnailService.getThumbnailRegistry().getThumbnailDefinition("doclib");
Action createThumbnailAction = ThumbnailHelper.createCreateThumbnailAction(thumbnailDef, services);
actionService.executeAction(createThumbnailAction, testNode, true, true);
return null;
}
});
// The thumbnail attempt has now failed. But in this case the compensating action should NOT have been scheduled.
// We'll wait briefly in case it has erroneously been scheduled.
Thread.sleep(3000); // This should be long enough for the compensating action to run - if it has been scheduled, which it shouldn't.
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
assertFalse("Node should not have renditioned aspect", secureNodeService.hasAspect(testNode, RenditionModel.ASPECT_RENDITIONED));
assertFalse("Node should not have failed thumbnails aspect", secureNodeService.hasAspect(testNode, ContentModel.ASPECT_FAILED_THUMBNAIL_SOURCE));
return null;
}
});
}
/**
* Test the getWorkingCopy method
*/
@Test
public void testETWOTWO_733()
{
NodeRef origNodeRef = nodeService.createNode(
this.rootNodeRef,
ContentModel.ASSOC_CHILDREN,
QName.createQName("test2"),
ContentModel.TYPE_CONTENT).getChildRef();
// Make a copy of the node
this.copyService.copyAndRename(
origNodeRef,
this.rootNodeRef,
ContentModel.ASSOC_CHILDREN,
QName.createQName("test6"),
false);
NodeRef wk1 = cociService.getWorkingCopy(origNodeRef);
assertNull(wk1);
// Check the document out
final NodeRef workingCopy = cociService.checkout(origNodeRef);
// Need to commit the transaction in order to get the indexer to run
TestTransaction.flagForCommit();
TestTransaction.end();
final NodeRef finalNodeRef = origNodeRef;
NodeRef wk3 = this.transactionService.getRetryingTransactionHelper().doInTransaction(
new RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute()
{
NodeRef wk2 = cociService.getWorkingCopy(finalNodeRef);
assertNotNull(wk2);
assertEquals(workingCopy, wk2);
cociService.cancelCheckout(workingCopy);
return cociService.getWorkingCopy(nodeRef);
}
});
assertNull(wk3);
}
@Test
public void testDeleteSpaceWithExecuteScriptRule() throws Exception
{
TestTransaction.flagForCommit();
TestTransaction.end();
// So we don't hang indefinitely waiting for the outer transaction
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Object>()
{
public Object execute()
{
NodeRef storeRootNodeRef = nodeService.getRootNode(new StoreRef("workspace://SpacesStore"));
// get company_home nodeRef
NodeRef companyHomeNodeRef = searchService.selectNodes(storeRootNodeRef, "/app:company_home", null, namespaceService, false).get(0);
assertNotNull("NodeRef company_home is null", companyHomeNodeRef);
// create test folder in company_home
QName testFolderName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "ISSUE_ETWOTWO_738_" + System.currentTimeMillis());
ChildAssociationRef childAssocRef = nodeService.createNode(companyHomeNodeRef, ContentModel.ASSOC_CONTAINS, testFolderName, ContentModel.TYPE_FOLDER);
NodeRef testFolderNodeRef = childAssocRef.getChildRef();
// get script nodeRef
NodeRef scriptRef = searchService.selectNodes(storeRootNodeRef, "/app:company_home/app:dictionary/app:scripts/cm:backup.js.sample", null, namespaceService, false).get(0);
assertNotNull("NodeRef script is null", scriptRef);
// create rule
Rule rule = new Rule();
rule.setRuleType("inbound");
rule.setTitle("rule title " + System.currentTimeMillis());
CompositeAction compositeAction = actionService.createCompositeAction();
rule.setAction(compositeAction);
// add the conditions to the rule
ActionCondition condition = actionService.createActionCondition("no-condition");
condition.setParameterValues(new HashMap<String, Serializable>());
condition.setInvertCondition(false);
compositeAction.addActionCondition(condition);
// add the action to the rule
Action action = actionService.createAction("script");
Map<String, Serializable> repoActionParams = new HashMap<String, Serializable>();
repoActionParams.put("script-ref", scriptRef);
action.setParameterValues(repoActionParams);
compositeAction.addAction(action);
// save rule
ruleService.saveRule(testFolderNodeRef, rule);
// delete node with rule
nodeService.deleteNode(testFolderNodeRef);
return null;
}
}, false, true);
}
@Test(expected=AlfrescoRuntimeException.class)
public void testImportingSameNamespaceFailsWithinSingleModel() throws Exception
{
// Create model
PropertyMap properties = new PropertyMap(1);
properties.put(ContentModel.PROP_MODEL_ACTIVE, true);
final NodeRef modelNode = this.nodeService.createNode(
this.rootNodeRef,
ContentModel.ASSOC_CHILDREN,
QName.createQName(NamespaceService.ALFRESCO_URI, "dictionaryModels"),
ContentModel.TYPE_DICTIONARY_MODEL,
properties).getChildRef();
assertNotNull(modelNode);
TestTransaction.flagForCommit();
TestTransaction.end();
// update model to introduce self referencing dependency
try
{
RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
txnHelper.setMaxRetries(1);
txnHelper.doInTransaction(new RetryingTransactionCallback<Void>() {
public Void execute() throws Exception {
ContentWriter contentWriter = contentService.getWriter(modelNode, ContentModel.PROP_CONTENT, true);
contentWriter.setEncoding("UTF-8");
contentWriter.setMimetype(MimetypeMap.MIMETYPE_XML);
contentWriter.putContent(Thread.currentThread().getContextClassLoader().getResourceAsStream("dictionary/modelWithCurrentNamespaceImported.xml"));
return null;
}
}, false, true);
fail("Validation should fail as a circular dependency was introduced");
} catch(AlfrescoRuntimeException e)
{
assertTrue(e.getCause().getMessage().contains("URI http://www.alfresco.org/model/dictionary/1.0 cannot be imported as it is already contained in the model's namespaces"));
throw e;
}
//delete model
finally
{
transactionService.getRetryingTransactionHelper().doInTransaction(
new RetryingTransactionCallback<Object>() {
public Object execute() throws Exception {
// Delete the model
DictionaryModelTypeTest.this.nodeService.deleteNode(modelNode);
return null;
}
}, false, true);
}
}
/**
* Test execution as per MNT-13055.
* <p>
* When we use the ExecuteAllRulesActionExecuter to explicitly (e.g. "manually")
* execute all the rules on a folder and its subfolders, the rule must correctly
* recurse into those subfolders. This is a more simple test case than the steps
* described in the above issue, but is crucial to the more complicated case
* succeeding.
*/
public void testRuleAppliesToSubfoldersSuccessfully()
{
final NodeRef rootFolder = this.nodeService.createNode(
this.rootNodeRef,
ContentModel.ASSOC_CHILDREN,
QName.createQName("{test}rootFolderForTest"),
ContentModel.TYPE_FOLDER).getChildRef();
final NodeRef folderA = fileFolderService.
create(rootFolder, "folderA", ContentModel.TYPE_FOLDER).getNodeRef();
NodeRef fileA = createFile(folderA, "fileA.txt").getNodeRef();
final NodeRef folderB = fileFolderService.
create(folderA, "folderB", ContentModel.TYPE_FOLDER).getNodeRef();
NodeRef fileB = createFile(folderB, "fileB.txt").getNodeRef();
TestTransaction.flagForCommit();
TestTransaction.end();
// On RootFolder create a rule
transactionHelper.doInTransaction(() -> {
Rule rule1 = new Rule();
rule1.setRuleType(RuleType.INBOUND);
Action action1 = actionService.createAction(AddFeaturesActionExecuter.NAME);
action1.setParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_CLASSIFIABLE);
rule1.setAction(action1);
rule1.applyToChildren(true);
rule1.setExecuteAsynchronously(false);
ruleService.enableRule(rule1);
ruleService.saveRule(rootFolder, rule1);
return null;
});
// Check the the docs don't have the aspects yet
transactionHelper.doInTransaction(() -> {
assertFalse(nodeService.hasAspect(folderA, ContentModel.ASPECT_CLASSIFIABLE));
assertFalse(nodeService.hasAspect(folderB, ContentModel.ASPECT_CLASSIFIABLE));
assertFalse(nodeService.hasAspect(fileA, ContentModel.ASPECT_CLASSIFIABLE));
assertFalse(nodeService.hasAspect(fileB, ContentModel.ASPECT_CLASSIFIABLE));
return null;
});
// Execute the action
transactionHelper.doInTransaction(() -> {
Map<String, Serializable> actionParams = new HashMap<>();
actionParams.put(ExecuteAllRulesActionExecuter.PARAM_RUN_ALL_RULES_ON_CHILDREN, true);
actionParams.put(ExecuteAllRulesActionExecuter.PARAM_EXECUTE_INHERITED_RULES, true);
Action action = actionService.createAction(ExecuteAllRulesActionExecuter.NAME, actionParams);
executer.execute(action, rootFolder);
return null;
});
transactionHelper.doInTransaction(() -> {
assertTrue(nodeService.hasAspect(folderA, ContentModel.ASPECT_CLASSIFIABLE));
assertTrue(nodeService.hasAspect(folderB, ContentModel.ASPECT_CLASSIFIABLE));
assertTrue(nodeService.hasAspect(fileA, ContentModel.ASPECT_CLASSIFIABLE));
assertTrue(nodeService.hasAspect(fileB, ContentModel.ASPECT_CLASSIFIABLE));
return null;
});
}
@Test
public void whenProgrammaticTransactionCommit_thenEntityIsInDatabase() {
assertTrue(TestTransaction.isActive());
//Save an entity and commit.
Session session = sessionFactory.getCurrentSession();
TestEntity newEntity = new TestEntity();
newEntity.setId(1);
session.save(newEntity);
TestEntity searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
assertTrue(TestTransaction.isFlaggedForRollback());
TestTransaction.flagForCommit();
TestTransaction.end();
assertFalse(TestTransaction.isFlaggedForRollback());
assertFalse(TestTransaction.isActive());
//Check that the entity is still there in a new transaction,
//then delete it, but don't commit.
TestTransaction.start();
assertTrue(TestTransaction.isFlaggedForRollback());
assertTrue(TestTransaction.isActive());
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
session.delete(searchEntity);
session.flush();
TestTransaction.end();
assertFalse(TestTransaction.isActive());
//Check that the entity is still there in a new transaction,
//then delete it and commit.
TestTransaction.start();
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
session.delete(searchEntity);
session.flush();
assertTrue(TestTransaction.isActive());
TestTransaction.flagForCommit();
TestTransaction.end();
assertFalse(TestTransaction.isActive());
//Check that the entity is no longer there in a new transaction.
TestTransaction.start();
assertTrue(TestTransaction.isActive());
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNull(searchEntity);
}