下面列出了org.springframework.test.context.transaction.TestTransaction#flagForCommit ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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 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 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 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 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");
}
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 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 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;
}
});
}
@Test
public void testAddVersionableAspectWithNoVersionType()
{
// No version-type specified when adding the aspect
NodeRef nodeRef = createNodeWithVersionType(null);
TestTransaction.flagForCommit();
TestTransaction.end();
assertCorrectVersionLabel(nodeRef, "1.0");
}
/**
* Deletes a child node and then iterates over the children of the parent node,
* getting the QName. This caused some issues after we did some optimization
* using lazy loading of the associations.
*/
public void testLazyLoadIssue() throws Exception
{
Map<QName, ChildAssociationRef> assocRefs = buildNodeGraph();
// commit results
TestTransaction.flagForCommit();
TestTransaction.end();
UserTransaction userTransaction = txnService.getUserTransaction();
try
{
userTransaction.begin();
ChildAssociationRef n6pn8Ref = assocRefs.get(QName.createQName(BaseNodeServiceTest.NAMESPACE, "n6_p_n8"));
NodeRef n6Ref = n6pn8Ref.getParentRef();
NodeRef n8Ref = n6pn8Ref.getChildRef();
// delete n8
nodeService.deleteNode(n8Ref);
// get the parent children
List<ChildAssociationRef> assocs = nodeService.getChildAssocs(n6Ref);
for (ChildAssociationRef assoc : assocs)
{
// just checking
}
userTransaction.commit();
}
catch(Exception e)
{
try { userTransaction.rollback(); } catch (IllegalStateException ee) {}
throw e;
}
}
/**
* See REPO-2519, MNT-17113
*
* @throws IOException
*/
@Test
public void testIfNodesExistsAfterCreateThumbnail() throws IOException
{
// Add the log appender to the root logger
LogErrorAppender logErrorAppender = new LogErrorAppender();
Logger.getRootLogger().addAppender(logErrorAppender);
// create content node for thumbnail node
NodeRef pdfOrig = createOriginalContent(folder, MimetypeMap.MIMETYPE_PDF);
QName qname = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "doclib");
ThumbnailDefinition details = thumbnailService.getThumbnailRegistry().getThumbnailDefinition(qname.getLocalName());
TestTransaction.flagForCommit();
TestTransaction.end();
// create thumbnail
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
// Delete the content node (pdfOrig) before the afterCommit code is executed
TestNodeDeleterListener testNodeDeleterListener = new TestNodeDeleterListener(pdfOrig);
// It needs to have a higher priority as the implemented afterCommit. The priority in order are (0,1,2,3,4)
AlfrescoTransactionSupport.bindListener(testNodeDeleterListener, 1);
thumbnailService.createThumbnail(pdfOrig, ContentModel.PROP_CONTENT, MimetypeMap.MIMETYPE_IMAGE_JPEG, details.getTransformationOptions(), "doclib");
return null;
}
}, false, true);
assertEquals("There should be no error anymore", 0, logErrorAppender.getLog().size());
}
/**
* 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;
});
}
/**
* Check that the maximum string lengths can be adjusted up and down.
* Note that this test ONLY works for MySQL because the other databases cannot support more than 1024 characters
* in the string_value column and the value may not be set to less than 1024.
*
* @see SchemaBootstrap#DEFAULT_MAX_STRING_LENGTH
*/
@SuppressWarnings("deprecation")
public void testMySQLInnoDBNodeStringLengthWorker() throws Exception
{
TestTransaction.flagForCommit();
TestTransaction.end();
// Skip of the dialect if not MySQL (also skip for MySQL Cluster NDB)
Dialect dialect = (Dialect) applicationContext.getBean("dialect");
if ((dialect instanceof MySQLClusterNDBDialect) || (! (dialect instanceof MySQLInnoDBDialect)))
{
return;
}
SchemaBootstrap schemaBootstrap = (SchemaBootstrap) applicationContext.getBean("schemaBootstrap");
assertEquals("Expected max string length to be MAX", Integer.MAX_VALUE, SchemaBootstrap.getMaxStringLength());
NodeStringLengthWorker worker = (NodeStringLengthWorker) applicationContext.getBean("nodeStringLengthWorker");
// If we run this worker just to get everything into the correct starting state.
// If it does not work, then that will be detected later anyway
NodeStringLengthWorkResult result = worker.execute();
assertTrue(result.getPropertiesProcessed() > 0);
assertEquals(0, result.getErrors());
// Now set the max string length to DEFAULT_MAX_STRING_LENGTH characters
schemaBootstrap.setMaximumStringLength(SchemaBootstrap.DEFAULT_MAX_STRING_LENGTH);
schemaBootstrap.onApplicationEvent(new ContextRefreshedEvent(applicationContext));
// Move any values persisted before the test
result = worker.execute();
int firstPassChanged = result.getPropertiesChanged();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < SchemaBootstrap.DEFAULT_MAX_STRING_LENGTH + 1; i++)
{
sb.append("A");
}
final String longString = sb.toString();
// Persist the property using the default MAX_VALUE so that it goes into the string_value
schemaBootstrap.setMaximumStringLength(Integer.MAX_VALUE);
schemaBootstrap.onApplicationEvent(new ContextRefreshedEvent(applicationContext));
txnService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
nodeService.setProperty(rootNodeRef, PROP_QNAME_STRING_VALUE, longString);
return null;
}
});
// The worker should do nothing
result = worker.execute();
assertEquals(firstPassChanged, result.getPropertiesChanged());
// Now bring the limit down to the match for other DBs
schemaBootstrap.setMaximumStringLength(SchemaBootstrap.DEFAULT_MAX_STRING_LENGTH);
schemaBootstrap.onApplicationEvent(new ContextRefreshedEvent(applicationContext));
result = worker.execute();
assertEquals(firstPassChanged + 1, result.getPropertiesChanged());
// Put the limit back to the MySQL default and all the large values should go back into MySQL's TEXT field
schemaBootstrap.setMaximumStringLength(Integer.MAX_VALUE);
schemaBootstrap.onApplicationEvent(new ContextRefreshedEvent(applicationContext));
result = worker.execute();
assertEquals(firstPassChanged + 1, result.getPropertiesChanged());
// Check that our string is still OK
String checkLongString = txnService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<String>()
{
@Override
public String execute() throws Throwable
{
return (String) nodeService.getProperty(rootNodeRef, PROP_QNAME_STRING_VALUE);
}
});
assertEquals("String manipulation corrupted the long string value. ", longString, checkLongString);
}
@Test
public void testOnContentCreateTrigger()
{
TestRuleType nodeCreate = createTestRuleType(ON_CREATE_NODE_TRIGGER);
assertFalse(nodeCreate.rulesTriggered);
NodeRef nodeRef = this.nodeService.createNode(
this.rootNodeRef,
ContentModel.ASSOC_CHILDREN,
ContentModel.ASSOC_CHILDREN,
ContentModel.TYPE_CONTENT).getChildRef();
assertTrue(nodeCreate.rulesTriggered);
// Terminate the transaction
TestTransaction.flagForCommit();
TestTransaction.end();
TestTransaction.start();
TestRuleType contentCreate = createTestRuleType(ON_CONTENT_CREATE_TRIGGER);
assertFalse(contentCreate.rulesTriggered);
// Try and trigger the type
ContentWriter contentWriter = this.contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
contentWriter.setEncoding("UTF-8");
contentWriter.putContent("some content");
// Check to see if the rule type has been triggered
assertTrue(contentCreate.rulesTriggered);
// Try and trigger the type (again)
contentCreate.rulesTriggered = false;
assertFalse(contentCreate.rulesTriggered);
ContentWriter contentWriter2 = this.contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
contentWriter2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
contentWriter2.setEncoding("UTF-8");
contentWriter2.putContent("some content");
// Check to see if the rule type has been triggered
assertFalse(contentCreate.rulesTriggered);
}
/**
* Test for MNT-13055:
*
* We create a folder structure thus:
* <pre>
* rootFolder (rule: add an aspect)
* |
* +- folderA ("do not inherit rules" + link to rootFolder's rule set)
* |
* +- fileA
* |
* +- folderB
* |
* +- fileB
* </pre>
* This test case specifies a rule on rootFolder that adds an aspect to all files within.
* folderA has the ignoreInheritedRules aspect applied, but also links to rootFolder's rule set.
* <p>
* We then explicitly execute folderA's rules, including for subfolders. Ultimately, we want to
* know that fileB did indeed have the ruleset executed on it, and therefore gained the classifiable aspect.
*/
public void testRulesFireOnNonInheritedFolderUsingLinkedRuleSetInstead()
{
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();
// Set folderA to "Don't Inherit Rules".
nodeService.addAspect(folderA, ASPECT_IGNORE_INHERITED_RULES, Collections.emptyMap());
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();
// Create a rule on rootFolder
Rule rule = new Rule();
rule.setRuleType(RuleType.INBOUND);
Action action = actionService.createAction(AddFeaturesActionExecuter.NAME);
action.setParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_CLASSIFIABLE);
rule.setAction(action);
// It mustn't matter whether this rule "applies to children", since we'll explicitly
// run it on "the folder and its subfolders".
rule.applyToChildren(false);
rule.setExecuteAsynchronously(false);
ruleService.enableRule(rule);
ruleService.saveRule(rootFolder, rule);
// Link to Rule Set of rootFolder to folderA
Action linkAction = actionService.createAction(LinkRules.NAME);
linkAction.setParameterValue(LinkRules.PARAM_LINK_FROM_NODE, rootFolder);
linkAction.setExecuteAsynchronously(false);
actionService.executeAction(linkAction, folderA);
TestTransaction.flagForCommit();
TestTransaction.end();
transactionHelper.doInTransaction(() -> {
assertFalse(nodeService.hasAspect(folderA, ContentModel.ASPECT_CLASSIFIABLE));
assertFalse(nodeService.hasAspect(fileA, ContentModel.ASPECT_CLASSIFIABLE));
assertFalse(nodeService.hasAspect(folderB, ContentModel.ASPECT_CLASSIFIABLE));
assertFalse(nodeService.hasAspect(fileB, ContentModel.ASPECT_CLASSIFIABLE));
return null;
});
// rootFolder: "Run rule for this folder and its subfolders".
transactionHelper.doInTransaction(() -> {
Map<String, Serializable> actionParams = new HashMap<>();
actionParams.put(ExecuteAllRulesActionExecuter.PARAM_RUN_ALL_RULES_ON_CHILDREN, true);
// In Share, when you manually trigger rules on a folder, this parameter (execute-inherited-rules)
// will be false if the aspect rule:ignoreInheritedRules is present, and true otherwise.
actionParams.put(ExecuteAllRulesActionExecuter.PARAM_EXECUTE_INHERITED_RULES, false);
Action rulesAction = actionService.createAction(ExecuteAllRulesActionExecuter.NAME, actionParams);
executer.execute(rulesAction, folderA);
return null;
});
transactionHelper.doInTransaction(() -> {
// We're running the rule on folderA, so the folder itself won't be processed.
assertFalse(nodeService.hasAspect(folderA, ContentModel.ASPECT_CLASSIFIABLE));
// The contents of folderA will all have the aspect added.
assertTrue(nodeService.hasAspect(fileA, ContentModel.ASPECT_CLASSIFIABLE));
assertTrue(nodeService.hasAspect(folderB, ContentModel.ASPECT_CLASSIFIABLE));
// The contents of folderB will all have the aspect added.
assertTrue(nodeService.hasAspect(fileB, ContentModel.ASPECT_CLASSIFIABLE));
return null;
});
}
public void testAspectRemovalWithCommit() throws Throwable
{
// Create a node to add the aspect to
NodeRef sourceNodeRef = nodeService.createNode(
rootNodeRef,
ASSOC_TYPE_QNAME_TEST_CHILDREN,
QName.createQName(BaseNodeServiceTest.NAMESPACE, "testAspectRemoval-source"),
ContentModel.TYPE_CONTAINER).getChildRef();
// Create a target for the associations
NodeRef targetNodeRef = nodeService.createNode(
rootNodeRef,
ASSOC_TYPE_QNAME_TEST_CHILDREN,
QName.createQName(BaseNodeServiceTest.NAMESPACE, "testAspectRemoval-target"),
ContentModel.TYPE_CONTAINER).getChildRef();
// Add the aspect to the source
nodeService.addAspect(sourceNodeRef, ASPECT_WITH_ASSOCIATIONS, null);
// Make the associations
nodeService.addChild(
sourceNodeRef,
targetNodeRef,
ASSOC_ASPECT_CHILD_ASSOC,
QName.createQName(NAMESPACE, "aspect-child"));
nodeService.createAssociation(sourceNodeRef, targetNodeRef, ASSOC_ASPECT_NORMAL_ASSOC);
// Check that the correct associations are present
assertEquals("Expected exactly one child",
1, nodeService.getChildAssocs(sourceNodeRef).size());
assertEquals("Expected exactly one target",
1, nodeService.getTargetAssocs(sourceNodeRef, RegexQNamePattern.MATCH_ALL).size());
// Force a commit here
TestTransaction.flagForCommit();
TestTransaction.end();
// start another transaction to remove the aspect
UserTransaction txn = txnService.getUserTransaction();
txn.begin();
try
{
Set<QName> aspects = nodeService.getAspects(sourceNodeRef);
int noAspectsBefore = aspects.size();
// Now remove the aspect
nodeService.removeAspect(sourceNodeRef, ASPECT_WITH_ASSOCIATIONS);
// Check that the associations were removed
assertEquals("Expected exactly zero child",
0, nodeService.getChildAssocs(sourceNodeRef).size());
assertEquals("Expected exactly zero target",
0, nodeService.getTargetAssocs(sourceNodeRef, RegexQNamePattern.MATCH_ALL).size());
aspects = nodeService.getAspects(sourceNodeRef);
assertEquals("Expected exactly one less aspect",
noAspectsBefore-1, aspects.size());
txn.commit();
}
catch (Throwable e)
{
try { txn.rollback(); } catch (Throwable ee) {}
throw e;
}
}
@Test
public void testImportingSameNamespaceFails() throws Exception
{
// just to make sure we don't regress ACE-5852, some tests should run as System
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
// Create model
final NodeRef modelNode = createActiveModel("dictionary/testModel.xml");
TestTransaction.flagForCommit();
TestTransaction.end();
// add second model to introduce self referencing dependency
TestTransaction.start();
PropertyMap properties = new PropertyMap(1);
properties.put(ContentModel.PROP_MODEL_ACTIVE, true);
final NodeRef modelNode2 = this.nodeService.createNode(
this.rootNodeRef,
ContentModel.ASSOC_CHILDREN,
QName.createQName(NamespaceService.ALFRESCO_URI, "dictionaryModels"),
ContentModel.TYPE_DICTIONARY_MODEL,
properties).getChildRef();
TestTransaction.flagForCommit();
TestTransaction.end();
try
{
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {
public Void execute() throws Exception {
ContentWriter contentWriter = DictionaryModelTypeTest.this.contentService.getWriter(modelNode2, ContentModel.PROP_CONTENT, true);
contentWriter.putContent(Thread.currentThread().getContextClassLoader().getResourceAsStream("dictionary/testModel2.xml"));
return null;
}
});
fail("Validation should fail as a circular dependency was introduced");
} catch(AlfrescoRuntimeException e)
{
assertTrue(e.getCause().getMessage().contains("URI mage.model cannot be imported as it is already contained in the model's namespaces"));
}
//delete model
finally
{
transactionService.getRetryingTransactionHelper().doInTransaction(
new RetryingTransactionCallback<Object>() {
public Object execute() throws Exception {
// Delete the model
DictionaryModelTypeTest.this.nodeService.deleteNode(modelNode);
return null;
}
});
}
}
@Before
public void before() throws Exception
{
super.before();
this.namespaceService= (NamespaceService) this.applicationContext.getBean("namespaceService");
this.renditionService = (RenditionService) this.applicationContext.getBean("renditionService");
this.repositoryHelper = (Repository) this.applicationContext.getBean("repositoryHelper");
this.scriptService = (ScriptService) this.applicationContext.getBean("scriptService");
this.transactionHelper = (RetryingTransactionHelper) this.applicationContext
.getBean("retryingTransactionHelper");
// Set the current security context as admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
// Register our test rendering engine if needed
DummyHelloWorldRenditionEngine.registerIfNeeded(this.applicationContext);
// Create test folders
NodeRef companyHome = this.repositoryHelper.getCompanyHome();
// Create the test folder used for these tests
this.testTargetFolder = createNode(companyHome, "testFolder-" + GUID.generate(), ContentModel.TYPE_FOLDER);
// Create the node used as a content supplier for tests
this.nodeWithDocContent = createContentNode(companyHome, "testDocContent-" + GUID.generate());
// Put some known PDF content in it.
File pdfQuickFile = AbstractContentTransformerTest.loadQuickTestFile("pdf");
assertNotNull("Failed to load required test file.", pdfQuickFile);
nodeService.setProperty(nodeWithDocContent, ContentModel.PROP_CONTENT, new ContentData(null,
MimetypeMap.MIMETYPE_PDF, 0L, null));
ContentWriter writer = contentService.getWriter(nodeWithDocContent, ContentModel.PROP_CONTENT, true);
writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
writer.setEncoding("UTF-8");
writer.putContent(pdfQuickFile);
// Put the titled aspect on it - used for testing rendition updates
Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>();
titledProps.put(ContentModel.PROP_TITLE, "Original test title");
titledProps.put(ContentModel.PROP_DESCRIPTION, "Dummy description");
nodeService.addAspect(nodeWithDocContent, ContentModel.ASPECT_TITLED, titledProps);
// Create a test image
this.nodeWithImageContent = createContentNode(companyHome, "testImageNode-" + GUID.generate());
// Stream some well-known image content into the node.
URL url = RenditionServiceIntegrationTest.class.getClassLoader().getResource("images/gray21.512.png");
assertNotNull("url of test image was null", url);
File imageFile = new File(url.getFile());
setImageContentOnNode(nodeWithImageContent, MimetypeMap.MIMETYPE_IMAGE_PNG, imageFile);
// Create a test template node.
this.nodeWithFreeMarkerContent = createFreeMarkerNode(companyHome);
TestTransaction.flagForCommit();
TestTransaction.end();
TestTransaction.start();
}
/**
* Inbound rule must not be applied on failed thumbnail
*
* see MNT-10914
*/
@Test
public void testRuleExecutionOnFailedThumbnailChild() throws Exception
{
// create inbound rule on folder
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put("aspect-name", ContentModel.ASPECT_GEN_CLASSIFIABLE);
Rule rule = new Rule();
rule.setRuleType(RuleType.INBOUND);
Action action = this.actionService.createAction(AddFeaturesActionExecuter.NAME, params);
ActionCondition condition = this.actionService.createActionCondition(NoConditionEvaluator.NAME, null);
action.addActionCondition(condition);
rule.setAction(action);
rule.applyToChildren(true);
services.getRuleService().saveRule(folder, rule);
TestTransaction.flagForCommit();
TestTransaction.end();
final NodeRef corruptNode = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
return createCorruptedContent(folder);
}
});
// 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(corruptNode, ContentModel.ASPECT_FAILED_THUMBNAIL_SOURCE));
// 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, corruptNode, true, true);
return null;
}
});
// The thumbnail attempt has now failed. But a compensating action should have been scheduled that will mark the
// source node with a failure aspect. As that is an asynchronous action, we need to wait for that to complete.
Thread.sleep(3000); // This should be long enough for the compensating action to run.
final NodeRef failedThumbnailNode = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
assertTrue("corrupt node should have failed thumbnails aspect", secureNodeService.hasAspect(corruptNode, ContentModel.ASPECT_FAILED_THUMBNAIL_SOURCE));
Map<String, FailedThumbnailInfo> failedThumbnails = thumbnailService.getFailedThumbnails(corruptNode);
assertEquals("Wrong number of failed thumbnails", 1, failedThumbnails.size());
assertTrue("Missing QName for failed thumbnail", failedThumbnails.containsKey("doclib"));
final FailedThumbnailInfo doclibFailureInfo = failedThumbnails.get("doclib");
assertNotNull("Failure info was null", doclibFailureInfo);
return doclibFailureInfo.getFailedThumbnailNode();
}
});
assertTrue("Rule must not be executed on document", secureNodeService.hasAspect(corruptNode, ContentModel.ASPECT_GEN_CLASSIFIABLE));
assertFalse("Rule must not be executed on failed thumbnail", secureNodeService.hasAspect(failedThumbnailNode, ContentModel.ASPECT_GEN_CLASSIFIABLE));
}
@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);
}