mirror of
https://github.com/Alfresco/alfresco-community-repo.git
synced 2025-09-10 14:11:58 +00:00
Compare commits
62 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
a7d885c630 | ||
|
3fcbb076a2 | ||
|
9ab4d29ff6 | ||
|
1388a76dc7 | ||
|
1944186ef8 | ||
|
66ea8c0534 | ||
|
571f4b121d | ||
|
2f2e7ade80 | ||
|
2d69d44049 | ||
|
6ad58b137e | ||
|
4c086751e6 | ||
|
7cb98f2d5d | ||
|
55faedde51 | ||
|
32a524eb1f | ||
|
105702bf09 | ||
|
9e2e00c4a8 | ||
|
e79eac4fd8 | ||
|
20f9cfc42d | ||
|
5baee04dcc | ||
|
f821756021 | ||
|
ae68b517f1 | ||
|
24b249d93d | ||
|
5d9b11d121 | ||
|
902f3b5275 | ||
|
3801ed4d99 | ||
|
382a4799ae | ||
|
67c44a934d | ||
|
35a364beaa | ||
|
68ed04cc6d | ||
|
dc52bc107d | ||
|
ff110af9b3 | ||
|
87b2e0f060 | ||
|
fd9d47826e | ||
|
6e31f713f0 | ||
|
7a70b40cc0 | ||
|
96c437e6a4 | ||
|
6e4a7c1866 | ||
|
b72cf6f267 | ||
|
f65fc31601 | ||
|
4697e7bac2 | ||
|
50455c8730 | ||
|
2fac4d8a9b | ||
|
7a300dc9c9 | ||
|
a996cf1842 | ||
|
1d9d6ad0bb | ||
|
8ba67497e1 | ||
|
fd889628c6 | ||
|
50b9f5c612 | ||
|
e6bdd5738c | ||
|
4bf29ca69c | ||
|
f4f5fd4182 | ||
|
dfb6f50056 | ||
|
c7227d19c4 | ||
|
9b779facd9 | ||
|
f64d0a1b59 | ||
|
8974845671 | ||
|
a7ae83bbee | ||
|
ee1ac25bf6 | ||
|
8757f0ff2b | ||
|
37f5b637dd | ||
|
b369538a61 | ||
|
1f844ce199 |
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo-amps</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
|
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-governance-services-community-parent</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
|
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-governance-services-automation-community-repo</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
|
@@ -26,6 +26,7 @@
|
||||
*/
|
||||
package org.alfresco.rest.v0;
|
||||
|
||||
import static org.apache.http.HttpStatus.SC_OK;
|
||||
import static org.testng.Assert.assertTrue;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
@@ -36,6 +37,7 @@ import java.util.List;
|
||||
import org.alfresco.rest.core.v0.BaseAPI;
|
||||
import org.alfresco.rest.rm.community.model.audit.AuditEntry;
|
||||
import org.alfresco.rest.rm.community.util.PojoUtility;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.slf4j.Logger;
|
||||
@@ -58,6 +60,8 @@ public class RMAuditAPI extends BaseAPI
|
||||
private static final String RM_AUDIT_API = "{0}rma/admin/rmauditlog";
|
||||
private static final String RM_AUDIT_LOG_API = RM_AUDIT_API + "?{1}";
|
||||
|
||||
private static final String RM_AUDIT_LOG_AS_RECORD = "{0}node/{1}/rmauditlog";
|
||||
|
||||
/**
|
||||
* Returns a list of rm audit entries .
|
||||
*
|
||||
@@ -84,6 +88,21 @@ public class RMAuditAPI extends BaseAPI
|
||||
return PojoUtility.jsonToObject(auditEntries, AuditEntry.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of rm audit entries .
|
||||
*
|
||||
* @param user The username of the user to use.
|
||||
* @param password The password of the user.
|
||||
* @param size Maximum number of log entries to return
|
||||
* @return return All return log entries
|
||||
*/
|
||||
public List<AuditEntry> getRMAuditLogAll(String user, String password, final int size) {
|
||||
String parameters = "size=" + size;
|
||||
JSONArray auditEntries = doGetRequest(user, password,
|
||||
MessageFormat.format(RM_AUDIT_LOG_API,"{0}", parameters)).getJSONObject("data").getJSONArray("entries");
|
||||
return PojoUtility.jsonToObject(auditEntries, AuditEntry.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the list of audit entries.
|
||||
*
|
||||
@@ -100,5 +119,19 @@ public class RMAuditAPI extends BaseAPI
|
||||
&& getRMAuditLog(username, password, 100, null).size() == 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs the Audit Log as Record.
|
||||
*
|
||||
* @param username The username of the user to use.
|
||||
* @param password The password of the user.
|
||||
* @param recNodeRef The Record Node reference for which Audit log should be created as record
|
||||
* @param destinationNodeRef The Folder id Node reference where the html file should be placed
|
||||
* @throws AssertionError If the API call didn't create the Audit Log as Record.
|
||||
*/
|
||||
public HttpResponse logsAuditLogAsRecord(String username, String password, String recNodeRef, String destinationNodeRef) {
|
||||
JSONObject requestParams = new JSONObject();
|
||||
requestParams.put("destination", destinationNodeRef);
|
||||
return doPostJsonRequest(username, password, SC_OK, requestParams, RM_AUDIT_LOG_AS_RECORD,recNodeRef);
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -97,4 +97,16 @@ public class RecordFoldersAPI extends BaseAPI
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public HttpResponse reOpenRecordFolder(String user, String password, String recordFolder)
|
||||
{
|
||||
String recNodeRef = getNodeRefSpacesStore() + contentService.getNodeRef(user, password, RM_SITE_ID, recordFolder);
|
||||
|
||||
JSONObject requestParams = new JSONObject();
|
||||
requestParams.put("name", "openRecordFolder");
|
||||
requestParams.put("nodeRef", recNodeRef);
|
||||
|
||||
return doPostJsonRequest(user, password, SC_OK, requestParams, RM_ACTIONS_API);
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -360,4 +360,25 @@ public class RecordsAPI extends BaseAPI
|
||||
{
|
||||
return getNodeRefSpacesStore() + getItemNodeRef(username, password, recordPath + "/" + recordName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reopens the record given as parameter
|
||||
*
|
||||
* @param user the user declaring the document as record
|
||||
* @param password the user's password
|
||||
* @param recordName the record name
|
||||
* @return The HTTP Response.
|
||||
*/
|
||||
|
||||
public HttpResponse reOpenRecord(String user, String password, String recordName)
|
||||
{
|
||||
String recNodeRef = getNodeRefSpacesStore() + contentService.getNodeRef(user, password, RM_SITE_ID, recordName);
|
||||
|
||||
JSONObject requestParams = new JSONObject();
|
||||
requestParams.put("name", "undeclareRecord");
|
||||
requestParams.put("nodeRef", recNodeRef);
|
||||
|
||||
return doPostJsonRequest(user, password, SC_OK, requestParams, RM_ACTIONS_API);
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
* #%L
|
||||
* Alfresco Records Management Module
|
||||
* %%
|
||||
* Copyright (C) 2005 - 2022 Alfresco Software Limited
|
||||
* %%
|
||||
* This file is part of the Alfresco software.
|
||||
* -
|
||||
* If the software was purchased under a paid Alfresco license, the terms of
|
||||
* the paid license agreement will prevail. Otherwise, the software is
|
||||
* provided under the following open source license terms:
|
||||
* -
|
||||
* Alfresco is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
* -
|
||||
* Alfresco is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
* -
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
|
||||
* #L%
|
||||
*/
|
||||
package org.alfresco.rest.rm.community.audit;
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.alfresco.rest.rm.community.base.TestData.*;
|
||||
import static org.alfresco.rest.rm.community.model.audit.AuditEvents.ADD_TO_HOLD;
|
||||
import static org.alfresco.rest.rm.community.model.audit.AuditEvents.REMOVE_FROM_HOLD;
|
||||
import static org.alfresco.rest.rm.community.util.CommonTestUtils.generateTestPrefix;
|
||||
import static org.alfresco.utility.data.RandomData.getRandomName;
|
||||
import static org.alfresco.utility.report.log.Step.STEP;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.empty;
|
||||
import static org.hamcrest.core.IsNot.not;
|
||||
import static org.springframework.http.HttpStatus.CREATED;
|
||||
import static org.testng.AssertJUnit.*;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import org.alfresco.dataprep.CMISUtil;
|
||||
import org.alfresco.rest.rm.community.base.BaseRMRestTest;
|
||||
import org.alfresco.rest.rm.community.model.audit.AuditEntry;
|
||||
import org.alfresco.rest.rm.community.model.audit.AuditEvents;
|
||||
import org.alfresco.rest.rm.community.model.record.Record;
|
||||
import org.alfresco.rest.rm.community.model.recordcategory.RecordCategory;
|
||||
import org.alfresco.rest.rm.community.model.recordcategory.RecordCategoryChild;
|
||||
import org.alfresco.rest.rm.community.model.recordfolder.RecordFolder;
|
||||
import org.alfresco.rest.rm.community.model.user.UserRoles;
|
||||
import org.alfresco.rest.v0.HoldsAPI;
|
||||
import org.alfresco.rest.v0.service.RMAuditService;
|
||||
import org.alfresco.rest.v0.service.RoleService;
|
||||
import org.alfresco.utility.model.FileModel;
|
||||
import org.alfresco.utility.model.SiteModel;
|
||||
import org.alfresco.utility.model.UserModel;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.testng.annotations.AfterClass;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.DataProvider;
|
||||
import org.testng.annotations.Test;
|
||||
public class AuditHoldsTest extends BaseRMRestTest {
|
||||
private final String PREFIX = generateTestPrefix(AuditAddToHoldTests.class);
|
||||
private final String HOLD1 = PREFIX + "hold1";
|
||||
private SiteModel publicSite;
|
||||
private FileModel testFile;
|
||||
@Autowired
|
||||
private RMAuditService rmAuditService;
|
||||
@Autowired
|
||||
private HoldsAPI holdsAPI;
|
||||
@Autowired
|
||||
private RoleService roleService;
|
||||
private UserModel rmAdmin;
|
||||
private RecordCategory recordCategory;
|
||||
private RecordCategoryChild recordFolder1,recordFolder2;
|
||||
private List<AuditEntry> auditEntries;
|
||||
private String hold1NodeRef;
|
||||
public static final String RECORD_FOLDER_THREE = "record-folder-three";
|
||||
@BeforeClass(alwaysRun = true)
|
||||
public void preconditionForAuditAddToHoldTests()
|
||||
{
|
||||
createRMSiteIfNotExists();
|
||||
rmAdmin = roleService.createUserWithRMRole(UserRoles.ROLE_RM_ADMIN.roleId);
|
||||
|
||||
STEP("Create a hold");
|
||||
hold1NodeRef = holdsAPI.createHoldAndGetNodeRef(rmAdmin.getUsername(), rmAdmin.getPassword(), HOLD1, HOLD_REASON,
|
||||
HOLD_DESCRIPTION);
|
||||
|
||||
STEP("Create a collaboration site with a test file.");
|
||||
publicSite = dataSite.usingAdmin().createPublicRandomSite();
|
||||
testFile = dataContent.usingAdmin().usingSite(publicSite).createContent(CMISUtil.DocumentType.TEXT_PLAIN);
|
||||
|
||||
STEP("Create a record category with 2 folders and 1 record");
|
||||
recordCategory = createRootCategory(getRandomName("recordCategory"));
|
||||
recordFolder1 = createRecordFolder(recordCategory.getId(), PREFIX + "recFolder1");
|
||||
recordFolder2 = createRecordFolder(recordCategory.getId(), PREFIX + "recFolder2");
|
||||
Record recordToBeAdded = createElectronicRecord(recordFolder1.getId(), PREFIX + "record");
|
||||
assertStatusCode(CREATED);
|
||||
|
||||
STEP("Add some items to the hold, then remove them from the hold");
|
||||
final List<String> itemsList = asList(testFile.getNodeRefWithoutVersion(), recordToBeAdded.getId(), recordFolder2.getId());
|
||||
final List<String> holdsList = Collections.singletonList(HOLD1);
|
||||
holdsAPI.addItemToHold(rmAdmin.getUsername(), rmAdmin.getPassword(), recordToBeAdded.getId(), HOLD1);
|
||||
holdsAPI.removeItemsFromHolds(rmAdmin.getUsername(), rmAdmin.getPassword(), itemsList, holdsList);
|
||||
|
||||
STEP("Delete the record folder that was held");
|
||||
getRestAPIFactory().getRecordFolderAPI().deleteRecordFolder(recordFolder2.getId());
|
||||
|
||||
STEP("Rename the parent of the record that was held");
|
||||
RecordFolder recordFolder = RecordFolder.builder().name(RECORD_FOLDER_THREE).build();
|
||||
getRestAPIFactory().getRecordFolderAPI().updateRecordFolder(recordFolder, recordFolder1.getId());
|
||||
}
|
||||
/**
|
||||
* Data provider with hold events that have links to held items
|
||||
*
|
||||
* @return the hold events
|
||||
*/
|
||||
@DataProvider (name = "holdsEvents")
|
||||
public Object[][] getHoldEvents()
|
||||
{
|
||||
return new AuditEvents[][]
|
||||
{
|
||||
{ ADD_TO_HOLD },
|
||||
{ REMOVE_FROM_HOLD }
|
||||
};
|
||||
}
|
||||
@Test (dataProvider = "holdsEvents")
|
||||
public void checkItemPathLink(AuditEvents event) {
|
||||
auditEntries = rmAuditService.getAuditEntriesFilteredByEvent(getAdminUser(), event);
|
||||
assertFalse("Audit results should not be empty",auditEntries.size()==0);
|
||||
final String auditedEvent = event + " - " + testFile.getName();
|
||||
assertTrue("Audit results should contain one " + auditedEvent + " event",auditEntries.stream().anyMatch(e -> e.getEvent().startsWith(event.eventDisplayName)));
|
||||
STEP("Check the audit log contains only an entry for add to hold.");
|
||||
assertThat(auditEntries, is(not(empty())));
|
||||
}
|
||||
@AfterClass(alwaysRun = true)
|
||||
private void cleanup() {
|
||||
dataSite.usingAdmin().deleteSite(publicSite);
|
||||
deleteRecordFolder(recordFolder1.getId());
|
||||
deleteRecordFolder(recordFolder2.getId());
|
||||
deleteRecordCategory(recordCategory.getId());
|
||||
rmAuditService.clearAuditLog();
|
||||
}
|
||||
}
|
@@ -0,0 +1,244 @@
|
||||
/*
|
||||
* #%L
|
||||
* Alfresco Records Management Module
|
||||
* %%
|
||||
* Copyright (C) 2005 - 2022 Alfresco Software Limited
|
||||
* %%
|
||||
* This file is part of the Alfresco software.
|
||||
* -
|
||||
* If the software was purchased under a paid Alfresco license, the terms of
|
||||
* the paid license agreement will prevail. Otherwise, the software is
|
||||
* provided under the following open source license terms:
|
||||
* -
|
||||
* Alfresco is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
* -
|
||||
* Alfresco is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
* -
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
|
||||
* #L%
|
||||
*/
|
||||
package org.alfresco.rest.rm.community.audit;
|
||||
|
||||
import org.alfresco.rest.rm.community.base.BaseRMRestTest;
|
||||
import org.alfresco.rest.rm.community.model.audit.AuditEntry;
|
||||
import org.alfresco.rest.rm.community.model.record.Record;
|
||||
import org.alfresco.rest.rm.community.model.recordcategory.RecordCategory;
|
||||
import org.alfresco.rest.rm.community.model.recordcategory.RecordCategoryChild;
|
||||
import org.alfresco.rest.v0.RMAuditAPI;
|
||||
import org.alfresco.rest.v0.RMRolesAndActionsAPI;
|
||||
import org.alfresco.rest.v0.RecordsAPI;
|
||||
import org.alfresco.test.AlfrescoTest;
|
||||
import org.alfresco.utility.Utility;
|
||||
import org.alfresco.utility.model.UserModel;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.testng.AssertJUnit;
|
||||
import org.testng.annotations.AfterClass;
|
||||
import org.testng.annotations.AfterMethod;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.alfresco.rest.rm.community.model.fileplancomponents.FilePlanComponentAspects.ASPECTS_COMPLETED_RECORD;
|
||||
import static org.alfresco.rest.rm.community.util.CommonTestUtils.generateTestPrefix;
|
||||
import static org.alfresco.rest.rm.community.utils.FilePlanComponentsUtil.createRecordModel;
|
||||
import static org.springframework.http.HttpStatus.OK;
|
||||
import static org.springframework.test.util.AssertionErrors.assertTrue;
|
||||
import static org.testng.Assert.assertFalse;
|
||||
import static org.testng.Assert.fail;
|
||||
|
||||
public class ElectronicRecordAuditLogTest extends BaseRMRestTest {
|
||||
|
||||
private Optional<UserModel> rmAdmin;
|
||||
@Autowired
|
||||
private RMRolesAndActionsAPI rmRolesAndActionsAPI;
|
||||
@Autowired
|
||||
private RMAuditAPI auditLog;
|
||||
@Autowired
|
||||
private RecordsAPI recordApi;
|
||||
/* electronic record details */
|
||||
private static final String AUDIT_ELECTRONIC_RECORD = generateTestPrefix(ElectronicRecordAuditLogTest.class) + "electronic record";
|
||||
private static final String AUDIT_COMPLETE_REOPEN_ELECTRONIC_RECORD = "Complete Reopen Electronic Record";
|
||||
public static final String TITLE = "Title";
|
||||
public static final String DESCRIPTION = "Description";
|
||||
private RecordCategory category1;
|
||||
private RecordCategoryChild recordFolder1;
|
||||
private Record electronicRecord, electronicRecord2;
|
||||
|
||||
@BeforeClass(alwaysRun = true)
|
||||
public void electronicRecordsAuditLogSetup()
|
||||
{
|
||||
createRMSiteIfNotExists();
|
||||
rmAdmin = Optional.ofNullable(getDataUser().createRandomTestUser());
|
||||
rmRolesAndActionsAPI.assignRoleToUser(
|
||||
getDataUser().usingAdmin().getAdminUser().getUsername(),
|
||||
getDataUser().usingAdmin().getAdminUser().getPassword(),
|
||||
rmAdmin.get().getUsername(),
|
||||
"Administrator");
|
||||
auditLog.clearAuditLog(rmAdmin.get().getUsername(),rmAdmin.get().getPassword());
|
||||
category1 = createRootCategory(TITLE, DESCRIPTION);
|
||||
recordFolder1 = createFolder(category1.getId(),TITLE);
|
||||
|
||||
electronicRecord = createElectronicRecord(recordFolder1.getId(),AUDIT_ELECTRONIC_RECORD,rmAdmin.get());
|
||||
}
|
||||
|
||||
@Test(description = "Audit log for newly filed electronic record")
|
||||
@AlfrescoTest(jira="RM-4303")
|
||||
public void newElectronicRecordAudit() {
|
||||
List<AuditEntry> auditEntries= auditLog.getRMAuditLogAll(getAdminUser().getUsername(),getAdminUser().getPassword(),100);
|
||||
|
||||
// newly created record contains 2 events: "file to" and metadata update
|
||||
// the order in which object creation and metadata update are listed isn't always identical due to
|
||||
// both happening in the same transaction
|
||||
assertTrue("File To Event is not present.",auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("File to")));
|
||||
assertTrue("Updated metadata Event is not present.",auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Updated Metadata")));
|
||||
}
|
||||
|
||||
@Test
|
||||
(
|
||||
dependsOnMethods = "newElectronicRecordAudit",
|
||||
description = "Viewing electronic record audit log is itself an auditable event"
|
||||
)
|
||||
@AlfrescoTest(jira="RM-4303")
|
||||
public void electronicRecordAuditIsEvent()
|
||||
{
|
||||
List<AuditEntry> auditEntries= auditLog.getRMAuditLogAll(getAdminUser().getUsername(),getAdminUser().getPassword(),100);
|
||||
assertTrue("Audit View Event is not present.",auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Audit View")));
|
||||
}
|
||||
|
||||
@Test
|
||||
(
|
||||
dependsOnMethods = "electronicRecordAuditIsEvent",
|
||||
description = "Rename electronic record is an edit metadata event"
|
||||
)
|
||||
@AlfrescoTest(jira="RM-4303")
|
||||
public void renameElectronicRecord() {
|
||||
auditLog.clearAuditLog(rmAdmin.get().getUsername(),rmAdmin.get().getPassword());
|
||||
Record renameElectronicRecord = createRecordModel("edited " + electronicRecord.getName(), "", "");
|
||||
|
||||
// rename record
|
||||
getRestAPIFactory().getRecordsAPI().updateRecord(renameElectronicRecord, electronicRecord.getId());
|
||||
assertStatusCode(OK);
|
||||
|
||||
// we expect 1 new event: "metadata update"
|
||||
List<AuditEntry> auditEntries= auditLog.getRMAuditLogAll(getAdminUser().getUsername(),getAdminUser().getPassword(),100);
|
||||
assertTrue("Updated metadata Event is not present.",auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Updated Metadata")));
|
||||
}
|
||||
|
||||
@Test (
|
||||
dependsOnMethods = "newElectronicRecordAudit",
|
||||
description = "Complete and reopen electronic record")
|
||||
@AlfrescoTest(jira="RM-4303")
|
||||
public void completeAndReopenElectronicRecord() {
|
||||
electronicRecord2 = createElectronicRecord(recordFolder1.getId(),AUDIT_COMPLETE_REOPEN_ELECTRONIC_RECORD);
|
||||
|
||||
// complete record
|
||||
recordApi.completeRecord(rmAdmin.get().getUsername(),rmAdmin.get().getPassword(),
|
||||
electronicRecord2.getName());
|
||||
|
||||
try
|
||||
{
|
||||
Utility.sleep(1000, 30000, () ->
|
||||
{
|
||||
org.alfresco.rest.rm.community.requests.gscore.api.RecordsAPI recordsAPI = getRestAPIFactory().getRecordsAPI();
|
||||
List<String> aspects = recordsAPI.getRecord(electronicRecord2.getId()).getAspectNames();
|
||||
// a record must be completed
|
||||
assertTrue("Record is not completed.",aspects.contains(ASPECTS_COMPLETED_RECORD));
|
||||
});
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
fail("InterruptedException received while waiting for results.");
|
||||
}
|
||||
|
||||
List<AuditEntry> auditEntries= auditLog.getRMAuditLogAll(getAdminUser().getUsername(),getAdminUser().getPassword(),100);
|
||||
assertTrue("Complete Record Event is not present.",auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Complete Record")));
|
||||
|
||||
// Reopen record
|
||||
recordApi.reOpenRecord(rmAdmin.get().getUsername(),rmAdmin.get().getPassword(),
|
||||
electronicRecord2.getName());
|
||||
|
||||
try
|
||||
{
|
||||
Utility.sleep(1000, 30000, () ->
|
||||
{
|
||||
org.alfresco.rest.rm.community.requests.gscore.api.RecordsAPI recordsAPI = getRestAPIFactory().getRecordsAPI();
|
||||
List<String> aspects = recordsAPI.getRecord(electronicRecord2.getId()).getAspectNames();
|
||||
// a record mustn't be completed
|
||||
assertFalse(aspects.contains(ASPECTS_COMPLETED_RECORD));
|
||||
});
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
fail("InterruptedException received while waiting for results.");
|
||||
}
|
||||
|
||||
auditEntries= auditLog.getRMAuditLogAll(getAdminUser().getUsername(),getAdminUser().getPassword(),100);
|
||||
assertTrue("Reopen Record Event is not present.",auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Reopen Record")));
|
||||
}
|
||||
|
||||
@Test
|
||||
(
|
||||
dependsOnMethods = "completeAndReopenElectronicRecord",
|
||||
description = "File electronic record's audit log as record"
|
||||
)
|
||||
@AlfrescoTest(jira="RM-4303")
|
||||
public void fileElectronicRecordAuditLogAsRecord()
|
||||
{
|
||||
// audit log is stored in the same folder, refresh it so that it appears in the list
|
||||
HttpResponse auditRecordHttpResponse = auditLog.logsAuditLogAsRecord(rmAdmin.get().getUsername(),rmAdmin.get().getPassword(),
|
||||
getRecordNodeRef(electronicRecord2.getId()),getFolderNodeRef(recordFolder1.getId()));
|
||||
JSONObject auditRecordProperties = getAuditPropertyValues(auditRecordHttpResponse);
|
||||
Record auditRecord = getRestAPIFactory().getRecordsAPI().getRecord(auditRecordProperties.get("record").toString()
|
||||
.replace("workspace://SpacesStore/",""));
|
||||
// check audit log
|
||||
AssertJUnit.assertTrue(auditRecordProperties.get("recordName").toString().endsWith(".html"));
|
||||
AssertJUnit.assertTrue(auditRecord.getAspectNames().stream().noneMatch(x -> x.startsWith(ASPECTS_COMPLETED_RECORD)));
|
||||
}
|
||||
|
||||
private String getFolderNodeRef(String folderId) {
|
||||
return "workspace://SpacesStore/" + folderId;
|
||||
}
|
||||
|
||||
private String getRecordNodeRef(String recordId) {
|
||||
return "workspace/SpacesStore/" + recordId;
|
||||
}
|
||||
|
||||
private JSONObject getAuditPropertyValues(HttpResponse httpResponse) {
|
||||
HttpEntity entity = httpResponse.getEntity();
|
||||
String responseString = null;
|
||||
try {
|
||||
responseString = EntityUtils.toString(entity, "UTF-8");
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
JSONObject result = new JSONObject(responseString);
|
||||
return result;
|
||||
}
|
||||
|
||||
@AfterMethod
|
||||
private void closeAuditLog() {
|
||||
auditLog.clearAuditLog(rmAdmin.get().getUsername(),rmAdmin.get().getPassword());
|
||||
}
|
||||
|
||||
@AfterClass(alwaysRun = true)
|
||||
private void electronicRecordAuditLogCleanup() {
|
||||
deleteRecord(electronicRecord.getId());
|
||||
deleteRecordFolder(recordFolder1.getId());
|
||||
deleteRecordCategory(category1.getId());
|
||||
dataUser.usingAdmin().deleteUser(new UserModel(rmAdmin.get().getUsername(), rmAdmin.get().getPassword()));
|
||||
}
|
||||
}
|
@@ -0,0 +1,246 @@
|
||||
/*
|
||||
* #%L
|
||||
* Alfresco Records Management Module
|
||||
* %%
|
||||
* Copyright (C) 2005 - 2022 Alfresco Software Limited
|
||||
* %%
|
||||
* This file is part of the Alfresco software.
|
||||
* -
|
||||
* If the software was purchased under a paid Alfresco license, the terms of
|
||||
* the paid license agreement will prevail. Otherwise, the software is
|
||||
* provided under the following open source license terms:
|
||||
* -
|
||||
* Alfresco is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
* -
|
||||
* Alfresco is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
* -
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
|
||||
* #L%
|
||||
*/
|
||||
package org.alfresco.rest.rm.community.audit;
|
||||
|
||||
import org.alfresco.rest.rm.community.base.BaseRMRestTest;
|
||||
import org.alfresco.rest.rm.community.model.audit.AuditEntry;
|
||||
import org.alfresco.rest.rm.community.model.record.Record;
|
||||
import org.alfresco.rest.rm.community.model.recordcategory.RecordCategory;
|
||||
import org.alfresco.rest.rm.community.model.recordcategory.RecordCategoryChild;
|
||||
import org.alfresco.rest.v0.RMAuditAPI;
|
||||
import org.alfresco.rest.v0.RMRolesAndActionsAPI;
|
||||
import org.alfresco.rest.v0.RecordsAPI;
|
||||
import org.alfresco.test.AlfrescoTest;
|
||||
import org.alfresco.utility.Utility;
|
||||
import org.alfresco.utility.model.UserModel;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.testng.AssertJUnit;
|
||||
import org.testng.annotations.AfterClass;
|
||||
import org.testng.annotations.AfterMethod;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import static org.alfresco.rest.rm.community.model.fileplancomponents.FilePlanComponentAspects.ASPECTS_COMPLETED_RECORD;
|
||||
import static org.alfresco.rest.rm.community.util.CommonTestUtils.generateTestPrefix;
|
||||
import static org.alfresco.rest.rm.community.utils.FilePlanComponentsUtil.createRecordModel;
|
||||
import static org.springframework.http.HttpStatus.OK;
|
||||
import static org.springframework.test.util.AssertionErrors.assertTrue;
|
||||
import static org.testng.Assert.assertFalse;
|
||||
import static org.testng.Assert.fail;
|
||||
|
||||
|
||||
public class NonElectronicRecordAuditLogTest extends BaseRMRestTest {
|
||||
private Optional<UserModel> rmAdmin;
|
||||
@Autowired
|
||||
private RMRolesAndActionsAPI rmRolesAndActionsAPI;
|
||||
@Autowired
|
||||
private RMAuditAPI auditLog;
|
||||
@Autowired
|
||||
private RecordsAPI recordApi;
|
||||
private RecordCategory category1;
|
||||
private RecordCategoryChild recordFolder1;
|
||||
private Record nonElectronicRecord , nonElectronicRecord2;
|
||||
private static final String AUDIT_NON_ELECTRONIC_RECORD = generateTestPrefix(NonElectronicRecordAuditLogTest.class) + "non electronic record";
|
||||
private static final String AUDIT_COMPLETE_REOPEN_NON_ELECTRONIC_RECORD = "Complete Reopen Non-Electronic Record";
|
||||
public static final String TITLE = "Title";
|
||||
public static final String DESCRIPTION = "Description";
|
||||
|
||||
@BeforeClass(alwaysRun = true)
|
||||
public void nonElectronicRecordAuditLogSetup()
|
||||
{
|
||||
createRMSiteIfNotExists();
|
||||
rmAdmin = Optional.ofNullable(getDataUser().createRandomTestUser());
|
||||
rmRolesAndActionsAPI.assignRoleToUser(
|
||||
getDataUser().usingAdmin().getAdminUser().getUsername(),
|
||||
getDataUser().usingAdmin().getAdminUser().getPassword(),
|
||||
rmAdmin.get().getUsername(),
|
||||
"Administrator");
|
||||
|
||||
auditLog.clearAuditLog(rmAdmin.get().getUsername(),rmAdmin.get().getPassword());
|
||||
category1 = createRootCategory(TITLE, DESCRIPTION);
|
||||
recordFolder1 = createFolder(category1.getId(),TITLE);
|
||||
nonElectronicRecord = createNonElectronicRecord(recordFolder1.getId(),AUDIT_NON_ELECTRONIC_RECORD,rmAdmin.get());
|
||||
|
||||
}
|
||||
|
||||
@Test(description = "Audit log for newly filed non-electronic record")
|
||||
@AlfrescoTest(jira="RM-4303")
|
||||
public void newNonElectronicRecordAudit()
|
||||
{
|
||||
|
||||
List<AuditEntry> auditEntries= auditLog.getRMAuditLogAll(getAdminUser().getUsername(),getAdminUser().getPassword(),100);
|
||||
|
||||
// newly created record contains 3 events: "created object", "file to" and metadata update
|
||||
assertTrue("File To Event is not present.",auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("File to")));
|
||||
assertTrue("Updated metadata Event is not present.",auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Updated Metadata")));
|
||||
assertTrue("Created Object Event is not present.",auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Created Object")));
|
||||
}
|
||||
|
||||
@Test
|
||||
(
|
||||
dependsOnMethods = "newNonElectronicRecordAudit",
|
||||
description = "Viewing Non electronic record audit log is itself an auditable event"
|
||||
)
|
||||
@AlfrescoTest(jira="RM-4303")
|
||||
public void nonElectronicRecordAuditIsEvent()
|
||||
{
|
||||
List<AuditEntry> auditEntries= auditLog.getRMAuditLogAll(getAdminUser().getUsername(),getAdminUser().getPassword(),100);
|
||||
assertTrue("Audit View Event is not present.",auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Audit View")));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
(
|
||||
dependsOnMethods = "nonElectronicRecordAuditIsEvent",
|
||||
description = "Rename electronic record is an edit metadata event"
|
||||
)
|
||||
@AlfrescoTest(jira="RM-4303")
|
||||
public void renameNonElectronicRecord()
|
||||
{
|
||||
auditLog.clearAuditLog(rmAdmin.get().getUsername(),rmAdmin.get().getPassword());
|
||||
Record renameNonElectronicRecord = createRecordModel("edited " + nonElectronicRecord.getName(), "", "");
|
||||
|
||||
// rename record
|
||||
getRestAPIFactory().getRecordsAPI().updateRecord(renameNonElectronicRecord, nonElectronicRecord.getId());
|
||||
assertStatusCode(OK);
|
||||
|
||||
// we expect 1 new event: "metadata update"
|
||||
List<AuditEntry> auditEntries= auditLog.getRMAuditLogAll(getAdminUser().getUsername(),getAdminUser().getPassword(),100);
|
||||
assertTrue("Updated metadata Event is not present.",auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Updated Metadata")));
|
||||
|
||||
}
|
||||
|
||||
@Test (dependsOnMethods = "newNonElectronicRecordAudit",description = "Complete and reopen electronic record")
|
||||
@AlfrescoTest(jira="RM-4303")
|
||||
public void completeAndReopenNonElectronicRecord()
|
||||
{
|
||||
nonElectronicRecord2 = createNonElectronicRecord(recordFolder1.getId(),AUDIT_COMPLETE_REOPEN_NON_ELECTRONIC_RECORD);
|
||||
|
||||
// complete record
|
||||
recordApi.completeRecord(rmAdmin.get().getUsername(),rmAdmin.get().getPassword(),
|
||||
nonElectronicRecord2.getName());
|
||||
|
||||
try
|
||||
{
|
||||
Utility.sleep(1000, 30000, () ->
|
||||
{
|
||||
org.alfresco.rest.rm.community.requests.gscore.api.RecordsAPI recordsAPI = getRestAPIFactory().getRecordsAPI();
|
||||
List<String> aspects = recordsAPI.getRecord(nonElectronicRecord2.getId()).getAspectNames();
|
||||
// a record must be completed
|
||||
assertTrue("Record is not completed.",aspects.contains(ASPECTS_COMPLETED_RECORD));
|
||||
});
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
fail("InterruptedException received while waiting for results.");
|
||||
}
|
||||
|
||||
List<AuditEntry> auditEntries= auditLog.getRMAuditLogAll(getAdminUser().getUsername(),getAdminUser().getPassword(),100);
|
||||
assertTrue("Complete Record Event is not present.",auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Complete Record")));
|
||||
|
||||
// Reopen record
|
||||
recordApi.reOpenRecord(rmAdmin.get().getUsername(),rmAdmin.get().getPassword(),
|
||||
nonElectronicRecord2.getName());
|
||||
|
||||
try
|
||||
{
|
||||
Utility.sleep(1000, 30000, () ->
|
||||
{
|
||||
org.alfresco.rest.rm.community.requests.gscore.api.RecordsAPI recordsAPI = getRestAPIFactory().getRecordsAPI();
|
||||
List<String> aspects = recordsAPI.getRecord(nonElectronicRecord2.getId()).getAspectNames();
|
||||
// a record mustn't be completed
|
||||
assertFalse(aspects.contains(ASPECTS_COMPLETED_RECORD));
|
||||
});
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
fail("InterruptedException received while waiting for results.");
|
||||
}
|
||||
|
||||
auditEntries= auditLog.getRMAuditLogAll(getAdminUser().getUsername(),getAdminUser().getPassword(),100);
|
||||
assertTrue("Reopen Record Event is not present.",auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Reopen Record")));
|
||||
|
||||
}
|
||||
@Test
|
||||
(
|
||||
dependsOnMethods = "completeAndReopenNonElectronicRecord",
|
||||
description = "File electronic record's audit log as record"
|
||||
)
|
||||
@AlfrescoTest(jira="RM-4303")
|
||||
public void fileNonElectronicRecordAuditLogAsRecord()
|
||||
{
|
||||
// audit log is stored in the same folder, refresh it so that it appears in the list
|
||||
HttpResponse auditRecordHttpResponse = auditLog.logsAuditLogAsRecord(rmAdmin.get().getUsername(),rmAdmin.get().getPassword(),
|
||||
getRecordNodeRef(nonElectronicRecord2.getId()),getFolderNodeRef(recordFolder1.getId()));
|
||||
JSONObject auditRecordProperties = getAuditPropertyValues(auditRecordHttpResponse);
|
||||
Record auditRecord = getRestAPIFactory().getRecordsAPI().getRecord(auditRecordProperties.get("record").toString()
|
||||
.replace("workspace://SpacesStore/",""));
|
||||
// check audit log
|
||||
AssertJUnit.assertTrue(auditRecordProperties.get("recordName").toString().endsWith(".html"));
|
||||
AssertJUnit.assertTrue(auditRecord.getAspectNames().stream().noneMatch(x -> x.startsWith(ASPECTS_COMPLETED_RECORD)));
|
||||
|
||||
}
|
||||
|
||||
private String getFolderNodeRef(String folderId) {
|
||||
return "workspace://SpacesStore/" + folderId;
|
||||
}
|
||||
|
||||
private String getRecordNodeRef(String recordId) {
|
||||
return "workspace/SpacesStore/" + recordId;
|
||||
}
|
||||
|
||||
private JSONObject getAuditPropertyValues(HttpResponse httpResponse) {
|
||||
HttpEntity entity = httpResponse.getEntity();
|
||||
String responseString = null;
|
||||
try {
|
||||
responseString = EntityUtils.toString(entity, "UTF-8");
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
JSONObject result = new JSONObject(responseString);
|
||||
return result;
|
||||
}
|
||||
@AfterMethod
|
||||
private void closeAuditLog() {
|
||||
auditLog.clearAuditLog(rmAdmin.get().getUsername(),rmAdmin.get().getPassword());
|
||||
}
|
||||
|
||||
@AfterClass(alwaysRun = true)
|
||||
private void nonElectronicRecordAuditLogCleanup() {
|
||||
deleteRecord(nonElectronicRecord.getId());
|
||||
deleteRecord(nonElectronicRecord2.getId());
|
||||
deleteRecordFolder(recordFolder1.getId());
|
||||
deleteRecordCategory(category1.getId());
|
||||
dataUser.usingAdmin().deleteUser(new UserModel(rmAdmin.get().getUsername(), rmAdmin.get().getPassword()));
|
||||
}
|
||||
}
|
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
* #%L
|
||||
* Alfresco Records Management Module
|
||||
* %%
|
||||
* Copyright (C) 2005 - 2022 Alfresco Software Limited
|
||||
* %%
|
||||
* This file is part of the Alfresco software.
|
||||
* -
|
||||
* If the software was purchased under a paid Alfresco license, the terms of
|
||||
* the paid license agreement will prevail. Otherwise, the software is
|
||||
* provided under the following open source license terms:
|
||||
* -
|
||||
* Alfresco is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
* -
|
||||
* Alfresco is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
* -
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
|
||||
* #L%
|
||||
*/
|
||||
package org.alfresco.rest.rm.community.audit;
|
||||
|
||||
import org.alfresco.rest.rm.community.base.BaseRMRestTest;
|
||||
import org.alfresco.rest.rm.community.model.audit.AuditEntry;
|
||||
import org.alfresco.rest.rm.community.model.recordcategory.RecordCategory;
|
||||
import org.alfresco.rest.v0.RMAuditAPI;
|
||||
import org.alfresco.rest.v0.RMRolesAndActionsAPI;
|
||||
import org.alfresco.test.AlfrescoTest;
|
||||
import org.alfresco.utility.model.UserModel;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.testng.annotations.AfterClass;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
import java.util.List;
|
||||
import static org.alfresco.rest.rm.community.util.CommonTestUtils.generateTestPrefix;
|
||||
import static org.alfresco.utility.data.RandomData.getRandomAlphanumeric;
|
||||
import static org.alfresco.utility.report.log.Step.STEP;
|
||||
import static org.springframework.http.HttpStatus.OK;
|
||||
import static org.springframework.test.util.AssertionErrors.assertTrue;
|
||||
|
||||
public class RecordCategoryAuditLogTest extends BaseRMRestTest {
|
||||
@Autowired
|
||||
private RMRolesAndActionsAPI rmRolesAndActionsAPI;
|
||||
@Autowired
|
||||
private RMAuditAPI auditLog;
|
||||
|
||||
private final String TEST_PREFIX = generateTestPrefix(RecordCategoryAuditLogTest.class);
|
||||
private final String RM_ADMIN = TEST_PREFIX + "rm_admin";
|
||||
private static final String AUDIT_CATEGORY = generateTestPrefix(RecordCategoryAuditLogTest.class) + "category";
|
||||
private RecordCategory recordCategoryAudit;
|
||||
|
||||
@BeforeClass(alwaysRun = true)
|
||||
public void recordCategoryAuditLogSetup() {
|
||||
STEP("Create RM Site");
|
||||
createRMSiteIfNotExists();
|
||||
|
||||
STEP("Create RM Admin user");
|
||||
rmRolesAndActionsAPI.createUserAndAssignToRole(getAdminUser().getUsername(), getAdminUser().getPassword(), RM_ADMIN,
|
||||
getAdminUser().getPassword(),
|
||||
"Administrator");
|
||||
}
|
||||
|
||||
@Test
|
||||
@AlfrescoTest(jira = "RM-2768")
|
||||
public void recordCategoryAudit() throws Exception {
|
||||
STEP("Create root level category");
|
||||
recordCategoryAudit = createRootCategory(AUDIT_CATEGORY);
|
||||
List<AuditEntry> auditEntries = auditLog.getRMAuditLogAll(getAdminUser().getUsername(), getAdminUser().getPassword(), 100);
|
||||
// newly created record category contains 3 events: object creation, inherited permissions set to false and metadata update
|
||||
// the order in which object creation and metadata update are listed isn't always identical due to
|
||||
// both happening in the same transaction
|
||||
assertTrue("Created Object Event is not present.", auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Created Object")));
|
||||
assertTrue("Updated metadata Event is not present.", auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Updated Metadata")));
|
||||
}
|
||||
|
||||
@Test
|
||||
(
|
||||
dependsOnMethods = "recordCategoryAudit",
|
||||
description = "Viewing audit log is itself an auditable event"
|
||||
)
|
||||
@AlfrescoTest(jira="RM-4303")
|
||||
public void recordCategoryAuditIsEvent() {
|
||||
List<AuditEntry> auditEntries = auditLog.getRMAuditLogAll(getAdminUser().getUsername(), getAdminUser().getPassword(), 100);
|
||||
assertTrue("Audit View Event is not present.", auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Audit View")));
|
||||
}
|
||||
|
||||
@Test
|
||||
(
|
||||
dependsOnMethods = "recordCategoryAuditIsEvent",
|
||||
description = "Record category rename is an edit metadata event"
|
||||
)
|
||||
@AlfrescoTest(jira="RM-4303")
|
||||
public void renameRecordCategory() {
|
||||
String categoryName = "Category name " + getRandomAlphanumeric();
|
||||
RecordCategory rootRecordCategory = createRootCategory(categoryName);
|
||||
String newCategoryName = "Rename " + categoryName;
|
||||
RecordCategory recordCategoryUpdated = RecordCategory.builder().name(newCategoryName).build();
|
||||
RecordCategory renamedRecordCategory = getRestAPIFactory().getRecordCategoryAPI().updateRecordCategory(recordCategoryUpdated, rootRecordCategory.getId());
|
||||
|
||||
assertStatusCode(OK);
|
||||
// we expect 1 new event: "metadata update"
|
||||
List<AuditEntry> auditEntries = auditLog.getRMAuditLogAll(getAdminUser().getUsername(), getAdminUser().getPassword(), 100);
|
||||
assertTrue("Updated metadata Event is not present.", auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Updated Metadata")));
|
||||
}
|
||||
@AfterClass(alwaysRun = true)
|
||||
private void electronicRecordAuditLogCleanup() {
|
||||
deleteRecordCategory(recordCategoryAudit.getId());
|
||||
dataUser.deleteUser(new UserModel(RM_ADMIN,
|
||||
getAdminUser().getPassword()));
|
||||
auditLog.clearAuditLog(getAdminUser().getUsername(), getAdminUser().getPassword());
|
||||
}
|
||||
}
|
||||
|
@@ -0,0 +1,175 @@
|
||||
/*
|
||||
* #%L
|
||||
* Alfresco Records Management Module
|
||||
* %%
|
||||
* Copyright (C) 2005 - 2022 Alfresco Software Limited
|
||||
* %%
|
||||
* This file is part of the Alfresco software.
|
||||
* -
|
||||
* If the software was purchased under a paid Alfresco license, the terms of
|
||||
* the paid license agreement will prevail. Otherwise, the software is
|
||||
* provided under the following open source license terms:
|
||||
* -
|
||||
* Alfresco is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
* -
|
||||
* Alfresco is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
* -
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
|
||||
* #L%
|
||||
*/
|
||||
package org.alfresco.rest.rm.community.audit;
|
||||
|
||||
import org.alfresco.rest.rm.community.base.BaseRMRestTest;
|
||||
import org.alfresco.rest.rm.community.model.audit.AuditEntry;
|
||||
import org.alfresco.rest.rm.community.model.recordcategory.RecordCategory;
|
||||
import org.alfresco.rest.rm.community.model.recordcategory.RecordCategoryChild;
|
||||
import org.alfresco.rest.rm.community.model.recordfolder.RecordFolder;
|
||||
import org.alfresco.rest.v0.RMAuditAPI;
|
||||
import org.alfresco.rest.v0.RMRolesAndActionsAPI;
|
||||
import org.alfresco.rest.v0.RecordFoldersAPI;
|
||||
import org.alfresco.test.AlfrescoTest;
|
||||
import org.alfresco.utility.Utility;
|
||||
import org.alfresco.utility.model.UserModel;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.testng.annotations.AfterClass;
|
||||
import org.testng.annotations.AfterMethod;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.alfresco.rest.rm.community.model.fileplancomponents.FilePlanComponentAspects.ASPECTS_COMPLETED_RECORD;
|
||||
import static org.alfresco.rest.rm.community.utils.FilePlanComponentsUtil.createRecordFolderModel;
|
||||
import static org.springframework.http.HttpStatus.OK;
|
||||
import static org.springframework.test.util.AssertionErrors.assertTrue;
|
||||
import static org.testng.Assert.assertFalse;
|
||||
import static org.testng.Assert.fail;
|
||||
|
||||
public class RecordFolderAuditLogTest extends BaseRMRestTest {
|
||||
|
||||
private Optional<UserModel> rmAdmin;
|
||||
@Autowired
|
||||
private RMRolesAndActionsAPI rmRolesAndActionsAPI;
|
||||
@Autowired
|
||||
private RMAuditAPI auditLog;
|
||||
|
||||
@Autowired
|
||||
private RecordFoldersAPI recordFoldersAPI;
|
||||
private RecordCategory category1;
|
||||
private RecordCategoryChild recordFolder1;
|
||||
public static final String TITLE = "Title";
|
||||
public static final String DESCRIPTION = "Description";
|
||||
|
||||
@BeforeClass(alwaysRun = true)
|
||||
public void recordFolderAuditLogSetup() {
|
||||
createRMSiteIfNotExists();
|
||||
rmAdmin = Optional.ofNullable(getDataUser().createRandomTestUser());
|
||||
rmRolesAndActionsAPI.assignRoleToUser(
|
||||
getDataUser().usingAdmin().getAdminUser().getUsername(),
|
||||
getDataUser().usingAdmin().getAdminUser().getPassword(),
|
||||
rmAdmin.get().getUsername(),
|
||||
"Administrator");
|
||||
}
|
||||
|
||||
@Test(description = "Audit log for empty record folder")
|
||||
@AlfrescoTest(jira = "RM-4303")
|
||||
public void recordFolderAudit() {
|
||||
category1 = createRootCategory(TITLE, DESCRIPTION);
|
||||
recordFolder1 = createFolder(category1.getId(), TITLE);
|
||||
List<AuditEntry> auditEntries = auditLog.getRMAuditLogAll(getAdminUser().getUsername(), getAdminUser().getPassword(), 100);
|
||||
assertTrue("Created Object Event is not present.", auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Created Object")));
|
||||
assertTrue("Updated metadata Event is not present.", auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Updated Metadata")));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
(
|
||||
dependsOnMethods = "recordFolderAudit",
|
||||
description = "Viewing record folder audit log is itself an auditable event"
|
||||
)
|
||||
@AlfrescoTest(jira = "RM-4303")
|
||||
public void recordFolderAuditIsEvent() {
|
||||
List<AuditEntry> auditEntries = auditLog.getRMAuditLogAll(getAdminUser().getUsername(), getAdminUser().getPassword(), 100);
|
||||
assertTrue("Audit View Event is not present.", auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Audit View")));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
(
|
||||
dependsOnMethods = "recordFolderAuditIsEvent",
|
||||
description = "Record folder rename is an edit metadata event"
|
||||
)
|
||||
@AlfrescoTest(jira = "RM-4303")
|
||||
public void renameRecordFolder() {
|
||||
auditLog.clearAuditLog(rmAdmin.get().getUsername(), rmAdmin.get().getPassword());
|
||||
RecordFolder renameRecordFolder = createRecordFolderModel(category1.getId(), "edited");
|
||||
getRestAPIFactory().getRecordFolderAPI().updateRecordFolder(renameRecordFolder, recordFolder1.getId());
|
||||
assertStatusCode(OK);
|
||||
// we expect 1 new event: "metadata update"
|
||||
List<AuditEntry> auditEntries = auditLog.getRMAuditLogAll(getAdminUser().getUsername(), getAdminUser().getPassword(), 100);
|
||||
// assertTrue("Move To Event is not present.",auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Move to")));
|
||||
assertTrue("Updated metadata Event is not present.", auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Updated Metadata")));
|
||||
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "recordFolderAudit",
|
||||
description = "Close and reopen folder")
|
||||
@AlfrescoTest(jira = "RM-4303")
|
||||
public void closeReopenFolder() {
|
||||
//close folder
|
||||
recordFoldersAPI.closeRecordFolder(rmAdmin.get().getUsername(), rmAdmin.get().getPassword(),
|
||||
recordFolder1.getName());
|
||||
try
|
||||
{
|
||||
Utility.sleep(1000, 30000, () ->
|
||||
{
|
||||
List<AuditEntry> auditEntries = auditLog.getRMAuditLogAll(getAdminUser().getUsername(), getAdminUser().getPassword(), 100);
|
||||
assertTrue("Folder Close Record Event is not present.", auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Close Record Folder")));
|
||||
|
||||
});
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
fail("InterruptedException received while waiting for results.");
|
||||
}
|
||||
|
||||
//reopen folder
|
||||
recordFoldersAPI.reOpenRecordFolder(rmAdmin.get().getUsername(), rmAdmin.get().getPassword(),
|
||||
recordFolder1.getName());
|
||||
try
|
||||
{
|
||||
Utility.sleep(1000, 30000, () ->
|
||||
{
|
||||
|
||||
List<AuditEntry> auditEntries = auditLog.getRMAuditLogAll(getAdminUser().getUsername(), getAdminUser().getPassword(), 100);
|
||||
assertTrue("Reopen Record Event is not present.", auditEntries.stream().anyMatch(x -> x.getEvent().startsWith("Open Record Folder")));
|
||||
|
||||
});
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
fail("InterruptedException received while waiting for results.");
|
||||
}
|
||||
}
|
||||
@AfterMethod
|
||||
private void closeAuditLog()
|
||||
{
|
||||
auditLog.clearAuditLog(rmAdmin.get().getUsername(),rmAdmin.get().getPassword());
|
||||
}
|
||||
|
||||
@AfterClass (alwaysRun = true)
|
||||
public void recordFolderAuditLogCleanup()
|
||||
{
|
||||
deleteRecordFolder(recordFolder1.getId());
|
||||
deleteRecordCategory(category1.getId());
|
||||
dataUser.usingAdmin().deleteUser(new UserModel(rmAdmin.get().getUsername(), rmAdmin.get().getPassword()));
|
||||
}
|
||||
|
||||
}
|
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-governance-services-community-parent</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
|
@@ -1,3 +1,3 @@
|
||||
SOLR6_TAG=2.0.5-A2
|
||||
SOLR6_TAG=2.0.5
|
||||
POSTGRES_TAG=14.4
|
||||
ACTIVEMQ_TAG=5.17.1-jre11-rockylinux8
|
||||
|
@@ -8,7 +8,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-governance-services-community-repo-parent</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
|
@@ -4,7 +4,7 @@
|
||||
|
||||
# Version label
|
||||
version.major=7
|
||||
version.minor=3
|
||||
version.minor=4
|
||||
version.revision=0
|
||||
version.label=
|
||||
|
||||
|
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-governance-services-community-repo-parent</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
|
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
|
@@ -8,7 +8,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo-amps</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
|
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
|
@@ -346,7 +346,7 @@ public class FTSQueryParser
|
||||
}
|
||||
constraints.add(constraint);
|
||||
}
|
||||
if (constraints.size() == 1)
|
||||
if (constraints.size() == 1 && Occur.EXCLUDE != constraints.get(0).getOccur())
|
||||
{
|
||||
return constraints.get(0);
|
||||
}
|
||||
|
@@ -69,20 +69,21 @@ public class LuceneDisjunction<Q, S, E extends Throwable> extends BaseDisjunctio
|
||||
@SuppressWarnings("unchecked")
|
||||
LuceneQueryBuilderComponent<Q, S, E> luceneQueryBuilderComponent = (LuceneQueryBuilderComponent<Q, S, E>) constraint;
|
||||
Q constraintQuery = luceneQueryBuilderComponent.addComponent(selectors, functionArgs, luceneContext, functionContext);
|
||||
queriestoDisjoin.add(new Pair<>(constraint, constraintQuery));
|
||||
queriestoDisjoin.add(new Pair<Constraint, Q>(constraint, constraintQuery));
|
||||
if (constraintQuery != null)
|
||||
{
|
||||
switch (constraint.getOccur())
|
||||
{
|
||||
case DEFAULT:
|
||||
case MANDATORY:
|
||||
case OPTIONAL:
|
||||
expressionBuilder.addOptional(constraintQuery, constraint.getBoost());
|
||||
break;
|
||||
case MANDATORY:
|
||||
expressionBuilder.addRequired(constraintQuery, constraint.getBoost());
|
||||
break;
|
||||
case EXCLUDE:
|
||||
expressionBuilder.addExcluded(constraintQuery, constraint.getBoost());
|
||||
QueryParserExpressionAdaptor<Q, E> subExpressionBuilder = luceneContext.getLuceneQueryParserAdaptor().getExpressionAdaptor();
|
||||
subExpressionBuilder.addRequired(luceneContext.getLuceneQueryParserAdaptor().getMatchAllNodesQuery());
|
||||
subExpressionBuilder.addExcluded(constraintQuery);
|
||||
expressionBuilder.addOptional(subExpressionBuilder.getQuery(), constraint.getBoost());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@@ -9,6 +9,6 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo-packaging</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
</project>
|
||||
|
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo-packaging</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
|
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
|
@@ -1,3 +1,3 @@
|
||||
SOLR6_TAG=2.0.5-A2
|
||||
SOLR6_TAG=2.0.5
|
||||
POSTGRES_TAG=14.4
|
||||
ACTIVEMQ_TAG=5.17.1-jre11-rockylinux8
|
||||
|
@@ -6,7 +6,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo-packaging</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
|
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo-tests</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<organization>
|
||||
|
@@ -9,7 +9,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo-tests</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<developers>
|
||||
|
@@ -9,7 +9,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo-tests</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<developers>
|
||||
|
@@ -9,7 +9,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo-tests</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<developers>
|
||||
|
@@ -28,16 +28,23 @@ package org.alfresco.rest.rules;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
|
||||
import static org.alfresco.rest.actions.access.AccessRestrictionUtil.ERROR_MESSAGE_ACCESS_RESTRICTED;
|
||||
import static org.alfresco.rest.actions.access.AccessRestrictionUtil.MAIL_ACTION;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.CHECKIN_ACTION;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.COPY_ACTION;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.ID;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.INVERTED;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.IS_SHARED;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.RULE_NAME_DEFAULT;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.RULE_SCRIPT_PARAM_ID;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.SCRIPT_ACTION;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.TEMPLATE_PARAM;
|
||||
import static org.alfresco.utility.constants.UserRole.SiteCollaborator;
|
||||
import static org.alfresco.utility.constants.UserRole.SiteConsumer;
|
||||
import static org.alfresco.utility.constants.UserRole.SiteContributor;
|
||||
import static org.alfresco.utility.constants.UserRole.SiteManager;
|
||||
import static org.alfresco.utility.model.FileModel.getRandomFileModel;
|
||||
import static org.alfresco.utility.model.FileType.TEXT_PLAIN;
|
||||
import static org.alfresco.utility.model.UserModel.getRandomUserModel;
|
||||
import static org.alfresco.utility.report.log.Step.STEP;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.springframework.http.HttpStatus.BAD_REQUEST;
|
||||
@@ -45,21 +52,30 @@ import static org.springframework.http.HttpStatus.CREATED;
|
||||
import static org.springframework.http.HttpStatus.FORBIDDEN;
|
||||
import static org.springframework.http.HttpStatus.NOT_FOUND;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import javax.json.Json;
|
||||
import javax.json.JsonObject;
|
||||
|
||||
import org.alfresco.rest.RestTest;
|
||||
import org.alfresco.rest.model.RestActionBodyExecTemplateModel;
|
||||
import org.alfresco.rest.model.RestActionConstraintModel;
|
||||
import org.alfresco.rest.model.RestCompositeConditionDefinitionModel;
|
||||
import org.alfresco.rest.model.RestRuleModel;
|
||||
import org.alfresco.rest.model.RestRuleModelsCollection;
|
||||
import org.alfresco.utility.constants.UserRole;
|
||||
import org.alfresco.utility.model.ContentModel;
|
||||
import org.alfresco.utility.model.FileModel;
|
||||
import org.alfresco.utility.model.FolderModel;
|
||||
import org.alfresco.utility.model.SiteModel;
|
||||
import org.alfresco.utility.model.TestGroup;
|
||||
import org.alfresco.utility.model.UserModel;
|
||||
import org.apache.chemistry.opencmis.client.api.CmisObject;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
@@ -160,6 +176,7 @@ public class CreateRulesTests extends RestTest
|
||||
}
|
||||
|
||||
/** Check that a user without permission to view the folder cannot create a rule in it. */
|
||||
@Test (groups = { TestGroup.REST_API, TestGroup.RULES })
|
||||
public void requireReadPermissionToCreateRule()
|
||||
{
|
||||
STEP("Create a user and use them to create a private site containing a folder");
|
||||
@@ -177,7 +194,8 @@ public class CreateRulesTests extends RestTest
|
||||
restClient.assertLastError().containsSummary("Insufficient permissions to manage rules");
|
||||
}
|
||||
|
||||
/** Check that a Collaborator cannot create a rule in a private folder. */
|
||||
/** Check that a Collaborator cannot create a rule in a folder in a private site. */
|
||||
@Test (groups = { TestGroup.REST_API, TestGroup.RULES })
|
||||
public void siteCollaboratorCannotCreateRule()
|
||||
{
|
||||
testRolePermissionsWith(SiteCollaborator);
|
||||
@@ -187,6 +205,7 @@ public class CreateRulesTests extends RestTest
|
||||
}
|
||||
|
||||
/** Check that a Contributor cannot create a rule in a private folder. */
|
||||
@Test (groups = { TestGroup.REST_API, TestGroup.RULES })
|
||||
public void siteContributorCannotCreateRule()
|
||||
{
|
||||
testRolePermissionsWith(SiteContributor);
|
||||
@@ -195,7 +214,8 @@ public class CreateRulesTests extends RestTest
|
||||
restClient.assertLastError().containsSummary("Insufficient permissions to manage rules");
|
||||
}
|
||||
|
||||
/** Check that a Consumer cannot create a rule in a private folder. */
|
||||
/** Check that a Consumer cannot create a rule in a folder in a private site. */
|
||||
@Test (groups = { TestGroup.REST_API, TestGroup.RULES })
|
||||
public void siteConsumerCannotCreateRule()
|
||||
{
|
||||
testRolePermissionsWith(SiteConsumer);
|
||||
@@ -204,7 +224,8 @@ public class CreateRulesTests extends RestTest
|
||||
restClient.assertLastError().containsSummary("Insufficient permissions to manage rules");
|
||||
}
|
||||
|
||||
/** Check that a siteManager can create a rule in a private folder. */
|
||||
/** Check that a siteManager can create a rule in a folder in a private site. */
|
||||
@Test (groups = { TestGroup.REST_API, TestGroup.RULES })
|
||||
public void siteManagerCanCreateRule()
|
||||
{
|
||||
testRolePermissionsWith(SiteManager)
|
||||
@@ -345,7 +366,7 @@ public class CreateRulesTests extends RestTest
|
||||
rule.assertThat().field("isShared").isNotNull();
|
||||
}
|
||||
|
||||
public RestRuleModel testRolePermissionsWith(UserRole userRole)
|
||||
private RestRuleModel testRolePermissionsWith(UserRole userRole)
|
||||
{
|
||||
STEP("Create a user and use them to create a private site containing a folder");
|
||||
SiteModel privateSite = dataSite.usingUser(user).createPrivateRandomSite();
|
||||
@@ -359,6 +380,112 @@ public class CreateRulesTests extends RestTest
|
||||
return restClient.authenticateUser(userWithRole).withPrivateAPI().usingNode(privateFolder).usingDefaultRuleSet().createSingleRule(ruleModel);
|
||||
}
|
||||
|
||||
/** Check that the folder's owner can create rules, even if it is in a private site they aren't a member of. */
|
||||
@Test (groups = { TestGroup.REST_API, TestGroup.RULES })
|
||||
public void checkOwnerCanCreateRule()
|
||||
{
|
||||
STEP("Use admin to create a private site.");
|
||||
SiteModel privateSite = dataSite.usingUser(dataUser.getAdminUser()).createPrivateRandomSite();
|
||||
|
||||
STEP("Add the user to the site, let them create a folder and then evict them from the site again.");
|
||||
dataUser.addUserToSite(user, privateSite, SiteManager);
|
||||
FolderModel folder = dataContent.usingUser(user).usingSite(privateSite).createFolder();
|
||||
dataUser.removeUserFromSite(user, privateSite);
|
||||
|
||||
STEP("Check the folder owner can create a rule.");
|
||||
RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(folder).usingDefaultRuleSet().createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(CREATED);
|
||||
}
|
||||
|
||||
/** Check that an administrator can create a rule in a private site even if they aren't a member. */
|
||||
@Test (groups = { TestGroup.REST_API, TestGroup.RULES })
|
||||
public void checkAdminCanCreateRule()
|
||||
{
|
||||
STEP("Use a user to create a private site with a folder.");
|
||||
SiteModel privateSite = dataSite.usingUser(user).createPrivateRandomSite();
|
||||
FolderModel folder = dataContent.usingUser(user).usingSite(privateSite).createFolder();
|
||||
|
||||
STEP("Check admin can create a rule.");
|
||||
RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
restClient.authenticateUser(dataUser.getAdminUser()).withPrivateAPI().usingNode(folder).usingDefaultRuleSet().createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(CREATED);
|
||||
}
|
||||
|
||||
/** Check that a coordinator can create rules in folders outside sites. */
|
||||
@Test (groups = { TestGroup.REST_API, TestGroup.RULES })
|
||||
public void checkCoordinatorCanCreateRule()
|
||||
{
|
||||
STEP("Create a folder in the user's file space.");
|
||||
FolderModel folder = dataContent.usingUser(user).usingUserHome().createFolder();
|
||||
|
||||
STEP("Create another user as a coordinator for this folder.");
|
||||
UserModel coordinator = dataUser.createRandomTestUser("Rules");
|
||||
/*
|
||||
Update folder node properties to add a coordinator
|
||||
{ "permissions": { "isInheritanceEnabled": true, "locallySet": { "authorityId": "coordinator.getUsername()",
|
||||
"name": "Coordinator", "accessStatus":"ALLOWED" } } }
|
||||
*/
|
||||
String putBody = getAddPermissionsBody(coordinator.getUsername(), "Coordinator");
|
||||
restClient.authenticateUser(user).withCoreAPI().usingNode(folder).updateNode(putBody);
|
||||
|
||||
STEP("Check the coordinator can create a rule.");
|
||||
RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
restClient.authenticateUser(coordinator).withPrivateAPI().usingNode(folder).usingDefaultRuleSet().createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(CREATED);
|
||||
}
|
||||
|
||||
/** Check that an editor cannot create rules in folders outside sites. */
|
||||
@Test (groups = { TestGroup.REST_API, TestGroup.RULES })
|
||||
public void checkEditorCannotCreateRule()
|
||||
{
|
||||
STEP("Create a folder in the user's file space.");
|
||||
FolderModel folder = dataContent.usingUser(user).usingUserHome().createFolder();
|
||||
|
||||
STEP("Create another user as a editor for this folder.");
|
||||
UserModel editor = dataUser.createRandomTestUser();
|
||||
/*
|
||||
Update folder node properties to add an editor
|
||||
{ "permissions": { "isInheritanceEnabled": true, "locallySet": { "authorityId": "editor.getUsername()",
|
||||
"name": "Coordinator", "accessStatus":"ALLOWED" } } }
|
||||
*/
|
||||
String putBody = getAddPermissionsBody(editor.getUsername(), "Editor");
|
||||
restClient.authenticateUser(user).withCoreAPI().usingNode(folder).updateNode(putBody);
|
||||
|
||||
STEP("Check the editor can create a rule.");
|
||||
RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
restClient.authenticateUser(editor).withPrivateAPI().usingNode(folder).usingDefaultRuleSet().createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(FORBIDDEN);
|
||||
}
|
||||
|
||||
/** Check that a collaborator cannot create rules in folders outside sites. */
|
||||
@Test (groups = { TestGroup.REST_API, TestGroup.RULES })
|
||||
public void checkCollaboratorCannotCreateRule()
|
||||
{
|
||||
STEP("Create a folder in the user's file space.");
|
||||
FolderModel folder = dataContent.usingUser(user).usingUserHome().createFolder();
|
||||
|
||||
STEP("Create another user as a collaborator for this folder.");
|
||||
UserModel collaborator = dataUser.createRandomTestUser();
|
||||
/*
|
||||
Update folder node properties to add a collaborator
|
||||
{ "permissions": { "isInheritanceEnabled": true, "locallySet": { "authorityId": "collaborator.getUsername()",
|
||||
"name": "Coordinator", "accessStatus":"ALLOWED" } } }
|
||||
*/
|
||||
String putBody = getAddPermissionsBody(collaborator.getUsername(), "Collaborator");
|
||||
restClient.authenticateUser(user).withCoreAPI().usingNode(folder).updateNode(putBody);
|
||||
|
||||
STEP("Check the collaborator can create a rule.");
|
||||
RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
restClient.authenticateUser(collaborator).withPrivateAPI().usingNode(folder).usingDefaultRuleSet().createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(FORBIDDEN);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check we can create a rule with several actions.
|
||||
*/
|
||||
@@ -368,10 +495,10 @@ public class CreateRulesTests extends RestTest
|
||||
final UserModel admin = dataUser.getAdminUser();
|
||||
|
||||
final RestRuleModel rule = restClient.authenticateUser(admin).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
.createSingleRule(rulesUtils.createVariousActions());
|
||||
.createSingleRule(rulesUtils.createRuleWithVariousActions());
|
||||
|
||||
RestRuleModel expectedRuleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
expectedRuleModel.setActions(rulesUtils.createVariousActions().getActions());
|
||||
expectedRuleModel.setActions(rulesUtils.createRuleWithVariousActions().getActions());
|
||||
expectedRuleModel.setTriggers(List.of("inbound"));
|
||||
|
||||
restClient.assertStatusCodeIs(CREATED);
|
||||
@@ -379,8 +506,38 @@ public class CreateRulesTests extends RestTest
|
||||
.assertThat().field(IS_SHARED).isNull();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check get an error when creating a rule with action with empty parameter value.
|
||||
*/
|
||||
@Test(groups = {TestGroup.REST_API, TestGroup.RULES})
|
||||
public void createRuleWithEmptyActionParameterValueShouldFail()
|
||||
{
|
||||
final RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
final RestActionBodyExecTemplateModel checkinAction = rulesUtils.createCustomActionModel(CHECKIN_ACTION, Map.of("description", ""));
|
||||
ruleModel.setActions(List.of(checkinAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet().createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(BAD_REQUEST).assertLastError().containsSummary("Action parameter should not have empty or null value");
|
||||
}
|
||||
|
||||
/**
|
||||
* Check can create a rule with action without any parameters when action definition states all of them are optional.
|
||||
*/
|
||||
@Test(groups = {TestGroup.REST_API, TestGroup.RULES})
|
||||
public void createRuleWithoutParameterWhenTheyAreOptional()
|
||||
{
|
||||
final RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
final RestActionBodyExecTemplateModel checkinAction = rulesUtils.createCustomActionModel(CHECKIN_ACTION, null);
|
||||
ruleModel.setActions(List.of(checkinAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet().createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(CREATED);
|
||||
}
|
||||
|
||||
/** Check that a normal user cannot create rules that use private actions. */
|
||||
@Test
|
||||
@Test(groups = {TestGroup.REST_API, TestGroup.RULES})
|
||||
public void createRuleWithActions_userCannotUsePrivateAction()
|
||||
{
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
@@ -391,7 +548,7 @@ public class CreateRulesTests extends RestTest
|
||||
}
|
||||
|
||||
/** Check that an administrator can create rules that use private actions. */
|
||||
@Test
|
||||
@Test(groups = {TestGroup.REST_API, TestGroup.RULES})
|
||||
public void createRuleWithActions_adminCanUsePrivateAction()
|
||||
{
|
||||
restClient.authenticateUser(dataUser.getAdminUser()).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
@@ -400,6 +557,33 @@ public class CreateRulesTests extends RestTest
|
||||
restClient.assertStatusCodeIs(CREATED);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that an administrator can create rules with email (private) action with reference to an email template.
|
||||
*/
|
||||
@Test(groups = {TestGroup.REST_API, TestGroup.RULES})
|
||||
public void createRuleWithActions_adminCanUseMailActionWithTemplate()
|
||||
{
|
||||
final RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
final RestActionBodyExecTemplateModel mailAction = new RestActionBodyExecTemplateModel();
|
||||
mailAction.setActionDefinitionId(MAIL_ACTION);
|
||||
final Map<String, Serializable> params = new HashMap<>();
|
||||
final UserModel sender = getRandomUserModel();
|
||||
final UserModel recipient = getRandomUserModel();
|
||||
params.put("from", sender.getEmailAddress());
|
||||
params.put("to", recipient.getEmailAddress());
|
||||
params.put("subject", "Test");
|
||||
final RestActionConstraintModel constraint = rulesUtils.getConstraintsForActionParam(user, MAIL_ACTION, TEMPLATE_PARAM);
|
||||
String templateScriptRef = constraint.getConstraintValues().stream().findFirst().get().getValue();
|
||||
params.put(TEMPLATE_PARAM, templateScriptRef);
|
||||
mailAction.setParams(params);
|
||||
ruleModel.setActions(List.of(mailAction));
|
||||
|
||||
restClient.authenticateUser(dataUser.getAdminUser()).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
.createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(CREATED);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check we get error when attempt to create a rule without any actions.
|
||||
*/
|
||||
@@ -423,17 +607,32 @@ public class CreateRulesTests extends RestTest
|
||||
public void createRuleWithInvalidActionsShouldFail()
|
||||
{
|
||||
final RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
final RestActionBodyExecTemplateModel invalidAction = new RestActionBodyExecTemplateModel();
|
||||
final String actionDefinitionId = "invalid-definition-value";
|
||||
invalidAction.setActionDefinitionId(actionDefinitionId);
|
||||
invalidAction.setParams(Map.of("dummy-key", "dummy-value"));
|
||||
final RestActionBodyExecTemplateModel invalidAction = rulesUtils.createCustomActionModel(actionDefinitionId, Map.of("dummy-key", "dummy-value"));
|
||||
ruleModel.setActions(List.of(invalidAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
.createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(BAD_REQUEST);
|
||||
restClient.assertLastError().containsSummary(String.format("Invalid action definition requested %s", actionDefinitionId));
|
||||
restClient.assertLastError().containsSummary(String.format("Invalid rule action definition requested %s", actionDefinitionId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check we get error when attempt to create a rule with an action tha is not applicable to rules.
|
||||
*/
|
||||
@Test(groups = {TestGroup.REST_API, TestGroup.RULES})
|
||||
public void createRuleWithNotApplicableActionShouldFail()
|
||||
{
|
||||
final RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
final RestActionBodyExecTemplateModel invalidAction =
|
||||
rulesUtils.createCustomActionModel(RulesTestsUtils.DELETE_RENDITION_ACTION, Map.of("dummy-key", "dummy-value"));
|
||||
ruleModel.setActions(List.of(invalidAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet().createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(BAD_REQUEST);
|
||||
restClient.assertLastError().containsSummary(String.format("Invalid rule action definition requested %s", RulesTestsUtils.DELETE_RENDITION_ACTION));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -443,9 +642,8 @@ public class CreateRulesTests extends RestTest
|
||||
public void createRuleWithMissingActionParametersShouldFail()
|
||||
{
|
||||
final RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
final RestActionBodyExecTemplateModel invalidAction = new RestActionBodyExecTemplateModel();
|
||||
final String actionDefinitionId = "copy";
|
||||
invalidAction.setActionDefinitionId(actionDefinitionId);
|
||||
final RestActionBodyExecTemplateModel invalidAction =
|
||||
rulesUtils.createCustomActionModel(RulesTestsUtils.COPY_ACTION, Collections.emptyMap());
|
||||
ruleModel.setActions(List.of(invalidAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
@@ -454,7 +652,7 @@ public class CreateRulesTests extends RestTest
|
||||
restClient.assertStatusCodeIs(BAD_REQUEST);
|
||||
restClient.assertLastError().containsSummary(
|
||||
String.format("Action parameters should not be null or empty for this action. See Action Definition for action of: %s",
|
||||
actionDefinitionId));
|
||||
COPY_ACTION));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -464,8 +662,8 @@ public class CreateRulesTests extends RestTest
|
||||
public void createRuleWithActionParameterNotFulfillingConstraint()
|
||||
{
|
||||
final RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
final String actionDefinitionId = "script";
|
||||
final String scriptRef = "script-ref";
|
||||
final String actionDefinitionId = SCRIPT_ACTION;
|
||||
final String scriptRef = RULE_SCRIPT_PARAM_ID;
|
||||
final String scriptNodeId = "dummy-script-node-id";
|
||||
final RestActionBodyExecTemplateModel scriptAction = rulesUtils.createCustomActionModel(actionDefinitionId, Map.of(scriptRef, scriptNodeId));
|
||||
ruleModel.setActions(List.of(scriptAction));
|
||||
@@ -484,14 +682,12 @@ public class CreateRulesTests extends RestTest
|
||||
* Check we get error when attempt to create a rule with action parameter that should not be passed.
|
||||
*/
|
||||
@Test(groups = {TestGroup.REST_API, TestGroup.RULES})
|
||||
public void createRuleWithoutInvalidActionParameterShouldFail()
|
||||
public void createRuleWithInvalidActionParameterShouldFail()
|
||||
{
|
||||
final RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
final RestActionBodyExecTemplateModel invalidAction = new RestActionBodyExecTemplateModel();
|
||||
final String actionDefinitionId = "add-features";
|
||||
invalidAction.setActionDefinitionId(actionDefinitionId);
|
||||
final String invalidParameterKey = "invalidParameterKey";
|
||||
invalidAction.setParams(Map.of(invalidParameterKey,"dummyValue"));
|
||||
final RestActionBodyExecTemplateModel invalidAction = rulesUtils.createCustomActionModel(
|
||||
RulesTestsUtils.ADD_FEATURES_ACTION, Map.of(invalidParameterKey, "dummyValue"));
|
||||
ruleModel.setActions(List.of(invalidAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
@@ -499,7 +695,7 @@ public class CreateRulesTests extends RestTest
|
||||
|
||||
restClient.assertStatusCodeIs(BAD_REQUEST);
|
||||
restClient.assertLastError().containsSummary(
|
||||
String.format("Action of definition id: %s must not contain parameter of name: %s", actionDefinitionId, invalidParameterKey));
|
||||
String.format("Action of definition id: %s must not contain parameter of name: %s", RulesTestsUtils.ADD_FEATURES_ACTION, invalidParameterKey));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -509,10 +705,7 @@ public class CreateRulesTests extends RestTest
|
||||
public void createRuleWithoutMandatoryActionParametersShouldFail()
|
||||
{
|
||||
final RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
final RestActionBodyExecTemplateModel invalidAction = new RestActionBodyExecTemplateModel();
|
||||
final String actionDefinitionId = "copy";
|
||||
invalidAction.setActionDefinitionId(actionDefinitionId);
|
||||
invalidAction.setParams(Map.of("deep-copy",false));
|
||||
final RestActionBodyExecTemplateModel invalidAction = rulesUtils.createCustomActionModel(COPY_ACTION, Map.of("deep-copy",false));
|
||||
ruleModel.setActions(List.of(invalidAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
@@ -529,10 +722,8 @@ public class CreateRulesTests extends RestTest
|
||||
public void createRuleThatUsesNonExistentNode()
|
||||
{
|
||||
RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
RestActionBodyExecTemplateModel invalidAction = new RestActionBodyExecTemplateModel();
|
||||
String actionDefinitionId = "copy";
|
||||
invalidAction.setActionDefinitionId(actionDefinitionId);
|
||||
invalidAction.setParams(Map.of("destination-folder", "non-existent-node"));
|
||||
RestActionBodyExecTemplateModel invalidAction = rulesUtils.createCustomActionModel(
|
||||
COPY_ACTION, Map.of("destination-folder", "non-existent-node"));
|
||||
ruleModel.setActions(List.of(invalidAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
@@ -552,10 +743,8 @@ public class CreateRulesTests extends RestTest
|
||||
FolderModel privateFolder = dataContent.usingAdmin().usingSite(privateSite).createFolder();
|
||||
|
||||
RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
RestActionBodyExecTemplateModel invalidAction = new RestActionBodyExecTemplateModel();
|
||||
String actionDefinitionId = "copy";
|
||||
invalidAction.setActionDefinitionId(actionDefinitionId);
|
||||
invalidAction.setParams(Map.of("destination-folder", privateFolder.getNodeRef()));
|
||||
RestActionBodyExecTemplateModel invalidAction = rulesUtils.createCustomActionModel(
|
||||
COPY_ACTION, Map.of("destination-folder", privateFolder.getNodeRef()));
|
||||
ruleModel.setActions(List.of(invalidAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
@@ -565,6 +754,144 @@ public class CreateRulesTests extends RestTest
|
||||
restClient.assertLastError().containsSummary("The entity with id: " + privateFolder.getNodeRef() + " was not found");
|
||||
}
|
||||
|
||||
/**
|
||||
* Check we get error when attempting to create a rule that copies files to a folder that a user only has read permission for.
|
||||
*/
|
||||
@Test (groups = { TestGroup.REST_API, TestGroup.RULES })
|
||||
public void createRuleThatWritesToNodeWithoutPermission()
|
||||
{
|
||||
SiteModel privateSite = dataSite.usingAdmin().createPrivateRandomSite();
|
||||
FolderModel privateFolder = dataContent.usingAdmin().usingSite(privateSite).createFolder();
|
||||
dataUser.usingAdmin().addUserToSite(user, privateSite, SiteConsumer);
|
||||
|
||||
RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
RestActionBodyExecTemplateModel invalidAction = rulesUtils.createCustomActionModel(
|
||||
COPY_ACTION, Map.of("destination-folder", privateFolder.getNodeRef()));
|
||||
|
||||
ruleModel.setActions(List.of(invalidAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
.createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(FORBIDDEN);
|
||||
restClient.assertLastError().containsSummary("No proper permissions for node: " + privateFolder.getNodeRef());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check we get error when attempting to create a rule that moves files to a node which is not a folder
|
||||
*/
|
||||
@Test(groups = {TestGroup.REST_API, TestGroup.RULES})
|
||||
public void createRuleThatMovesToNodeWhichIsNotAFolderShouldFail()
|
||||
{
|
||||
final FileModel fileModel = dataContent.usingUser(user).usingSite(site).createContent(getRandomFileModel(TEXT_PLAIN));
|
||||
|
||||
final RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
final RestActionBodyExecTemplateModel invalidAction = rulesUtils.createCustomActionModel(
|
||||
RulesTestsUtils.MOVE_ACTION, Map.of("destination-folder", fileModel.getNodeRef()));
|
||||
ruleModel.setActions(List.of(invalidAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
.createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(BAD_REQUEST);
|
||||
restClient.assertLastError().containsSummary("Node is not a folder " + fileModel.getNodeRef());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Check we get error when attempting to create a rule with mail action defined with non-existing mail template.
|
||||
*/
|
||||
@Test(groups = {TestGroup.REST_API, TestGroup.RULES})
|
||||
public void createRuleWithMailActionReferringToNonExistingTemplate()
|
||||
{
|
||||
final RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
final RestActionBodyExecTemplateModel mailAction = new RestActionBodyExecTemplateModel();
|
||||
mailAction.setActionDefinitionId(MAIL_ACTION);
|
||||
final Map<String, Serializable> params = new HashMap<>();
|
||||
final UserModel sender = getRandomUserModel();
|
||||
final UserModel recipient = getRandomUserModel();
|
||||
params.put("from", sender.getEmailAddress());
|
||||
params.put("to", recipient.getEmailAddress());
|
||||
params.put("subject", "Test");
|
||||
final String mailTemplate = "non-existing-node-id";
|
||||
params.put(TEMPLATE_PARAM, mailTemplate);
|
||||
mailAction.setParams(params);
|
||||
ruleModel.setActions(List.of(mailAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
.createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(BAD_REQUEST);
|
||||
restClient.assertLastError().containsSummary("Action parameter: template has invalid value (" + mailTemplate +
|
||||
"). Look up possible values for constraint name ac-email-templates");
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the user can create a rule with a script.
|
||||
*/
|
||||
@Test (groups = { TestGroup.REST_API, TestGroup.RULES })
|
||||
public void checkCanUseScriptInRule()
|
||||
{
|
||||
RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
RestActionBodyExecTemplateModel scriptAction = rulesUtils.createCustomActionModel(
|
||||
SCRIPT_ACTION, Map.of(RULE_SCRIPT_PARAM_ID, rulesUtils.getReviewAndApproveWorkflowNode()));
|
||||
ruleModel.setActions(List.of(scriptAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
.createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(CREATED);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the script has to be stored in the scripts directory in the data dictionary.
|
||||
*/
|
||||
@Test (groups = { TestGroup.REST_API, TestGroup.RULES })
|
||||
public void checkCantUseNodeOutsideScriptsDirectory()
|
||||
{
|
||||
STEP("Copy script to location outside data dictionary.");
|
||||
FolderModel folderOutsideDataDictionary = dataContent.usingUser(user).usingSite(site).createFolder();
|
||||
String sourceNodeId = rulesUtils.getReviewAndApproveWorkflowNode();
|
||||
ContentModel sourceNode = new ContentModel("/Data Dictionary/Scripts/start-pooled-review-workflow.js");
|
||||
sourceNode.setNodeRef("/workspace://SpacesStore/" + sourceNodeId);
|
||||
CmisObject scriptOutsideDataDictionary = dataContent.getContentActions().copyTo(dataUser.getAdminUser().getUsername(),
|
||||
dataUser.getAdminUser().getPassword(),
|
||||
sourceNode.getCmisLocation(),
|
||||
folderOutsideDataDictionary.getCmisLocation());
|
||||
String scriptId = scriptOutsideDataDictionary.getId().substring(0, scriptOutsideDataDictionary.getId().indexOf(";"));
|
||||
|
||||
STEP("Try to use this script in rule.");
|
||||
RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
RestActionBodyExecTemplateModel scriptAction = rulesUtils.createCustomActionModel(
|
||||
SCRIPT_ACTION, Map.of(RULE_SCRIPT_PARAM_ID, scriptId));
|
||||
ruleModel.setActions(List.of(scriptAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
.createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(BAD_REQUEST)
|
||||
.assertLastError().containsSummary("script-ref has invalid value");
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a real category needs to be supplied when linking to a category.
|
||||
*/
|
||||
@Test (groups = { TestGroup.REST_API, TestGroup.RULES })
|
||||
public void checkLinkToCategoryNeedsRealCategory()
|
||||
{
|
||||
STEP("Attempt to link to a category with a folder node, rather than a category node.");
|
||||
String nonCategoryNodeRef = ruleFolder.getNodeRef();
|
||||
RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
RestActionBodyExecTemplateModel categoryAction = rulesUtils.createCustomActionModel(
|
||||
RulesTestsUtils.LINK_CATEGORY_ACTION, Map.of("category-value", nonCategoryNodeRef));
|
||||
ruleModel.setActions(List.of(categoryAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
.createSingleRule(ruleModel);
|
||||
|
||||
restClient.assertStatusCodeIs(BAD_REQUEST);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check we can create a rule with multiple conditions
|
||||
*/
|
||||
@@ -623,4 +950,16 @@ public class CreateRulesTests extends RestTest
|
||||
restClient.assertStatusCodeIs(BAD_REQUEST);
|
||||
restClient.assertLastError().containsSummary("Category in condition is invalid");
|
||||
}
|
||||
|
||||
private String getAddPermissionsBody(String username, String role)
|
||||
{
|
||||
JsonObject userPermission = Json.createObjectBuilder().add("permissions",
|
||||
Json.createObjectBuilder()
|
||||
.add("isInheritanceEnabled", true)
|
||||
.add("locallySet", Json.createObjectBuilder()
|
||||
.add("authorityId", username)
|
||||
.add("name", role).add("accessStatus", "ALLOWED")))
|
||||
.build();
|
||||
return userPermission.toString();
|
||||
}
|
||||
}
|
||||
|
@@ -30,7 +30,10 @@ import static org.alfresco.rest.rules.RulesTestsUtils.LOCKABLE_ASPECT;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.RULE_NAME_DEFAULT;
|
||||
import static org.alfresco.utility.report.log.Step.STEP;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.alfresco.dataprep.CMISUtil;
|
||||
import org.alfresco.rest.RestTest;
|
||||
@@ -294,5 +297,28 @@ public class ExecuteRulesTests extends RestTest
|
||||
rulesUtils.assertThat(fileNode).containsAspects(AUDIO_ASPECT);
|
||||
}
|
||||
|
||||
//TODO: add test(s) that would cover handling executing broken rule and/or broken rule execution (ACS-3699)
|
||||
/**
|
||||
* Try to execute rule with broken action and receive 404 error.
|
||||
*/
|
||||
@Test(groups = { TestGroup.REST_API, TestGroup.RULES, TestGroup.ACTIONS })
|
||||
public void executeRules_copyActionWithDeletedDestinationFolder()
|
||||
{
|
||||
FolderModel owningFolder = dataContent.usingUser(user).usingSite(site).createFolder();
|
||||
FileModel owningFolderFile = dataContent.usingUser(user).usingResource(owningFolder).createContent(CMISUtil.DocumentType.TEXT_PLAIN);
|
||||
FolderModel destinationFolder = dataContent.usingUser(user).usingSite(site).createFolder();
|
||||
|
||||
STEP("Create copy action and rule");
|
||||
final Map<String, Serializable> copyParams =
|
||||
Map.of("destination-folder", destinationFolder.getNodeRef(), "deep-copy", true);
|
||||
final RestActionBodyExecTemplateModel copyAction = rulesUtils.createCustomActionModel("copy", copyParams);
|
||||
final RestRuleModel ruleModel = rulesUtils.createRuleModelWithDefaultValues();
|
||||
ruleModel.setActions(Arrays.asList(copyAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(owningFolder).usingDefaultRuleSet().createSingleRule(ruleModel);
|
||||
|
||||
STEP("Delete destination folder and execute rule");
|
||||
restClient.authenticateUser(user).withCoreAPI().usingNode(destinationFolder).deleteNode(destinationFolder.getNodeRef());
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(owningFolder).executeRules(rulesUtils.createRuleExecutionRequest());
|
||||
restClient.assertStatusCodeIs(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
@@ -26,6 +26,7 @@
|
||||
package org.alfresco.rest.rules;
|
||||
|
||||
import static org.alfresco.rest.requests.RuleSettings.IS_INHERITANCE_ENABLED;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.MOVE_ACTION;
|
||||
import static org.alfresco.utility.report.log.Step.STEP;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.springframework.http.HttpStatus.FORBIDDEN;
|
||||
@@ -341,7 +342,7 @@ public class GetRuleSetsTests extends RestTest
|
||||
dataContent.usingAdmin().usingResource(privateFolder).setInheritPermissions(false);
|
||||
// Create the grandchild with user and use admin to move it under the private folder.
|
||||
FolderModel publicGrandchild = dataContent.usingUser(user).usingSite(siteModel).createFolder();
|
||||
coreAPIForAdmin().usingActions().executeAction("move", publicGrandchild, ImmutableMap.of("destination-folder", "workspace://SpacesStore/" + privateFolder.getNodeRef()));
|
||||
coreAPIForAdmin().usingActions().executeAction(MOVE_ACTION, publicGrandchild, ImmutableMap.of("destination-folder", "workspace://SpacesStore/" + privateFolder.getNodeRef()));
|
||||
// Create the non-inheriting folder.
|
||||
FolderModel nonInheritingFolder = dataContent.usingUser(user).usingResource(folder).createFolder();
|
||||
RestRuleSettingsModel nonInheriting = new RestRuleSettingsModel();
|
||||
|
@@ -314,9 +314,11 @@ public class GetRulesTests extends RestTest
|
||||
public void getRuleActions()
|
||||
{
|
||||
STEP("Create a rule with a few actions");
|
||||
FolderModel folder = dataContent.usingUser(user).usingSite(site).createFolder();
|
||||
final RestRuleModel rule = restClient.authenticateUser(user).withPrivateAPI().usingNode(folder).usingDefaultRuleSet()
|
||||
.createSingleRule(rulesUtils.createVariousActions());
|
||||
final FolderModel folder = dataContent.usingUser(user).usingSite(site).createFolder();
|
||||
final RestRuleModel ruleWithVariousActions = rulesUtils.createRuleWithVariousActions();
|
||||
final UserModel admin = dataUser.getAdminUser();
|
||||
final RestRuleModel rule = restClient.authenticateUser(admin).withPrivateAPI().usingNode(folder).usingDefaultRuleSet()
|
||||
.createSingleRule(ruleWithVariousActions);
|
||||
|
||||
STEP("Retrieve the created rule via the GET endpoint");
|
||||
final RestRuleModel getRuleBody = restClient.authenticateUser(user).withPrivateAPI().usingNode(folder).usingDefaultRuleSet().getSingleRule(rule.getId());
|
||||
|
@@ -51,12 +51,11 @@ import org.alfresco.utility.data.DataUserAIS;
|
||||
import org.alfresco.utility.model.FolderModel;
|
||||
import org.alfresco.utility.model.SiteModel;
|
||||
import org.alfresco.utility.model.UserModel;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class RulesTestsUtils implements InitializingBean
|
||||
public class RulesTestsUtils
|
||||
{
|
||||
static final String RULE_NAME_DEFAULT = "ruleName";
|
||||
static final String RULE_DESCRIPTION_DEFAULT = "rule description";
|
||||
@@ -64,8 +63,6 @@ public class RulesTestsUtils implements InitializingBean
|
||||
static final boolean RULE_CASCADE_DEFAULT = true;
|
||||
static final boolean RULE_ASYNC_DEFAULT = true;
|
||||
static final boolean RULE_SHARED_DEFAULT = false;
|
||||
static final String RULE_SCRIPT_ID = "script";
|
||||
static final String RULE_SCRIPT_PARAM_ID = "script-ref";
|
||||
static final String RULE_ERROR_SCRIPT_LABEL = "Start Pooled Review and Approve Workflow";
|
||||
static final String INBOUND = "inbound";
|
||||
static final String UPDATE = "update";
|
||||
@@ -77,6 +74,15 @@ public class RulesTestsUtils implements InitializingBean
|
||||
static final String IS_SHARED = "isShared";
|
||||
static final String AUDIO_ASPECT = "audio:audio";
|
||||
static final String LOCKABLE_ASPECT = "cm:lockable";
|
||||
static final String TEMPLATE_PARAM = "template";
|
||||
static final String RULE_SCRIPT_PARAM_ID = "script-ref";
|
||||
static final String CHECKIN_ACTION = "check-in";
|
||||
static final String LINK_CATEGORY_ACTION = "link-category";
|
||||
static final String DELETE_RENDITION_ACTION = "delete-rendition";
|
||||
static final String COPY_ACTION = "copy";
|
||||
static final String ADD_FEATURES_ACTION = "add-features";
|
||||
static final String MOVE_ACTION = "move";
|
||||
static final String SCRIPT_ACTION = "script";
|
||||
|
||||
@Autowired
|
||||
private RestWrapper restClient;
|
||||
@@ -87,37 +93,49 @@ public class RulesTestsUtils implements InitializingBean
|
||||
@Autowired
|
||||
private DataContent dataContent;
|
||||
|
||||
private SiteModel site;
|
||||
/** Public site used by these helper methods. This is populated by the getter and should not be accessed directly. */
|
||||
private SiteModel publicSite;
|
||||
/** Script node used by these helper methods. This is populated by the getter and should not be accessed directly. */
|
||||
private String reviewAndApproveWorkflowNode;
|
||||
|
||||
/** Destination folder for copy action used by these helper methods. This is populated by the getter and should not be accessed directly. */
|
||||
private FolderModel copyDestinationFolder;
|
||||
|
||||
/** Destination folder for check out action used by these helper methods. This is populated by the getter and should not be accessed directly. */
|
||||
private FolderModel checkOutDestinationFolder;
|
||||
|
||||
/**
|
||||
* Initialise the util class.
|
||||
* Get the constraint value for a given action parameter label.
|
||||
*
|
||||
* @param user The user to use to obtain the information.
|
||||
* @param actionId The id of the action definition.
|
||||
* @param paramId The id of the parameter for the action.
|
||||
* @param constraintLabel The label of the desired value of the parameter.
|
||||
* @return The value to use for the parameter.
|
||||
*/
|
||||
@Override
|
||||
public void afterPropertiesSet()
|
||||
public String findConstraintValue(UserModel user, String actionId, String paramId, String constraintLabel)
|
||||
{
|
||||
UserModel admin = dataUser.getAdminUser();
|
||||
// Obtain the node ref for the review and approve workflow.
|
||||
RestActionDefinitionModel actionDef = restClient.authenticateUser(admin).withCoreAPI().usingActions().getActionDefinitionById(RULE_SCRIPT_ID);
|
||||
RestParameterDefinitionModel paramDef = actionDef.getParameterDefinitions().stream().filter(param -> param.getName().equals(RULE_SCRIPT_PARAM_ID)).findFirst().get();
|
||||
String constraintName = paramDef.getParameterConstraintName();
|
||||
RestActionConstraintModel constraintDef = restClient.authenticateUser(admin).withCoreAPI().usingActions().getActionConstraintByName(constraintName);
|
||||
RestActionConstraintDataModel reviewAndApprove = constraintDef.getConstraintValues().stream().filter(constraintValue -> constraintValue.getLabel().equals(RULE_ERROR_SCRIPT_LABEL)).findFirst().get();
|
||||
reviewAndApproveWorkflowNode = reviewAndApprove.getValue();
|
||||
|
||||
// Create a couple of public folders to be used as action destinations.
|
||||
site = dataSite.usingUser(admin).createPublicRandomSite();
|
||||
copyDestinationFolder = dataContent.usingUser(admin).usingSite(site).createFolder();
|
||||
checkOutDestinationFolder = dataContent.usingUser(admin).usingSite(site).createFolder();
|
||||
RestActionConstraintModel constraintDef = getConstraintsForActionParam(user, actionId, paramId);
|
||||
RestActionConstraintDataModel constraintDataModel = constraintDef.getConstraintValues().stream().filter(constraintValue -> constraintValue.getLabel().equals(constraintLabel)).findFirst().get();
|
||||
return constraintDataModel.getValue();
|
||||
}
|
||||
|
||||
public RestRuleModel createRuleModelWithModifiedValues()
|
||||
/**
|
||||
* Get all constraint values for a given action parameter.
|
||||
*
|
||||
* @param user The user to use to obtain the information.
|
||||
* @param actionId The id of the action definition.
|
||||
* @param paramId The id of the parameter for the action.
|
||||
* @return The value to use for the parameter.
|
||||
*/
|
||||
public RestActionConstraintModel getConstraintsForActionParam(UserModel user, String actionId, String paramId)
|
||||
{
|
||||
return createRuleModelWithModifiedValues(List.of(createAddAudioAspectAction()));
|
||||
RestActionDefinitionModel actionDef = restClient.authenticateUser(user).withCoreAPI().usingActions().getActionDefinitionById(actionId);
|
||||
RestParameterDefinitionModel paramDef = actionDef.getParameterDefinitions().stream().filter(param -> param.getName().equals(paramId)).findFirst().get();
|
||||
if (paramDef.getParameterConstraintName() == null)
|
||||
{
|
||||
throw new IllegalArgumentException("Supplied parameter " + paramId + " for action " + actionId + " does not have a defined constraint.");
|
||||
}
|
||||
String constraintName = paramDef.getParameterConstraintName();
|
||||
return restClient.authenticateUser(user).withCoreAPI().usingActions().getActionConstraintByName(constraintName);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -127,19 +145,49 @@ public class RulesTestsUtils implements InitializingBean
|
||||
*/
|
||||
public String getReviewAndApproveWorkflowNode()
|
||||
{
|
||||
if (reviewAndApproveWorkflowNode == null)
|
||||
{
|
||||
UserModel admin = dataUser.getAdminUser();
|
||||
reviewAndApproveWorkflowNode = findConstraintValue(admin, SCRIPT_ACTION, RULE_SCRIPT_PARAM_ID, RULE_ERROR_SCRIPT_LABEL);
|
||||
}
|
||||
return reviewAndApproveWorkflowNode;
|
||||
}
|
||||
|
||||
public SiteModel getPublicSite()
|
||||
{
|
||||
if (publicSite == null)
|
||||
{
|
||||
UserModel admin = dataUser.getAdminUser();
|
||||
publicSite = dataSite.usingUser(admin).createPublicRandomSite();
|
||||
}
|
||||
return publicSite;
|
||||
}
|
||||
|
||||
public FolderModel getCopyDestinationFolder()
|
||||
{
|
||||
if (copyDestinationFolder == null)
|
||||
{
|
||||
UserModel admin = dataUser.getAdminUser();
|
||||
copyDestinationFolder = dataContent.usingUser(admin).usingSite(getPublicSite()).createFolder();
|
||||
}
|
||||
return copyDestinationFolder;
|
||||
}
|
||||
|
||||
public FolderModel getCheckOutDestinationFolder()
|
||||
{
|
||||
if (checkOutDestinationFolder == null)
|
||||
{
|
||||
UserModel admin = dataUser.getAdminUser();
|
||||
checkOutDestinationFolder = dataContent.usingUser(admin).usingSite(getPublicSite()).createFolder();
|
||||
}
|
||||
return checkOutDestinationFolder;
|
||||
}
|
||||
|
||||
public RestRuleModel createRuleModelWithModifiedValues()
|
||||
{
|
||||
return createRuleModelWithModifiedValues(List.of(createAddAudioAspectAction()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a rule model filled with custom constant values.
|
||||
*
|
||||
@@ -198,7 +246,7 @@ public class RulesTestsUtils implements InitializingBean
|
||||
|
||||
public RestActionBodyExecTemplateModel createAddAspectAction(String aspect)
|
||||
{
|
||||
return createCustomActionModel("add-features", Map.of("aspect-name", aspect));
|
||||
return createCustomActionModel(ADD_FEATURES_ACTION, Map.of("aspect-name", aspect));
|
||||
}
|
||||
|
||||
public RestActionBodyExecTemplateModel createCustomActionModel(String actionDefinitionId, Map<String, Serializable> params)
|
||||
@@ -236,13 +284,13 @@ public class RulesTestsUtils implements InitializingBean
|
||||
));
|
||||
}
|
||||
|
||||
public RestRuleModel createVariousActions()
|
||||
public RestRuleModel createRuleWithVariousActions()
|
||||
{
|
||||
final Map<String, Serializable> copyParams =
|
||||
Map.of("destination-folder", copyDestinationFolder.getNodeRef(), "deep-copy", true);
|
||||
final RestActionBodyExecTemplateModel copyAction = createCustomActionModel("copy", copyParams);
|
||||
Map.of("destination-folder", getCopyDestinationFolder().getNodeRef(), "deep-copy", true);
|
||||
final RestActionBodyExecTemplateModel copyAction = createCustomActionModel(COPY_ACTION, copyParams);
|
||||
final Map<String, Serializable> checkOutParams =
|
||||
Map.of("destination-folder", checkOutDestinationFolder.getNodeRef(), "assoc-name", "cm:checkout",
|
||||
Map.of("destination-folder", getCheckOutDestinationFolder().getNodeRef(), "assoc-name", "cm:checkout",
|
||||
"assoc-type", "cm:contains");
|
||||
final RestActionBodyExecTemplateModel checkOutAction = createCustomActionModel("check-out", checkOutParams);
|
||||
// The counter action takes no parameters, so check we can omit the "params" entry.
|
||||
|
@@ -26,6 +26,8 @@
|
||||
package org.alfresco.rest.rules;
|
||||
|
||||
import static org.alfresco.rest.actions.access.AccessRestrictionUtil.ERROR_MESSAGE_ACCESS_RESTRICTED;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.ADD_FEATURES_ACTION;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.COPY_ACTION;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.ID;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.INBOUND;
|
||||
import static org.alfresco.rest.rules.RulesTestsUtils.INVERTED;
|
||||
@@ -247,7 +249,7 @@ public class UpdateRulesTests extends RestTest
|
||||
.updateRule(rule.getId(), rule);
|
||||
|
||||
restClient.assertStatusCodeIs(BAD_REQUEST);
|
||||
restClient.assertLastError().containsSummary(String.format("Invalid action definition requested %s", actionDefinitionId));
|
||||
restClient.assertLastError().containsSummary(String.format("Invalid rule action definition requested %s", actionDefinitionId));
|
||||
}
|
||||
|
||||
/** Check we can use the POST response to create the new rule. */
|
||||
@@ -257,7 +259,7 @@ public class UpdateRulesTests extends RestTest
|
||||
FolderModel destination = dataContent.usingUser(user).usingSite(site).createFolder();
|
||||
|
||||
RestActionBodyExecTemplateModel copyAction = new RestActionBodyExecTemplateModel();
|
||||
copyAction.setActionDefinitionId("copy");
|
||||
copyAction.setActionDefinitionId(COPY_ACTION);
|
||||
copyAction.setParams(ImmutableMap.of("destination-folder", destination.getNodeRef()));
|
||||
RestRuleModel rule = createAndSaveRule("Rule name", List.of(copyAction));
|
||||
|
||||
@@ -269,7 +271,7 @@ public class UpdateRulesTests extends RestTest
|
||||
|
||||
restClient.assertStatusCodeIs(OK);
|
||||
updatedRule.assertThat().field("name").is("Updated rule name")
|
||||
.assertThat().field("actions.actionDefinitionId").is(List.of("copy"))
|
||||
.assertThat().field("actions.actionDefinitionId").is(List.of(COPY_ACTION))
|
||||
.assertThat().field("actions.params").is(List.of(ImmutableMap.of("destination-folder", destination.getNodeRef())));
|
||||
}
|
||||
|
||||
@@ -459,12 +461,10 @@ public class UpdateRulesTests extends RestTest
|
||||
final RestRuleModel rule = createAndSaveRule(rulesUtils.createRuleModelWithModifiedValues());
|
||||
|
||||
STEP("Try to update the rule by adding several actions");
|
||||
final Map<String, Serializable> copyParams =
|
||||
Map.of("destination-folder", rulesUtils.getCopyDestinationFolder().getNodeRef(), "deep-copy", true);
|
||||
final RestActionBodyExecTemplateModel copyAction = rulesUtils.createCustomActionModel("copy", copyParams);
|
||||
final RestActionBodyExecTemplateModel counterAction = rulesUtils.createCustomActionModel("counter", null);
|
||||
final Map<String, Serializable> addAspectParams = Map.of("aspect-name", "cm:taggable");
|
||||
final RestActionBodyExecTemplateModel addAspectAction = rulesUtils.createCustomActionModel("add-features", addAspectParams);
|
||||
rule.setActions(Arrays.asList(copyAction, addAspectAction));
|
||||
final RestActionBodyExecTemplateModel addAspectAction = rulesUtils.createCustomActionModel(ADD_FEATURES_ACTION, addAspectParams);
|
||||
rule.setActions(Arrays.asList(counterAction, addAspectAction));
|
||||
|
||||
final RestRuleModel updatedRule = restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
.updateRule(rule.getId(), rule);
|
||||
@@ -489,7 +489,8 @@ public class UpdateRulesTests extends RestTest
|
||||
final RestActionBodyExecTemplateModel checkOutAction = rulesUtils.createCustomActionModel("check-out", checkOutParams);
|
||||
rule.setActions(List.of(checkOutAction));
|
||||
|
||||
restClient.authenticateUser(user).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
final UserModel admin = dataUser.getAdminUser();
|
||||
restClient.authenticateUser(admin).withPrivateAPI().usingNode(ruleFolder).usingDefaultRuleSet()
|
||||
.updateRule(rule.getId(), rule);
|
||||
|
||||
restClient.assertStatusCodeIs(BAD_REQUEST);
|
||||
@@ -507,7 +508,7 @@ public class UpdateRulesTests extends RestTest
|
||||
|
||||
STEP("Try to update the rule by adding action with invalid parameter (non-existing namespace in value)");
|
||||
final RestActionBodyExecTemplateModel action = new RestActionBodyExecTemplateModel();
|
||||
action.setActionDefinitionId("add-features");
|
||||
action.setActionDefinitionId(ADD_FEATURES_ACTION);
|
||||
final String aspectNameParam = "aspect-name";
|
||||
final String paramValue = "dummy:dummy";
|
||||
action.setParams(Map.of(aspectNameParam, paramValue));
|
||||
|
@@ -9,7 +9,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo-tests</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<developers>
|
||||
|
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo-packaging</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
|
16
pom.xml
16
pom.xml
@@ -2,7 +2,7 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>alfresco-community-repo</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>Alfresco Community Repo Parent</name>
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
|
||||
<properties>
|
||||
<acs.version.major>7</acs.version.major>
|
||||
<acs.version.minor>3</acs.version.minor>
|
||||
<acs.version.minor>4</acs.version.minor>
|
||||
<acs.version.revision>0</acs.version.revision>
|
||||
<acs.version.label />
|
||||
<amp.min.version>${acs.version.major}.0.0</amp.min.version>
|
||||
@@ -51,8 +51,8 @@
|
||||
<dependency.alfresco-log-sanitizer.version>0.2</dependency.alfresco-log-sanitizer.version>
|
||||
<dependency.activiti-engine.version>5.23.0</dependency.activiti-engine.version>
|
||||
<dependency.activiti.version>5.23.0</dependency.activiti.version>
|
||||
<dependency.alfresco-transform-service.version>2.0.0-A5</dependency.alfresco-transform-service.version>
|
||||
<dependency.alfresco-transform-core.version>3.0.0-A6</dependency.alfresco-transform-core.version>
|
||||
<dependency.alfresco-transform-service.version>2.0.0</dependency.alfresco-transform-service.version>
|
||||
<dependency.alfresco-transform-core.version>3.0.0</dependency.alfresco-transform-core.version>
|
||||
<dependency.alfresco-greenmail.version>6.4</dependency.alfresco-greenmail.version>
|
||||
<dependency.acs-event-model.version>0.0.16</dependency.acs-event-model.version>
|
||||
|
||||
@@ -109,9 +109,9 @@
|
||||
<dependency.jakarta-json-path.version>2.7.0</dependency.jakarta-json-path.version>
|
||||
<dependency.jakarta-rpc-api.version>1.1.4</dependency.jakarta-rpc-api.version>
|
||||
|
||||
<alfresco.googledrive.version>3.3.0-A1</alfresco.googledrive.version>
|
||||
<alfresco.aos-module.version>1.4.1</alfresco.aos-module.version>
|
||||
<alfresco.api-explorer.version>7.3.0-A1</alfresco.api-explorer.version> <!-- Also in alfresco-enterprise-share -->
|
||||
<alfresco.googledrive.version>3.3.0</alfresco.googledrive.version>
|
||||
<alfresco.aos-module.version>1.5.0</alfresco.aos-module.version>
|
||||
<alfresco.api-explorer.version>7.3.0</alfresco.api-explorer.version> <!-- Also in alfresco-enterprise-share -->
|
||||
|
||||
<alfresco.maven-plugin.version>2.2.0</alfresco.maven-plugin.version>
|
||||
<license-maven-plugin.version>2.0.1.alfresco-2</license-maven-plugin.version>
|
||||
@@ -149,7 +149,7 @@
|
||||
<connection>scm:git:https://github.com/Alfresco/alfresco-community-repo.git</connection>
|
||||
<developerConnection>scm:git:https://github.com/Alfresco/alfresco-community-repo.git</developerConnection>
|
||||
<url>https://github.com/Alfresco/alfresco-community-repo</url>
|
||||
<tag>17.169</tag>
|
||||
<tag>20.3</tag>
|
||||
</scm>
|
||||
|
||||
<distributionManagement>
|
||||
|
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@@ -27,6 +27,8 @@
|
||||
package org.alfresco.rest.api;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.alfresco.rest.api.model.Action;
|
||||
import org.alfresco.rest.api.model.ActionDefinition;
|
||||
import org.alfresco.rest.api.model.ActionParameterConstraint;
|
||||
@@ -53,4 +55,6 @@ public interface Actions
|
||||
|
||||
@Experimental
|
||||
ActionParameterConstraint getActionConstraint(String constraintName);
|
||||
@Experimental
|
||||
ActionDefinition getRuleActionDefinitionById(String actionDefinitionId);
|
||||
}
|
||||
|
@@ -26,13 +26,35 @@
|
||||
|
||||
package org.alfresco.rest.api.actions;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.alfresco.rest.api.model.rules.Action;
|
||||
import org.alfresco.service.Experimental;
|
||||
|
||||
@Experimental
|
||||
public interface ActionValidator
|
||||
{
|
||||
|
||||
String ALL_ACTIONS = "all";
|
||||
|
||||
/**
|
||||
* Provides validation logic for given action.
|
||||
*/
|
||||
void validate(Action action);
|
||||
|
||||
boolean isEnabled();
|
||||
/**
|
||||
* Returns priority of validator (applied to bulk validation in @see {@link org.alfresco.rest.api.impl.mapper.rules.RestRuleActionModelMapper})
|
||||
* The lower number, the higher priority is set for the validator.
|
||||
* @return priority expressed as int
|
||||
*/
|
||||
int getPriority();
|
||||
|
||||
/**
|
||||
* By default validator is applied to all actions
|
||||
*
|
||||
* @return indicator for all defined action definition ids
|
||||
*/
|
||||
default List<String> getActionDefinitionIds() {
|
||||
return List.of(ALL_ACTIONS);
|
||||
}
|
||||
}
|
||||
|
@@ -145,21 +145,7 @@ public class ActionsImpl implements Actions
|
||||
private ActionDefinition getActionDefinition(
|
||||
org.alfresco.service.cmr.action.ActionDefinition actionDefinitionId)
|
||||
{
|
||||
List<ActionDefinition.ParameterDefinition> paramDefs =
|
||||
actionDefinitionId.
|
||||
getParameterDefinitions().
|
||||
stream().
|
||||
map(this::toModel).
|
||||
collect(Collectors.toList());
|
||||
return new ActionDefinition(
|
||||
actionDefinitionId.getName(), // ID is a synonym for name.
|
||||
actionDefinitionId.getName(),
|
||||
actionDefinitionId.getTitle(),
|
||||
actionDefinitionId.getDescription(),
|
||||
toShortQNames(actionDefinitionId.getApplicableTypes()),
|
||||
actionDefinitionId.getAdhocPropertiesAllowed(),
|
||||
actionDefinitionId.getTrackStatus(),
|
||||
paramDefs);
|
||||
return mapFromServiceModel(actionDefinitionId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -215,23 +201,7 @@ public class ActionsImpl implements Actions
|
||||
|
||||
List<ActionDefinition> sortedPage = actionDefinitions.
|
||||
stream().
|
||||
map(actionDefinition -> {
|
||||
List<ActionDefinition.ParameterDefinition> paramDefs =
|
||||
actionDefinition.
|
||||
getParameterDefinitions().
|
||||
stream().
|
||||
map(this::toModel).
|
||||
collect(Collectors.toList());
|
||||
return new ActionDefinition(
|
||||
actionDefinition.getName(), // ID is a synonym for name.
|
||||
actionDefinition.getName(),
|
||||
actionDefinition.getTitle(),
|
||||
actionDefinition.getDescription(),
|
||||
toShortQNames(actionDefinition.getApplicableTypes()),
|
||||
actionDefinition.getAdhocPropertiesAllowed(),
|
||||
actionDefinition.getTrackStatus(),
|
||||
paramDefs);
|
||||
}).
|
||||
map(this::mapFromServiceModel).
|
||||
sorted(comparator).
|
||||
skip(skip).
|
||||
limit(maxItems).
|
||||
@@ -246,6 +216,40 @@ public class ActionsImpl implements Actions
|
||||
actionDefinitions.size());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Experimental
|
||||
public ActionDefinition getRuleActionDefinitionById(String actionDefinitionId)
|
||||
{
|
||||
if (actionDefinitionId == null)
|
||||
{
|
||||
throw new InvalidArgumentException("actionDefinitionId is null");
|
||||
}
|
||||
return actionService.getActionDefinitions().stream()
|
||||
.filter(a -> actionDefinitionId.equals(a.getName()))
|
||||
.map(this::mapFromServiceModel)
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new NotFoundException(NotFoundException.DEFAULT_MESSAGE_ID, new String[] {actionDefinitionId}));
|
||||
}
|
||||
|
||||
private ActionDefinition mapFromServiceModel(org.alfresco.service.cmr.action.ActionDefinition actionDefinition)
|
||||
{
|
||||
List<ActionDefinition.ParameterDefinition> paramDefs =
|
||||
actionDefinition.
|
||||
getParameterDefinitions().
|
||||
stream().
|
||||
map(this::toModel).
|
||||
collect(Collectors.toList());
|
||||
return new ActionDefinition(
|
||||
actionDefinition.getName(), // ID is a synonym for name.
|
||||
actionDefinition.getName(),
|
||||
actionDefinition.getTitle(),
|
||||
actionDefinition.getDescription(),
|
||||
toShortQNames(actionDefinition.getApplicableTypes()),
|
||||
actionDefinition.getAdhocPropertiesAllowed(),
|
||||
actionDefinition.getTrackStatus(),
|
||||
paramDefs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Action executeAction(Action action, Parameters parameters)
|
||||
{
|
||||
|
@@ -29,13 +29,15 @@ package org.alfresco.rest.api.impl.mapper.rules;
|
||||
import static java.util.Collections.emptyMap;
|
||||
|
||||
import static org.alfresco.repo.action.access.ActionAccessRestriction.ACTION_CONTEXT_PARAM_NAME;
|
||||
import static org.alfresco.rest.api.actions.ActionValidator.ALL_ACTIONS;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.alfresco.repo.action.ActionImpl;
|
||||
import org.alfresco.repo.action.CompositeActionImpl;
|
||||
@@ -80,7 +82,7 @@ public class RestRuleActionModelMapper implements RestModelMapper<Action, org.al
|
||||
final Map<String, Serializable> convertedParams = actionModel.getParameterValues()
|
||||
.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, e -> parameterConverter.convertParamFromServiceModel(e.getValue())));
|
||||
.collect(HashMap::new, (m, v) -> m.put(v.getKey(), parameterConverter.convertParamFromServiceModel(v.getValue())), HashMap::putAll);
|
||||
convertedParams.remove(ACTION_CONTEXT_PARAM_NAME);
|
||||
builder.params(convertedParams);
|
||||
}
|
||||
@@ -116,7 +118,9 @@ public class RestRuleActionModelMapper implements RestModelMapper<Action, org.al
|
||||
}
|
||||
private void validateAction(Action action) {
|
||||
actionValidators.stream()
|
||||
.filter(ActionValidator::isEnabled)
|
||||
.forEach(v -> v.validate(action));
|
||||
.filter(v -> (v.getActionDefinitionIds().contains(action.getActionDefinitionId()) ||
|
||||
v.getActionDefinitionIds().equals(List.of(ALL_ACTIONS))))
|
||||
.sorted(Comparator.comparing(ActionValidator::getPriority))
|
||||
.forEachOrdered(v -> v.validate(action));
|
||||
}
|
||||
}
|
||||
|
@@ -34,6 +34,7 @@ import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.alfresco.rest.api.Nodes;
|
||||
import org.alfresco.rest.framework.core.exceptions.EntityNotFoundException;
|
||||
@@ -51,6 +52,7 @@ import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter;
|
||||
import org.alfresco.service.cmr.security.PermissionService;
|
||||
import org.alfresco.service.namespace.NamespaceService;
|
||||
import org.alfresco.service.namespace.QName;
|
||||
import org.apache.logging.log4j.util.Strings;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||
@@ -58,6 +60,8 @@ import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||
@Experimental
|
||||
public class ActionParameterConverter
|
||||
{
|
||||
static final String ACTION_PARAMETER_SHOULD_NOT_HAVE_EMPTY_OR_NULL_VALUE =
|
||||
"Action parameter should not have empty or null value";
|
||||
private final DictionaryService dictionaryService;
|
||||
private final ActionService actionService;
|
||||
private final NamespaceService namespaceService;
|
||||
@@ -93,6 +97,9 @@ public class ActionParameterConverter
|
||||
|
||||
for (Map.Entry<String, Serializable> param : params.entrySet())
|
||||
{
|
||||
if (Objects.toString(param.getValue(), Strings.EMPTY).isEmpty()) {
|
||||
throw new InvalidArgumentException(ACTION_PARAMETER_SHOULD_NOT_HAVE_EMPTY_OR_NULL_VALUE, new String[] {param.getKey()});
|
||||
}
|
||||
final ParameterDefinition paramDef = definition.getParameterDefintion(param.getKey());
|
||||
if (paramDef == null && !definition.getAdhocPropertiesAllowed())
|
||||
{
|
||||
@@ -159,16 +166,17 @@ public class ActionParameterConverter
|
||||
}
|
||||
else
|
||||
{
|
||||
if (typeQName.equals(DataTypeDefinition.QNAME) && typeQName.toString().contains(":"))
|
||||
final String stringValue = Objects.toString(propertyValue, Strings.EMPTY);
|
||||
if (typeQName.isMatch(DataTypeDefinition.QNAME) && typeQName.toString().contains(":"))
|
||||
{
|
||||
value = QName.createQName(propertyValue.toString(), namespaceService);
|
||||
value = QName.createQName(stringValue, namespaceService);
|
||||
}
|
||||
else if (typeQName.isMatch(DataTypeDefinition.NODE_REF))
|
||||
{
|
||||
NodeRef nodeRef = nodes.validateOrLookupNode(propertyValue.toString(), null);
|
||||
NodeRef nodeRef = nodes.validateOrLookupNode(stringValue, null);
|
||||
if (permissionService.hasReadPermission(nodeRef) != ALLOWED)
|
||||
{
|
||||
throw new EntityNotFoundException(propertyValue.toString());
|
||||
throw new EntityNotFoundException(stringValue);
|
||||
}
|
||||
value = nodeRef;
|
||||
}
|
||||
|
@@ -0,0 +1,171 @@
|
||||
/*
|
||||
* #%L
|
||||
* Alfresco Remote API
|
||||
* %%
|
||||
* Copyright (C) 2005 - 2022 Alfresco Software Limited
|
||||
* %%
|
||||
* This file is part of the Alfresco software.
|
||||
* If the software was purchased under a paid Alfresco license, the terms of
|
||||
* the paid license agreement will prevail. Otherwise, the software is
|
||||
* provided under the following open source license terms:
|
||||
*
|
||||
* Alfresco is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Alfresco is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
|
||||
* #L%
|
||||
*/
|
||||
|
||||
package org.alfresco.rest.api.impl.validator.actions;
|
||||
|
||||
import static org.alfresco.model.ContentModel.TYPE_CATEGORY;
|
||||
import static org.alfresco.model.ContentModel.TYPE_FOLDER;
|
||||
import static org.alfresco.service.cmr.dictionary.DataTypeDefinition.NODE_REF;
|
||||
import static org.alfresco.service.cmr.security.AccessStatus.ALLOWED;
|
||||
import static org.alfresco.service.cmr.security.PermissionService.WRITE;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.alfresco.repo.action.executer.CheckOutActionExecuter;
|
||||
import org.alfresco.repo.action.executer.CopyActionExecuter;
|
||||
import org.alfresco.repo.action.executer.ImageTransformActionExecuter;
|
||||
import org.alfresco.repo.action.executer.ImporterActionExecuter;
|
||||
import org.alfresco.repo.action.executer.LinkCategoryActionExecuter;
|
||||
import org.alfresco.repo.action.executer.MoveActionExecuter;
|
||||
import org.alfresco.repo.action.executer.SimpleWorkflowActionExecuter;
|
||||
import org.alfresco.repo.action.executer.TransformActionExecuter;
|
||||
import org.alfresco.rest.api.Actions;
|
||||
import org.alfresco.rest.api.Nodes;
|
||||
import org.alfresco.rest.api.actions.ActionValidator;
|
||||
import org.alfresco.rest.api.model.ActionDefinition;
|
||||
import org.alfresco.rest.api.model.rules.Action;
|
||||
import org.alfresco.rest.framework.core.exceptions.EntityNotFoundException;
|
||||
import org.alfresco.rest.framework.core.exceptions.InvalidArgumentException;
|
||||
import org.alfresco.rest.framework.core.exceptions.PermissionDeniedException;
|
||||
import org.alfresco.service.cmr.repository.NodeRef;
|
||||
import org.alfresco.service.cmr.security.PermissionService;
|
||||
import org.alfresco.service.namespace.NamespaceService;
|
||||
import org.apache.commons.collections.MapUtils;
|
||||
import org.apache.logging.log4j.util.Strings;
|
||||
|
||||
/**
|
||||
* This class provides logic for validation of permissions for action parameters which reference node.
|
||||
*/
|
||||
public class ActionNodeParameterValidator implements ActionValidator
|
||||
{
|
||||
/**
|
||||
* This list holds action parameter names which require only READ permission on a referenced node
|
||||
* That means, all other parameters that reference nodes will require WRITE permission
|
||||
*/
|
||||
static final Map<String, List<String>> REQUIRE_READ_PERMISSION_PARAMS =
|
||||
Map.of(LinkCategoryActionExecuter.NAME, List.of(LinkCategoryActionExecuter.PARAM_CATEGORY_VALUE));
|
||||
|
||||
static final String NO_PROPER_PERMISSIONS_FOR_NODE = "No proper permissions for node: ";
|
||||
static final String NOT_A_CATEGORY = "Node is not a category ";
|
||||
static final String NOT_A_FOLDER = "Node is not a folder ";
|
||||
|
||||
private final Actions actions;
|
||||
private final NamespaceService namespaceService;
|
||||
private final Nodes nodes;
|
||||
private final PermissionService permissionService;
|
||||
|
||||
public ActionNodeParameterValidator(Actions actions, NamespaceService namespaceService, Nodes nodes,
|
||||
PermissionService permissionService)
|
||||
{
|
||||
this.actions = actions;
|
||||
this.namespaceService = namespaceService;
|
||||
this.nodes = nodes;
|
||||
this.permissionService = permissionService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates action parameters that reference nodes against access permissions for executing user.
|
||||
*
|
||||
* @param action Action to be validated
|
||||
*/
|
||||
@Override
|
||||
public void validate(Action action)
|
||||
{
|
||||
final ActionDefinition actionDefinition = actions.getRuleActionDefinitionById(action.getActionDefinitionId());
|
||||
final List<ActionDefinition.ParameterDefinition> nodeRefParams = actionDefinition.getParameterDefinitions().stream()
|
||||
.filter(pd -> NODE_REF.toPrefixString(namespaceService).equals(pd.getType()))
|
||||
.collect(Collectors.toList());
|
||||
validateNodes(nodeRefParams, action);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return List of action definitions applicable to this validator
|
||||
*/
|
||||
@Override
|
||||
public List<String> getActionDefinitionIds()
|
||||
{
|
||||
return List.of(CopyActionExecuter.NAME, MoveActionExecuter.NAME, CheckOutActionExecuter.NAME, ImporterActionExecuter.NAME,
|
||||
LinkCategoryActionExecuter.NAME, SimpleWorkflowActionExecuter.NAME, TransformActionExecuter.NAME,
|
||||
ImageTransformActionExecuter.NAME);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPriority()
|
||||
{
|
||||
return Integer.MIN_VALUE + 1;
|
||||
}
|
||||
|
||||
private void validateNodes(final List<ActionDefinition.ParameterDefinition> nodeRefParamDefinitions,
|
||||
final Action action)
|
||||
{
|
||||
if (MapUtils.isNotEmpty(action.getParams()))
|
||||
{
|
||||
nodeRefParamDefinitions.stream()
|
||||
.filter(pd -> action.getParams().containsKey(pd.getName()))
|
||||
.forEach(p -> {
|
||||
final String nodeId = Objects.toString(action.getParams().get(p.getName()), Strings.EMPTY);
|
||||
final NodeRef nodeRef = nodes.validateNode(nodeId);
|
||||
validatePermission(action.getActionDefinitionId(), p.getName(), nodeRef);
|
||||
validateType(action.getActionDefinitionId(), nodeRef);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void validatePermission(final String actionDefinitionId, final String paramName, final NodeRef nodeRef)
|
||||
{
|
||||
if (permissionService.hasReadPermission(nodeRef) != ALLOWED)
|
||||
{
|
||||
throw new EntityNotFoundException(nodeRef.getId());
|
||||
}
|
||||
if (!REQUIRE_READ_PERMISSION_PARAMS.containsKey(actionDefinitionId) ||
|
||||
REQUIRE_READ_PERMISSION_PARAMS.get(actionDefinitionId).stream().noneMatch(paramName::equals))
|
||||
{
|
||||
if (permissionService.hasPermission(nodeRef, WRITE) != ALLOWED)
|
||||
{
|
||||
throw new PermissionDeniedException(NO_PROPER_PERMISSIONS_FOR_NODE + nodeRef.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateType(final String actionDefinitionId, final NodeRef nodeRef)
|
||||
{
|
||||
if (!LinkCategoryActionExecuter.NAME.equals(actionDefinitionId))
|
||||
{
|
||||
if (!nodes.nodeMatches(nodeRef, Set.of(TYPE_FOLDER), Collections.emptySet()))
|
||||
{
|
||||
throw new InvalidArgumentException(NOT_A_FOLDER + nodeRef.getId());
|
||||
}
|
||||
} else if (!nodes.nodeMatches(nodeRef, Set.of(TYPE_CATEGORY), Collections.emptySet()))
|
||||
{
|
||||
throw new InvalidArgumentException(NOT_A_CATEGORY + nodeRef.getId());
|
||||
}
|
||||
}
|
||||
}
|
@@ -27,7 +27,11 @@
|
||||
package org.alfresco.rest.api.impl.validator.actions;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.alfresco.rest.api.Actions;
|
||||
import org.alfresco.rest.api.actions.ActionValidator;
|
||||
@@ -39,6 +43,7 @@ import org.alfresco.rest.framework.core.exceptions.NotFoundException;
|
||||
import org.alfresco.service.Experimental;
|
||||
import org.apache.commons.collections.CollectionUtils;
|
||||
import org.apache.commons.collections.MapUtils;
|
||||
import org.apache.logging.log4j.util.Strings;
|
||||
|
||||
/**
|
||||
* This class will validate all action types against action parameters definitions (mandatory parameters, parameter constraints)
|
||||
@@ -46,14 +51,14 @@ import org.apache.commons.collections.MapUtils;
|
||||
@Experimental
|
||||
public class ActionParameterDefinitionValidator implements ActionValidator
|
||||
{
|
||||
private static final boolean IS_ENABLED = true;
|
||||
static final String INVALID_PARAMETER_VALUE =
|
||||
"Action parameter: %s has invalid value (%s). Look up possible values for constraint name %s";
|
||||
static final String MISSING_PARAMETER = "Missing action's mandatory parameter: %s";
|
||||
static final String MUST_NOT_CONTAIN_PARAMETER = "Action of definition id: %s must not contain parameter of name: %s";
|
||||
static final String PARAMS_SHOULD_NOT_BE_EMPTY =
|
||||
"Action parameters should not be null or empty for this action. See Action Definition for action of: %s";
|
||||
static final String INVALID_ACTION_DEFINITION = "Invalid action definition requested %s";
|
||||
static final String INVALID_ACTION_DEFINITION = "Invalid rule action definition requested %s";
|
||||
static final String EMPTY_ACTION_DEFINITION = "Empty/null rule action definition id";
|
||||
|
||||
private final Actions actions;
|
||||
|
||||
@@ -71,51 +76,81 @@ public class ActionParameterDefinitionValidator implements ActionValidator
|
||||
public void validate(Action action)
|
||||
{
|
||||
ActionDefinition actionDefinition;
|
||||
final String actionDefinitionId = action.getActionDefinitionId();
|
||||
if (Strings.isBlank(actionDefinitionId))
|
||||
{
|
||||
throw new InvalidArgumentException(EMPTY_ACTION_DEFINITION);
|
||||
}
|
||||
try
|
||||
{
|
||||
actionDefinition = actions.getActionDefinitionById(action.getActionDefinitionId());
|
||||
} catch (NotFoundException e) {
|
||||
throw new InvalidArgumentException(String.format(INVALID_ACTION_DEFINITION, action.getActionDefinitionId()));
|
||||
actionDefinition = actions.getRuleActionDefinitionById(actionDefinitionId);
|
||||
} catch (NotFoundException e)
|
||||
{
|
||||
throw new InvalidArgumentException(String.format(INVALID_ACTION_DEFINITION, actionDefinitionId));
|
||||
}
|
||||
validateParametersSize(action.getParams(), actionDefinition);
|
||||
final Map<String, Serializable> params = action.getParams();
|
||||
if (MapUtils.isNotEmpty(params))
|
||||
{
|
||||
params.forEach((key, value) -> checkParameterShouldExist(key, actionDefinition));
|
||||
actionDefinition.getParameterDefinitions().forEach(p -> validateParameterDefinitions(p, params));
|
||||
getParameterDefinitions(actionDefinition).forEach(p -> validateParameterDefinitions(p, params));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This validator should be applied to all actions
|
||||
*
|
||||
* @return list of all defined action definition ids
|
||||
*/
|
||||
@Override
|
||||
public boolean isEnabled()
|
||||
public List<String> getActionDefinitionIds()
|
||||
{
|
||||
return IS_ENABLED;
|
||||
return List.of(ALL_ACTIONS);
|
||||
}
|
||||
|
||||
/**
|
||||
* This validator should have highest priority and be executed first of all (thus minimal integer is returned here).
|
||||
*
|
||||
* @return minimal integer value
|
||||
*/
|
||||
@Override
|
||||
public int getPriority()
|
||||
{
|
||||
return Integer.MIN_VALUE;
|
||||
}
|
||||
|
||||
private void validateParametersSize(final Map<String, Serializable> params, final ActionDefinition actionDefinition)
|
||||
{
|
||||
if (CollectionUtils.isNotEmpty(actionDefinition.getParameterDefinitions()) && MapUtils.isEmpty(params))
|
||||
final List<ActionDefinition.ParameterDefinition> parameterDefinitions = getParameterDefinitions(actionDefinition);
|
||||
if (CollectionUtils.isNotEmpty(
|
||||
parameterDefinitions.stream().filter(ActionDefinition.ParameterDefinition::isMandatory).collect(Collectors.toList())) &&
|
||||
MapUtils.isEmpty(params))
|
||||
{
|
||||
throw new IllegalArgumentException(String.format(PARAMS_SHOULD_NOT_BE_EMPTY, actionDefinition.getName()));
|
||||
throw new InvalidArgumentException(String.format(PARAMS_SHOULD_NOT_BE_EMPTY, actionDefinition.getName()));
|
||||
}
|
||||
}
|
||||
|
||||
private List<ActionDefinition.ParameterDefinition> getParameterDefinitions(ActionDefinition actionDefinition)
|
||||
{
|
||||
return actionDefinition.getParameterDefinitions() == null ? Collections.emptyList() : actionDefinition.getParameterDefinitions();
|
||||
}
|
||||
|
||||
private void validateParameterDefinitions(final ActionDefinition.ParameterDefinition parameterDefinition,
|
||||
final Map<String, Serializable> params)
|
||||
{
|
||||
final Serializable parameterValue = params.get(parameterDefinition.getName());
|
||||
if (parameterDefinition.isMandatory() && parameterValue == null)
|
||||
{
|
||||
throw new IllegalArgumentException(String.format(MISSING_PARAMETER, parameterDefinition.getName()));
|
||||
throw new InvalidArgumentException(String.format(MISSING_PARAMETER, parameterDefinition.getName()));
|
||||
}
|
||||
if (parameterDefinition.getParameterConstraintName() != null)
|
||||
{
|
||||
final ActionParameterConstraint actionConstraint =
|
||||
actions.getActionConstraint(parameterDefinition.getParameterConstraintName());
|
||||
if (parameterValue != null && actionConstraint.getConstraintValues().stream()
|
||||
.noneMatch(constraintData -> constraintData.getValue().equals(parameterValue.toString())))
|
||||
.noneMatch(constraintData -> constraintData.getValue().equals(Objects.toString(parameterValue, null))))
|
||||
{
|
||||
throw new IllegalArgumentException(String.format(INVALID_PARAMETER_VALUE, parameterDefinition.getName(), parameterValue,
|
||||
throw new InvalidArgumentException(String.format(INVALID_PARAMETER_VALUE, parameterDefinition.getName(), parameterValue,
|
||||
actionConstraint.getConstraintName()));
|
||||
}
|
||||
}
|
||||
@@ -123,11 +158,9 @@ public class ActionParameterDefinitionValidator implements ActionValidator
|
||||
|
||||
private void checkParameterShouldExist(final String parameterName, final ActionDefinition actionDefinition)
|
||||
{
|
||||
if (actionDefinition.getParameterDefinitions().stream().noneMatch(pd -> parameterName.equals(pd.getName())))
|
||||
if (getParameterDefinitions(actionDefinition).stream().noneMatch(pd -> parameterName.equals(pd.getName())))
|
||||
{
|
||||
throw new IllegalArgumentException(String.format(MUST_NOT_CONTAIN_PARAMETER, actionDefinition.getName(), parameterName));
|
||||
throw new InvalidArgumentException(String.format(MUST_NOT_CONTAIN_PARAMETER, actionDefinition.getName(), parameterName));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@@ -593,6 +593,12 @@
|
||||
<bean id="actionParameterConstraintsValidator" class="org.alfresco.rest.api.impl.validator.actions.ActionParameterDefinitionValidator">
|
||||
<constructor-arg name="actions" ref="Actions"/>
|
||||
</bean>
|
||||
<bean id="actionNodeParameterValidator" class="org.alfresco.rest.api.impl.validator.actions.ActionNodeParameterValidator">
|
||||
<constructor-arg name="actions" ref="Actions"/>
|
||||
<constructor-arg name="namespaceService" ref="NamespaceService"/>
|
||||
<constructor-arg name="nodes" ref="Nodes"/>
|
||||
<constructor-arg name="permissionService" ref="PermissionService"/>
|
||||
</bean>
|
||||
|
||||
<!-- action parameter validators end here-->
|
||||
|
||||
@@ -977,6 +983,7 @@
|
||||
<constructor-arg name="actionValidators">
|
||||
<list>
|
||||
<ref bean="actionParameterConstraintsValidator"/>
|
||||
<ref bean="actionNodeParameterValidator"/>
|
||||
</list>
|
||||
</constructor-arg>
|
||||
</bean>
|
||||
|
@@ -36,6 +36,8 @@ import org.alfresco.rest.api.impl.rules.NodeValidatorTest;
|
||||
import org.alfresco.rest.api.impl.rules.RuleLoaderTest;
|
||||
import org.alfresco.rest.api.impl.rules.RuleSetsImplTest;
|
||||
import org.alfresco.rest.api.impl.rules.RulesImplTest;
|
||||
import org.alfresco.rest.api.impl.validator.actions.ActionNodeParameterValidatorTest;
|
||||
import org.alfresco.rest.api.impl.validator.actions.ActionParameterDefinitionValidatorTest;
|
||||
import org.alfresco.rest.api.rules.NodeRuleSetsRelationTest;
|
||||
import org.alfresco.rest.api.rules.NodeRulesRelationTest;
|
||||
import org.alfresco.service.Experimental;
|
||||
@@ -53,6 +55,8 @@ import org.junit.runners.Suite;
|
||||
RuleLoaderTest.class,
|
||||
ActionParameterConverterTest.class,
|
||||
ActionPermissionValidatorTest.class,
|
||||
ActionParameterDefinitionValidatorTest.class,
|
||||
ActionNodeParameterValidatorTest.class,
|
||||
RestRuleSimpleConditionModelMapperTest.class,
|
||||
RestRuleCompositeConditionModelMapperTest.class,
|
||||
RestRuleActionModelMapperTest.class,
|
||||
|
@@ -76,7 +76,6 @@ public class RestRuleActionModelMapperTest
|
||||
@Before
|
||||
public void setUp() {
|
||||
objectUnderTest = new RestRuleActionModelMapper(parameterConverter, List.of(sampleValidatorMock));
|
||||
given(sampleValidatorMock.isEnabled()).willReturn(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@@ -44,6 +44,7 @@ import java.io.Serializable;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import org.alfresco.repo.action.executer.AddFeaturesActionExecuter;
|
||||
import org.alfresco.repo.action.executer.CheckInActionExecuter;
|
||||
import org.alfresco.repo.action.executer.CheckOutActionExecuter;
|
||||
@@ -56,6 +57,7 @@ import org.alfresco.repo.action.executer.SetPropertyValueActionExecuter;
|
||||
import org.alfresco.repo.action.executer.SimpleWorkflowActionExecuter;
|
||||
import org.alfresco.rest.api.Nodes;
|
||||
import org.alfresco.rest.framework.core.exceptions.EntityNotFoundException;
|
||||
import org.alfresco.rest.framework.core.exceptions.InvalidArgumentException;
|
||||
import org.alfresco.rest.framework.core.exceptions.NotFoundException;
|
||||
import org.alfresco.service.Experimental;
|
||||
import org.alfresco.service.cmr.action.ActionDefinition;
|
||||
@@ -67,6 +69,7 @@ import org.alfresco.service.cmr.repository.NodeRef;
|
||||
import org.alfresco.service.cmr.security.PermissionService;
|
||||
import org.alfresco.service.namespace.NamespaceService;
|
||||
import org.alfresco.service.namespace.QName;
|
||||
import org.apache.logging.log4j.util.Strings;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
@@ -609,6 +612,28 @@ public class ActionParameterConverterTest
|
||||
assertThatExceptionOfType(EntityNotFoundException.class).isThrownBy(() -> objectUnderTest.getConvertedParams(params, name));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNullParamValue()
|
||||
{
|
||||
final String name = CheckOutActionExecuter.NAME;
|
||||
final String destinationFolderKey = CheckOutActionExecuter.PARAM_DESTINATION_FOLDER;
|
||||
final String assocNameKey = CheckOutActionExecuter.PARAM_ASSOC_QNAME;
|
||||
final String assocTypeKey = CheckOutActionExecuter.PARAM_ASSOC_TYPE_QNAME;
|
||||
final Map<String, Serializable> params =
|
||||
Map.of(destinationFolderKey, Strings.EMPTY, assocNameKey, Strings.EMPTY, assocTypeKey, Strings.EMPTY);
|
||||
|
||||
given(actionService.getActionDefinition(name)).willReturn(actionDefinition);
|
||||
|
||||
//when
|
||||
assertThrows(InvalidArgumentException.class, () ->objectUnderTest.getConvertedParams(params, name));
|
||||
|
||||
then(actionService).should().getActionDefinition(name);
|
||||
then(actionService).shouldHaveNoMoreInteractions();
|
||||
then(actionDefinition).shouldHaveNoInteractions();
|
||||
then(dictionaryService).shouldHaveNoInteractions();
|
||||
then(namespaceService).shouldHaveNoInteractions();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInvalidActionDefinitionConversion() {
|
||||
final String invalidName = "dummy-definition";
|
||||
|
@@ -0,0 +1,366 @@
|
||||
/*
|
||||
* #%L
|
||||
* Alfresco Remote API
|
||||
* %%
|
||||
* Copyright (C) 2005 - 2022 Alfresco Software Limited
|
||||
* %%
|
||||
* This file is part of the Alfresco software.
|
||||
* If the software was purchased under a paid Alfresco license, the terms of
|
||||
* the paid license agreement will prevail. Otherwise, the software is
|
||||
* provided under the following open source license terms:
|
||||
*
|
||||
* Alfresco is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Alfresco is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
|
||||
* #L%
|
||||
*/
|
||||
|
||||
package org.alfresco.rest.api.impl.validator.actions;
|
||||
|
||||
import static org.alfresco.model.ContentModel.TYPE_CATEGORY;
|
||||
import static org.alfresco.model.ContentModel.TYPE_FOLDER;
|
||||
import static org.alfresco.rest.api.impl.validator.actions.ActionNodeParameterValidator.NOT_A_CATEGORY;
|
||||
import static org.alfresco.rest.api.impl.validator.actions.ActionNodeParameterValidator.NOT_A_FOLDER;
|
||||
import static org.alfresco.rest.api.impl.validator.actions.ActionNodeParameterValidator.NO_PROPER_PERMISSIONS_FOR_NODE;
|
||||
import static org.alfresco.rest.api.impl.validator.actions.ActionNodeParameterValidator.REQUIRE_READ_PERMISSION_PARAMS;
|
||||
import static org.alfresco.service.cmr.dictionary.DataTypeDefinition.CATEGORY;
|
||||
import static org.alfresco.service.cmr.dictionary.DataTypeDefinition.NODE_REF;
|
||||
import static org.alfresco.service.cmr.dictionary.DataTypeDefinition.TEXT;
|
||||
import static org.alfresco.service.cmr.repository.StoreRef.STORE_REF_WORKSPACE_SPACESSTORE;
|
||||
import static org.alfresco.service.namespace.NamespaceService.DEFAULT_PREFIX;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.BDDMockito.then;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.alfresco.repo.action.executer.CheckOutActionExecuter;
|
||||
import org.alfresco.repo.action.executer.CopyActionExecuter;
|
||||
import org.alfresco.repo.action.executer.ImageTransformActionExecuter;
|
||||
import org.alfresco.repo.action.executer.ImporterActionExecuter;
|
||||
import org.alfresco.repo.action.executer.LinkCategoryActionExecuter;
|
||||
import org.alfresco.repo.action.executer.MoveActionExecuter;
|
||||
import org.alfresco.repo.action.executer.SimpleWorkflowActionExecuter;
|
||||
import org.alfresco.repo.action.executer.TransformActionExecuter;
|
||||
import org.alfresco.rest.api.Actions;
|
||||
import org.alfresco.rest.api.Nodes;
|
||||
import org.alfresco.rest.api.model.ActionDefinition;
|
||||
import org.alfresco.rest.api.model.rules.Action;
|
||||
import org.alfresco.rest.framework.core.exceptions.EntityNotFoundException;
|
||||
import org.alfresco.rest.framework.core.exceptions.InvalidArgumentException;
|
||||
import org.alfresco.rest.framework.core.exceptions.PermissionDeniedException;
|
||||
import org.alfresco.service.cmr.repository.NodeRef;
|
||||
import org.alfresco.service.cmr.security.AccessStatus;
|
||||
import org.alfresco.service.cmr.security.PermissionService;
|
||||
import org.alfresco.service.namespace.NamespaceService;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ActionNodeParameterValidatorTest
|
||||
{
|
||||
private static final String READ_RIGHTS_REQUIRED_DEFINITION_ID = LinkCategoryActionExecuter.NAME;
|
||||
private static final String CATEGORY_NODE_REF_PARAM = REQUIRE_READ_PERMISSION_PARAMS.get(READ_RIGHTS_REQUIRED_DEFINITION_ID).get(0);
|
||||
private static final String DESTINATION_FOLDER_PARAM = "destination-folder";
|
||||
private static final String NODE_ID = "node-id";
|
||||
private static final String COPY_ACTION = CopyActionExecuter.NAME;
|
||||
|
||||
@Mock
|
||||
private Actions actionsMock;
|
||||
@Mock
|
||||
private NamespaceService namespaceServiceMock;
|
||||
@Mock
|
||||
private Nodes nodesMock;
|
||||
@Mock
|
||||
private PermissionService permissionServiceMock;
|
||||
|
||||
@InjectMocks
|
||||
private ActionNodeParameterValidator objectUnderTest;
|
||||
|
||||
@Test
|
||||
public void testProperPermissionsForReadRights()
|
||||
{
|
||||
final Action action = new Action();
|
||||
action.setActionDefinitionId(READ_RIGHTS_REQUIRED_DEFINITION_ID);
|
||||
action.setParams(Map.of(CATEGORY_NODE_REF_PARAM, NODE_ID));
|
||||
ActionDefinition.ParameterDefinition parameterDef =
|
||||
new ActionDefinition.ParameterDefinition(CATEGORY_NODE_REF_PARAM, NODE_REF.toPrefixString(), false, true, null, null);
|
||||
final ActionDefinition actionDefinition =
|
||||
new ActionDefinition(COPY_ACTION, COPY_ACTION, null, null, null, false, false,
|
||||
List.of(parameterDef));
|
||||
given(actionsMock.getRuleActionDefinitionById(READ_RIGHTS_REQUIRED_DEFINITION_ID)).willReturn(actionDefinition);
|
||||
given(namespaceServiceMock.getPrefixes(NODE_REF.getNamespaceURI())).willReturn(List.of(DEFAULT_PREFIX));
|
||||
final NodeRef nodeRef = new NodeRef(STORE_REF_WORKSPACE_SPACESSTORE, NODE_ID);
|
||||
given(nodesMock.validateNode(NODE_ID)).willReturn(nodeRef);
|
||||
given(permissionServiceMock.hasReadPermission(nodeRef)).willReturn(AccessStatus.ALLOWED);
|
||||
given(nodesMock.nodeMatches(nodeRef, Set.of(TYPE_CATEGORY), Collections.emptySet())).willReturn(true);
|
||||
|
||||
//when
|
||||
objectUnderTest.validate(action);
|
||||
|
||||
then(actionsMock).should().getRuleActionDefinitionById(READ_RIGHTS_REQUIRED_DEFINITION_ID);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
then(namespaceServiceMock).should().getPrefixes(NODE_REF.getNamespaceURI());
|
||||
then(namespaceServiceMock).shouldHaveNoMoreInteractions();
|
||||
then(nodesMock).should().validateNode(NODE_ID);
|
||||
then(nodesMock).should().nodeMatches(nodeRef, Set.of(TYPE_CATEGORY), Collections.emptySet());
|
||||
then(nodesMock).shouldHaveNoMoreInteractions();
|
||||
then(permissionServiceMock).should().hasReadPermission(nodeRef);
|
||||
then(permissionServiceMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEnoughPermissionsForReadRights()
|
||||
{
|
||||
final Action action = new Action();
|
||||
action.setActionDefinitionId(COPY_ACTION);
|
||||
action.setParams(Map.of(DESTINATION_FOLDER_PARAM, NODE_ID));
|
||||
ActionDefinition.ParameterDefinition parameterDef =
|
||||
new ActionDefinition.ParameterDefinition(DESTINATION_FOLDER_PARAM, NODE_REF.toPrefixString(), false, true, null, null);
|
||||
final ActionDefinition actionDefinition =
|
||||
new ActionDefinition(COPY_ACTION, COPY_ACTION, null, null, null, false, false,
|
||||
List.of(parameterDef));
|
||||
given(actionsMock.getRuleActionDefinitionById(COPY_ACTION)).willReturn(actionDefinition);
|
||||
given(namespaceServiceMock.getPrefixes(NODE_REF.getNamespaceURI())).willReturn(List.of(DEFAULT_PREFIX));
|
||||
final NodeRef nodeRef = new NodeRef(STORE_REF_WORKSPACE_SPACESSTORE, NODE_ID);
|
||||
given(nodesMock.validateNode(NODE_ID)).willReturn(nodeRef);
|
||||
given(permissionServiceMock.hasReadPermission(nodeRef)).willReturn(AccessStatus.DENIED);
|
||||
|
||||
//when
|
||||
assertThatExceptionOfType(EntityNotFoundException.class).isThrownBy(() -> objectUnderTest.validate(action));
|
||||
|
||||
then(actionsMock).should().getRuleActionDefinitionById(COPY_ACTION);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
then(namespaceServiceMock).should().getPrefixes(NODE_REF.getNamespaceURI());
|
||||
then(namespaceServiceMock).shouldHaveNoMoreInteractions();
|
||||
then(nodesMock).should().validateNode(NODE_ID);
|
||||
then(nodesMock).shouldHaveNoMoreInteractions();
|
||||
then(permissionServiceMock).should().hasReadPermission(nodeRef);
|
||||
then(permissionServiceMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidateForNodeNotFound()
|
||||
{
|
||||
final Action action = new Action();
|
||||
action.setActionDefinitionId(COPY_ACTION);
|
||||
action.setParams(Map.of(DESTINATION_FOLDER_PARAM, NODE_ID));
|
||||
ActionDefinition.ParameterDefinition parameterDef =
|
||||
new ActionDefinition.ParameterDefinition(DESTINATION_FOLDER_PARAM, NODE_REF.toPrefixString(), false, true, null, null);
|
||||
final ActionDefinition actionDefinition =
|
||||
new ActionDefinition(COPY_ACTION, COPY_ACTION, null, null, null, false, false,
|
||||
List.of(parameterDef));
|
||||
given(actionsMock.getRuleActionDefinitionById(COPY_ACTION)).willReturn(actionDefinition);
|
||||
given(namespaceServiceMock.getPrefixes(NODE_REF.getNamespaceURI())).willReturn(List.of(DEFAULT_PREFIX));
|
||||
given(nodesMock.validateNode(NODE_ID)).willThrow(EntityNotFoundException.class);
|
||||
|
||||
//when
|
||||
assertThatExceptionOfType(EntityNotFoundException.class).isThrownBy(() -> objectUnderTest.validate(action));
|
||||
|
||||
then(actionsMock).should().getRuleActionDefinitionById(COPY_ACTION);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
then(namespaceServiceMock).should().getPrefixes(NODE_REF.getNamespaceURI());
|
||||
then(namespaceServiceMock).shouldHaveNoMoreInteractions();
|
||||
then(nodesMock).should().validateNode(NODE_ID);
|
||||
then(nodesMock).shouldHaveNoMoreInteractions();
|
||||
then(permissionServiceMock).shouldHaveNoInteractions();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProperPermissionsForWriteRights()
|
||||
{
|
||||
final Action action = new Action();
|
||||
action.setActionDefinitionId(COPY_ACTION);
|
||||
action.setParams(Map.of(DESTINATION_FOLDER_PARAM, NODE_ID));
|
||||
ActionDefinition.ParameterDefinition parameterDef =
|
||||
new ActionDefinition.ParameterDefinition(DESTINATION_FOLDER_PARAM, NODE_REF.toPrefixString(), false, true, null, null);
|
||||
final ActionDefinition actionDefinition =
|
||||
new ActionDefinition(COPY_ACTION, COPY_ACTION, null, null, null, false, false,
|
||||
List.of(parameterDef));
|
||||
given(actionsMock.getRuleActionDefinitionById(COPY_ACTION)).willReturn(actionDefinition);
|
||||
given(namespaceServiceMock.getPrefixes(NODE_REF.getNamespaceURI())).willReturn(List.of(DEFAULT_PREFIX));
|
||||
final NodeRef nodeRef = new NodeRef(STORE_REF_WORKSPACE_SPACESSTORE, NODE_ID);
|
||||
given(nodesMock.validateNode(NODE_ID)).willReturn(nodeRef);
|
||||
given(permissionServiceMock.hasReadPermission(nodeRef)).willReturn(AccessStatus.ALLOWED);
|
||||
given(permissionServiceMock.hasPermission(nodeRef, PermissionService.WRITE)).willReturn(AccessStatus.ALLOWED);
|
||||
given(nodesMock.nodeMatches(nodeRef, Set.of(TYPE_FOLDER), Collections.emptySet())).willReturn(true);
|
||||
|
||||
//when
|
||||
objectUnderTest.validate(action);
|
||||
|
||||
then(actionsMock).should().getRuleActionDefinitionById(COPY_ACTION);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
then(namespaceServiceMock).should().getPrefixes(NODE_REF.getNamespaceURI());
|
||||
then(namespaceServiceMock).shouldHaveNoMoreInteractions();
|
||||
then(nodesMock).should().validateNode(NODE_ID);
|
||||
then(nodesMock).should().nodeMatches(nodeRef, Set.of(TYPE_FOLDER), Collections.emptySet());
|
||||
then(nodesMock).shouldHaveNoMoreInteractions();
|
||||
then(permissionServiceMock).should().hasReadPermission(nodeRef);
|
||||
then(permissionServiceMock).should().hasPermission(nodeRef, PermissionService.WRITE);
|
||||
then(permissionServiceMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEnoughPermissionsForWriteRights()
|
||||
{
|
||||
final Action action = new Action();
|
||||
action.setActionDefinitionId(COPY_ACTION);
|
||||
action.setParams(Map.of(DESTINATION_FOLDER_PARAM, NODE_ID));
|
||||
ActionDefinition.ParameterDefinition parameterDef =
|
||||
new ActionDefinition.ParameterDefinition(DESTINATION_FOLDER_PARAM, NODE_REF.toPrefixString(), false, true, null, null);
|
||||
final ActionDefinition actionDefinition =
|
||||
new ActionDefinition(COPY_ACTION, COPY_ACTION, null, null, null, false, false,
|
||||
List.of(parameterDef));
|
||||
given(actionsMock.getRuleActionDefinitionById(COPY_ACTION)).willReturn(actionDefinition);
|
||||
given(namespaceServiceMock.getPrefixes(NODE_REF.getNamespaceURI())).willReturn(List.of(DEFAULT_PREFIX));
|
||||
final NodeRef nodeRef = new NodeRef(STORE_REF_WORKSPACE_SPACESSTORE, NODE_ID);
|
||||
given(nodesMock.validateNode(NODE_ID)).willReturn(nodeRef);
|
||||
given(permissionServiceMock.hasReadPermission(nodeRef)).willReturn(AccessStatus.ALLOWED);
|
||||
given(permissionServiceMock.hasPermission(nodeRef, PermissionService.WRITE)).willReturn(AccessStatus.DENIED);
|
||||
|
||||
//when
|
||||
assertThatExceptionOfType(PermissionDeniedException.class).isThrownBy(() -> objectUnderTest.validate(action))
|
||||
.withMessageContaining(NO_PROPER_PERMISSIONS_FOR_NODE + NODE_ID);
|
||||
|
||||
then(actionsMock).should().getRuleActionDefinitionById(COPY_ACTION);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
then(namespaceServiceMock).should().getPrefixes(NODE_REF.getNamespaceURI());
|
||||
then(namespaceServiceMock).shouldHaveNoMoreInteractions();
|
||||
then(nodesMock).should().validateNode(NODE_ID);
|
||||
then(nodesMock).shouldHaveNoMoreInteractions();
|
||||
then(permissionServiceMock).should().hasReadPermission(nodeRef);
|
||||
then(permissionServiceMock).should().hasPermission(nodeRef, PermissionService.WRITE);
|
||||
then(permissionServiceMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoValidationExecutedForNonNodeRefParam()
|
||||
{
|
||||
final Action action = new Action();
|
||||
action.setActionDefinitionId(COPY_ACTION);
|
||||
final String dummyParam = "dummyParam";
|
||||
action.setParams(Map.of(dummyParam, "dummyValue"));
|
||||
ActionDefinition.ParameterDefinition parameterDef =
|
||||
new ActionDefinition.ParameterDefinition(dummyParam, TEXT.toPrefixString(), false, true, null, null);
|
||||
final ActionDefinition actionDefinition =
|
||||
new ActionDefinition(COPY_ACTION, COPY_ACTION, null, null, null, false, false,
|
||||
List.of(parameterDef));
|
||||
given(actionsMock.getRuleActionDefinitionById(COPY_ACTION)).willReturn(actionDefinition);
|
||||
given(namespaceServiceMock.getPrefixes(NODE_REF.getNamespaceURI())).willReturn(List.of(DEFAULT_PREFIX));
|
||||
|
||||
//when
|
||||
objectUnderTest.validate(action);
|
||||
|
||||
then(actionsMock).should().getRuleActionDefinitionById(COPY_ACTION);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
then(namespaceServiceMock).should().getPrefixes(NODE_REF.getNamespaceURI());
|
||||
then(namespaceServiceMock).shouldHaveNoMoreInteractions();
|
||||
then(nodesMock).shouldHaveNoInteractions();
|
||||
then(permissionServiceMock).shouldHaveNoInteractions();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrongTypeOfNodeWhenFolderExpected()
|
||||
{
|
||||
final Action action = new Action();
|
||||
action.setActionDefinitionId(COPY_ACTION);
|
||||
action.setParams(Map.of(DESTINATION_FOLDER_PARAM, NODE_ID));
|
||||
ActionDefinition.ParameterDefinition parameterDef =
|
||||
new ActionDefinition.ParameterDefinition(DESTINATION_FOLDER_PARAM, NODE_REF.toPrefixString(), false, true, null, null);
|
||||
final ActionDefinition actionDefinition =
|
||||
new ActionDefinition(COPY_ACTION, COPY_ACTION, null, null, null, false, false,
|
||||
List.of(parameterDef));
|
||||
given(actionsMock.getRuleActionDefinitionById(COPY_ACTION)).willReturn(actionDefinition);
|
||||
given(namespaceServiceMock.getPrefixes(NODE_REF.getNamespaceURI())).willReturn(List.of(DEFAULT_PREFIX));
|
||||
final NodeRef nodeRef = new NodeRef(STORE_REF_WORKSPACE_SPACESSTORE, NODE_ID);
|
||||
given(nodesMock.validateNode(NODE_ID)).willReturn(nodeRef);
|
||||
given(permissionServiceMock.hasReadPermission(nodeRef)).willReturn(AccessStatus.ALLOWED);
|
||||
given(permissionServiceMock.hasPermission(nodeRef, PermissionService.WRITE)).willReturn(AccessStatus.ALLOWED);
|
||||
given(nodesMock.nodeMatches(nodeRef, Set.of(TYPE_FOLDER), Collections.emptySet())).willReturn(false);
|
||||
|
||||
//when
|
||||
assertThatExceptionOfType(InvalidArgumentException.class).isThrownBy(() -> objectUnderTest.validate(action))
|
||||
.withMessageContaining(NOT_A_FOLDER + NODE_ID);
|
||||
|
||||
then(actionsMock).should().getRuleActionDefinitionById(COPY_ACTION);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
then(namespaceServiceMock).should().getPrefixes(NODE_REF.getNamespaceURI());
|
||||
then(namespaceServiceMock).shouldHaveNoMoreInteractions();
|
||||
then(nodesMock).should().validateNode(NODE_ID);
|
||||
then(nodesMock).should().nodeMatches(nodeRef, Set.of(TYPE_FOLDER), Collections.emptySet());
|
||||
then(nodesMock).shouldHaveNoMoreInteractions();
|
||||
then(permissionServiceMock).should().hasReadPermission(nodeRef);
|
||||
then(permissionServiceMock).should().hasPermission(nodeRef, PermissionService.WRITE);
|
||||
then(permissionServiceMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrongTypeOfNodeWhenCategoryExpected()
|
||||
{
|
||||
final Action action = new Action();
|
||||
action.setActionDefinitionId(READ_RIGHTS_REQUIRED_DEFINITION_ID);
|
||||
action.setParams(Map.of(CATEGORY_NODE_REF_PARAM, NODE_ID));
|
||||
ActionDefinition.ParameterDefinition parameterDef =
|
||||
new ActionDefinition.ParameterDefinition(CATEGORY_NODE_REF_PARAM, NODE_REF.toPrefixString(), false, true, null, null);
|
||||
final ActionDefinition actionDefinition =
|
||||
new ActionDefinition(READ_RIGHTS_REQUIRED_DEFINITION_ID, READ_RIGHTS_REQUIRED_DEFINITION_ID, null, null, null, false, false,
|
||||
List.of(parameterDef));
|
||||
given(actionsMock.getRuleActionDefinitionById(READ_RIGHTS_REQUIRED_DEFINITION_ID)).willReturn(actionDefinition);
|
||||
given(namespaceServiceMock.getPrefixes(NODE_REF.getNamespaceURI())).willReturn(List.of(DEFAULT_PREFIX));
|
||||
final NodeRef nodeRef = new NodeRef(STORE_REF_WORKSPACE_SPACESSTORE, NODE_ID);
|
||||
given(nodesMock.validateNode(NODE_ID)).willReturn(nodeRef);
|
||||
given(permissionServiceMock.hasReadPermission(nodeRef)).willReturn(AccessStatus.ALLOWED);
|
||||
given(nodesMock.nodeMatches(nodeRef, Set.of(TYPE_CATEGORY), Collections.emptySet())).willReturn(false);
|
||||
|
||||
//when
|
||||
assertThatExceptionOfType(InvalidArgumentException.class).isThrownBy(() -> objectUnderTest.validate(action))
|
||||
.withMessageContaining(NOT_A_CATEGORY + NODE_ID);
|
||||
|
||||
then(actionsMock).should().getRuleActionDefinitionById(READ_RIGHTS_REQUIRED_DEFINITION_ID);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
then(namespaceServiceMock).should().getPrefixes(NODE_REF.getNamespaceURI());
|
||||
then(namespaceServiceMock).shouldHaveNoMoreInteractions();
|
||||
then(nodesMock).should().validateNode(NODE_ID);
|
||||
then(nodesMock).should().nodeMatches(nodeRef, Set.of(TYPE_CATEGORY), Collections.emptySet());
|
||||
then(nodesMock).shouldHaveNoMoreInteractions();
|
||||
then(permissionServiceMock).should().hasReadPermission(nodeRef);
|
||||
then(permissionServiceMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetDefinitionIds()
|
||||
{
|
||||
final List<String> expectedIds =
|
||||
List.of(CopyActionExecuter.NAME, MoveActionExecuter.NAME, CheckOutActionExecuter.NAME, ImporterActionExecuter.NAME,
|
||||
LinkCategoryActionExecuter.NAME, SimpleWorkflowActionExecuter.NAME, TransformActionExecuter.NAME,
|
||||
ImageTransformActionExecuter.NAME);
|
||||
final List<String> actualIds = objectUnderTest.getActionDefinitionIds();
|
||||
|
||||
assertEquals(expectedIds, actualIds);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHasProperPriority()
|
||||
{
|
||||
final int expectedPriority = Integer.MIN_VALUE + 1;
|
||||
final int actualPriority = objectUnderTest.getPriority();
|
||||
|
||||
assertEquals(expectedPriority, actualPriority);
|
||||
}
|
||||
}
|
@@ -26,12 +26,16 @@
|
||||
|
||||
package org.alfresco.rest.api.impl.validator.actions;
|
||||
|
||||
import static org.alfresco.rest.api.impl.validator.actions.ActionParameterDefinitionValidator.EMPTY_ACTION_DEFINITION;
|
||||
import static org.alfresco.rest.api.impl.validator.actions.ActionParameterDefinitionValidator.INVALID_ACTION_DEFINITION;
|
||||
import static org.alfresco.rest.api.impl.validator.actions.ActionParameterDefinitionValidator.MISSING_PARAMETER;
|
||||
import static org.alfresco.rest.api.impl.validator.actions.ActionParameterDefinitionValidator.MUST_NOT_CONTAIN_PARAMETER;
|
||||
import static org.alfresco.rest.api.impl.validator.actions.ActionParameterDefinitionValidator.PARAMS_SHOULD_NOT_BE_EMPTY;
|
||||
import static org.alfresco.service.cmr.dictionary.DataTypeDefinition.BOOLEAN;
|
||||
import static org.alfresco.service.cmr.dictionary.DataTypeDefinition.TEXT;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.BDDMockito.then;
|
||||
|
||||
import java.util.Collections;
|
||||
@@ -42,11 +46,12 @@ import java.util.Map;
|
||||
import org.alfresco.rest.api.Actions;
|
||||
import org.alfresco.rest.api.model.ActionDefinition;
|
||||
import org.alfresco.rest.api.model.rules.Action;
|
||||
import org.alfresco.rest.framework.core.exceptions.InvalidArgumentException;
|
||||
import org.alfresco.rest.framework.core.exceptions.NotFoundException;
|
||||
import org.alfresco.service.Experimental;
|
||||
import org.alfresco.service.namespace.QName;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.BDDMockito;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
@@ -74,12 +79,12 @@ public class ActionParameterDefinitionValidatorTest
|
||||
final List<ActionDefinition.ParameterDefinition> parameterDefinitions =
|
||||
List.of(createParameterDefinition(MANDATORY_PARAM_KEY, TEXT, true, null));
|
||||
final ActionDefinition actionDefinition = createActionDefinition(actionDefinitionId, parameterDefinitions);
|
||||
BDDMockito.given(actionsMock.getActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
given(actionsMock.getRuleActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
|
||||
//when
|
||||
objectUnderTest.validate(action);
|
||||
|
||||
then(actionsMock).should().getActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).should().getRuleActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@@ -90,17 +95,34 @@ public class ActionParameterDefinitionValidatorTest
|
||||
final String actionDefinitionId = "properActionDefinition";
|
||||
action.setActionDefinitionId(actionDefinitionId);
|
||||
final ActionDefinition actionDefinition = createActionDefinition(actionDefinitionId, null);
|
||||
BDDMockito.given(actionsMock.getActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
given(actionsMock.getRuleActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
|
||||
//when
|
||||
objectUnderTest.validate(action);
|
||||
|
||||
then(actionsMock).should().getActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).should().getRuleActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidationPassesWhenNoMandatoryParameters()
|
||||
public void testValidationPassesWhenNoMandatoryParametersNeeded()
|
||||
{
|
||||
final Action action = new Action();
|
||||
final String actionDefinitionId = "properActionDefinition";
|
||||
action.setActionDefinitionId(actionDefinitionId);
|
||||
final ActionDefinition actionDefinition =
|
||||
createActionDefinition(actionDefinitionId, List.of(createParameterDefinition(NON_MANDATORY_PARAM_KEY, TEXT, false, null)));
|
||||
given(actionsMock.getRuleActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
|
||||
//when
|
||||
objectUnderTest.validate(action);
|
||||
|
||||
then(actionsMock).should().getRuleActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidationPassesWhenOptionalParametersNotProvided()
|
||||
{
|
||||
final Action action = new Action();
|
||||
final String actionDefinitionId = "properActionDefinition";
|
||||
@@ -110,12 +132,12 @@ public class ActionParameterDefinitionValidatorTest
|
||||
List.of(createParameterDefinition(MANDATORY_PARAM_KEY, TEXT, true, null),
|
||||
createParameterDefinition(NON_MANDATORY_PARAM_KEY, BOOLEAN, false, null));
|
||||
final ActionDefinition actionDefinition = createActionDefinition(actionDefinitionId, parameterDefinitions);
|
||||
BDDMockito.given(actionsMock.getActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
given(actionsMock.getRuleActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
|
||||
//when
|
||||
objectUnderTest.validate(action);
|
||||
|
||||
then(actionsMock).should().getActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).should().getRuleActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@@ -129,13 +151,13 @@ public class ActionParameterDefinitionValidatorTest
|
||||
final List<ActionDefinition.ParameterDefinition> parameterDefinitions =
|
||||
List.of(createParameterDefinition(MANDATORY_PARAM_KEY, TEXT, true, null));
|
||||
final ActionDefinition actionDefinition = createActionDefinition(actionDefinitionId, parameterDefinitions);
|
||||
BDDMockito.given(actionsMock.getActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
given(actionsMock.getRuleActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
|
||||
//when
|
||||
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> objectUnderTest.validate(action))
|
||||
assertThatExceptionOfType(InvalidArgumentException.class).isThrownBy(() -> objectUnderTest.validate(action))
|
||||
.withMessageContaining(String.format(MUST_NOT_CONTAIN_PARAMETER, actionDefinitionId, NON_MANDATORY_PARAM_KEY));
|
||||
|
||||
then(actionsMock).should().getActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).should().getRuleActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@@ -148,13 +170,13 @@ public class ActionParameterDefinitionValidatorTest
|
||||
final List<ActionDefinition.ParameterDefinition> parameterDefinitions =
|
||||
List.of(createParameterDefinition(MANDATORY_PARAM_KEY, TEXT, true, null));
|
||||
final ActionDefinition actionDefinition = createActionDefinition(actionDefinitionId, parameterDefinitions);
|
||||
BDDMockito.given(actionsMock.getActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
given(actionsMock.getRuleActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
|
||||
//when
|
||||
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> objectUnderTest.validate(action))
|
||||
assertThatExceptionOfType(InvalidArgumentException.class).isThrownBy(() -> objectUnderTest.validate(action))
|
||||
.withMessageContaining(String.format(PARAMS_SHOULD_NOT_BE_EMPTY, actionDefinitionId));
|
||||
|
||||
then(actionsMock).should().getActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).should().getRuleActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@@ -170,13 +192,13 @@ public class ActionParameterDefinitionValidatorTest
|
||||
final List<ActionDefinition.ParameterDefinition> parameterDefinitions =
|
||||
List.of(createParameterDefinition(MANDATORY_PARAM_KEY, TEXT, true, null));
|
||||
final ActionDefinition actionDefinition = createActionDefinition(actionDefinitionId, parameterDefinitions);
|
||||
BDDMockito.given(actionsMock.getActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
given(actionsMock.getRuleActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
|
||||
//when
|
||||
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> objectUnderTest.validate(action))
|
||||
assertThatExceptionOfType(InvalidArgumentException.class).isThrownBy(() -> objectUnderTest.validate(action))
|
||||
.withMessageContaining(String.format(MISSING_PARAMETER, MANDATORY_PARAM_KEY));
|
||||
|
||||
then(actionsMock).should().getActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).should().getRuleActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@@ -191,16 +213,56 @@ public class ActionParameterDefinitionValidatorTest
|
||||
List.of(createParameterDefinition(MANDATORY_PARAM_KEY, TEXT, true, null),
|
||||
createParameterDefinition(NON_MANDATORY_PARAM_KEY, BOOLEAN, false, null));
|
||||
final ActionDefinition actionDefinition = createActionDefinition(actionDefinitionId, parameterDefinitions);
|
||||
BDDMockito.given(actionsMock.getActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
given(actionsMock.getRuleActionDefinitionById(actionDefinitionId)).willReturn(actionDefinition);
|
||||
|
||||
//when
|
||||
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> objectUnderTest.validate(action))
|
||||
assertThatExceptionOfType(InvalidArgumentException.class).isThrownBy(() -> objectUnderTest.validate(action))
|
||||
.withMessageContaining(String.format(MISSING_PARAMETER, MANDATORY_PARAM_KEY));
|
||||
|
||||
then(actionsMock).should().getActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).should().getRuleActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidationFailsWhenActionWithNullActionDefinition()
|
||||
{
|
||||
final Action action = new Action();
|
||||
action.setActionDefinitionId(null);
|
||||
action.setParams(Map.of(MANDATORY_PARAM_KEY, "paramValue"));
|
||||
|
||||
//when
|
||||
assertThatExceptionOfType(InvalidArgumentException.class).isThrownBy(() -> objectUnderTest.validate(action))
|
||||
.withMessageContaining(EMPTY_ACTION_DEFINITION);
|
||||
|
||||
then(actionsMock).shouldHaveNoInteractions();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidationFailsWhenNotApplicableActionDefinition()
|
||||
{
|
||||
final Action action = new Action();
|
||||
final String actionDefinitionId = "notApplicableActionDefinition";
|
||||
action.setActionDefinitionId(actionDefinitionId);
|
||||
action.setParams(Map.of(MANDATORY_PARAM_KEY, "paramValue"));
|
||||
given(actionsMock.getRuleActionDefinitionById(actionDefinitionId)).willThrow(NotFoundException.class);
|
||||
|
||||
//when
|
||||
assertThatExceptionOfType(InvalidArgumentException.class).isThrownBy(() -> objectUnderTest.validate(action))
|
||||
.withMessageContaining(String.format(INVALID_ACTION_DEFINITION, actionDefinitionId));
|
||||
|
||||
then(actionsMock).should().getRuleActionDefinitionById(actionDefinitionId);
|
||||
then(actionsMock).shouldHaveNoMoreInteractions();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHasProperPriority()
|
||||
{
|
||||
final int expectedPriority = Integer.MIN_VALUE;
|
||||
final int actualPriority = objectUnderTest.getPriority();
|
||||
|
||||
assertEquals(expectedPriority, actualPriority);
|
||||
}
|
||||
|
||||
private ActionDefinition createActionDefinition(final String actionDefinitionId,
|
||||
List<ActionDefinition.ParameterDefinition> parameterDefinitions)
|
||||
{
|
||||
|
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.alfresco</groupId>
|
||||
<artifactId>alfresco-community-repo</artifactId>
|
||||
<version>17.169</version>
|
||||
<version>20.3</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@@ -1,28 +1,28 @@
|
||||
/*
|
||||
* #%L
|
||||
* Alfresco Repository
|
||||
* %%
|
||||
* Copyright (C) 2005 - 2016 Alfresco Software Limited
|
||||
* %%
|
||||
* This file is part of the Alfresco software.
|
||||
* If the software was purchased under a paid Alfresco license, the terms of
|
||||
* the paid license agreement will prevail. Otherwise, the software is
|
||||
* provided under the following open source license terms:
|
||||
*
|
||||
* Alfresco is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Alfresco is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
|
||||
* #L%
|
||||
*/
|
||||
/*
|
||||
* #%L
|
||||
* Alfresco Repository
|
||||
* %%
|
||||
* Copyright (C) 2005 - 2016 Alfresco Software Limited
|
||||
* %%
|
||||
* This file is part of the Alfresco software.
|
||||
* If the software was purchased under a paid Alfresco license, the terms of
|
||||
* the paid license agreement will prevail. Otherwise, the software is
|
||||
* provided under the following open source license terms:
|
||||
*
|
||||
* Alfresco is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Alfresco is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
|
||||
* #L%
|
||||
*/
|
||||
package org.alfresco.repo.download;
|
||||
|
||||
import java.io.File;
|
||||
@@ -36,6 +36,7 @@ import org.alfresco.model.ForumModel;
|
||||
import org.alfresco.model.RenditionModel;
|
||||
import org.alfresco.repo.action.executer.ActionExecuter;
|
||||
import org.alfresco.repo.action.executer.ActionExecuterAbstractBase;
|
||||
import org.alfresco.repo.rule.RuleModel;
|
||||
import org.alfresco.repo.security.authentication.AuthenticationUtil;
|
||||
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
|
||||
import org.alfresco.repo.transaction.RetryingTransactionHelper;
|
||||
@@ -203,7 +204,7 @@ public class CreateDownloadArchiveAction extends ActionExecuterAbstractBase
|
||||
crawlerParameters.setExportFrom(exportFrom);
|
||||
|
||||
crawlerParameters.setCrawlSelf(true);
|
||||
crawlerParameters.setExcludeChildAssocs(new QName[] {RenditionModel.ASSOC_RENDITION, ForumModel.ASSOC_DISCUSSION});
|
||||
crawlerParameters.setExcludeChildAssocs(new QName[] {RenditionModel.ASSOC_RENDITION, ForumModel.ASSOC_DISCUSSION, RuleModel.ASSOC_RULE_FOLDER });
|
||||
crawlerParameters.setExcludeAspects(new QName[] {ContentModel.ASPECT_WORKING_COPY});
|
||||
|
||||
// Get an estimate of the size for statuses
|
||||
|
@@ -3,7 +3,7 @@
|
||||
repository.name=Main Repository
|
||||
|
||||
# Schema number
|
||||
version.schema=17000
|
||||
version.schema=18000
|
||||
|
||||
# Directory configuration
|
||||
|
||||
|
@@ -77,6 +77,7 @@ import org.junit.runners.Suite;
|
||||
org.alfresco.repo.rule.RuleServiceImplUnitTest.class,
|
||||
org.alfresco.repo.service.StoreRedirectorProxyFactoryTest.class,
|
||||
org.alfresco.repo.site.RoleComparatorImplTest.class,
|
||||
org.alfresco.repo.template.UnsafeMethodsTest.class,
|
||||
org.alfresco.repo.tenant.MultiTAdminServiceImplTest.class,
|
||||
org.alfresco.repo.thumbnail.ThumbnailServiceImplParameterTest.class,
|
||||
org.alfresco.repo.transfer.ContentChunkerImplTest.class,
|
||||
|
@@ -27,6 +27,7 @@ package org.alfresco.repo.download;
|
||||
|
||||
import net.sf.acegisecurity.Authentication;
|
||||
import org.alfresco.model.ContentModel;
|
||||
import org.alfresco.repo.action.executer.AddFeaturesActionExecuter;
|
||||
import org.alfresco.repo.model.Repository;
|
||||
import org.alfresco.repo.node.SystemNodeUtils;
|
||||
import org.alfresco.repo.node.integrity.IntegrityChecker;
|
||||
@@ -34,6 +35,8 @@ import org.alfresco.repo.security.authentication.AuthenticationUtil;
|
||||
import org.alfresco.repo.security.permissions.AccessDeniedException;
|
||||
import org.alfresco.repo.transaction.RetryingTransactionHelper;
|
||||
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
|
||||
import org.alfresco.service.cmr.action.Action;
|
||||
import org.alfresco.service.cmr.action.ActionService;
|
||||
import org.alfresco.service.cmr.admin.RepoAdminService;
|
||||
import org.alfresco.service.cmr.coci.CheckOutCheckInService;
|
||||
import org.alfresco.service.cmr.download.DownloadService;
|
||||
@@ -47,6 +50,8 @@ import org.alfresco.service.cmr.repository.ContentReader;
|
||||
import org.alfresco.service.cmr.repository.ContentService;
|
||||
import org.alfresco.service.cmr.repository.NodeRef;
|
||||
import org.alfresco.service.cmr.repository.NodeService;
|
||||
import org.alfresco.service.cmr.rule.RuleService;
|
||||
import org.alfresco.service.cmr.rule.RuleType;
|
||||
import org.alfresco.service.cmr.security.MutableAuthenticationService;
|
||||
import org.alfresco.service.cmr.security.PermissionService;
|
||||
import org.alfresco.service.cmr.security.PersonService;
|
||||
@@ -75,6 +80,7 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.Serializable;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -82,6 +88,7 @@ import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
/**
|
||||
@@ -128,6 +135,8 @@ public class DownloadServiceIntegrationTest
|
||||
private static RetryingTransactionHelper TRANSACTION_HELPER;
|
||||
private static IntegrityChecker INTEGRITY_CHECKER;
|
||||
private static RepoAdminService REPO_ADMIN_SERVICE;
|
||||
private static RuleService RULE_SERVICE;
|
||||
private static ActionService ACTION_SERVICE;
|
||||
|
||||
// Test Content
|
||||
private NodeRef rootFolder;
|
||||
@@ -192,6 +201,8 @@ public class DownloadServiceIntegrationTest
|
||||
INTEGRITY_CHECKER.setFailOnViolation(true);
|
||||
INTEGRITY_CHECKER.setTraceOn(true);
|
||||
REPO_ADMIN_SERVICE = APP_CONTEXT_INIT.getApplicationContext().getBean("RepoAdminService", RepoAdminService.class);
|
||||
RULE_SERVICE = APP_CONTEXT_INIT.getApplicationContext().getBean("ruleService", RuleService.class);
|
||||
ACTION_SERVICE = APP_CONTEXT_INIT.getApplicationContext().getBean("actionService", ActionService.class);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -207,28 +218,49 @@ public class DownloadServiceIntegrationTest
|
||||
NodeRef COMPANY_HOME = repositoryHelper.getCompanyHome();
|
||||
|
||||
// Create some static test content
|
||||
rootFolder = testNodes.createNode(COMPANY_HOME, "rootFolder", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());
|
||||
allEntries.add("rootFolder/");
|
||||
rootFolder = testNodes.createNode(COMPANY_HOME, "rootFolder", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());
|
||||
allEntries.add("rootFolder/");
|
||||
|
||||
TRANSACTION_HELPER.doInTransaction(() -> {
|
||||
org.alfresco.service.cmr.rule.Rule parentRule = new org.alfresco.service.cmr.rule.Rule();
|
||||
parentRule.setRuleTypes(Collections.singletonList(RuleType.INBOUND));
|
||||
parentRule.setTitle("DownloadServiceIntegrationTest" + GUID.generate());
|
||||
parentRule.setDescription("Add Classifiable");
|
||||
Action action = ACTION_SERVICE.createAction(AddFeaturesActionExecuter.NAME);
|
||||
action.setParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_CLASSIFIABLE);
|
||||
parentRule.setAction(action);
|
||||
parentRule.applyToChildren(true);
|
||||
|
||||
RULE_SERVICE.saveRule(rootFolder, parentRule);
|
||||
|
||||
return null;
|
||||
}, false, true);
|
||||
|
||||
rootFile = testNodes.createNodeWithTextContent(COMPANY_HOME, "rootFile.txt", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName(), "Root file content");
|
||||
allEntries.add("rootFile.txt");
|
||||
|
||||
testNodes.createNodeWithTextContent(rootFolder, "level1File.txt", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName(), "Level 1 file content");
|
||||
|
||||
NodeRef createdNode = testNodes.createNodeWithTextContent(rootFolder, "level1File.txt", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName(), "Level 1 file content");
|
||||
assertTrue(NODE_SERVICE.hasAspect(createdNode, ContentModel.ASPECT_CLASSIFIABLE));
|
||||
allEntries.add("rootFolder/level1File.txt");
|
||||
|
||||
level1Folder1 = testNodes.createNode(rootFolder, "level1Folder1", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());
|
||||
assertTrue(NODE_SERVICE.hasAspect(level1Folder1, ContentModel.ASPECT_CLASSIFIABLE));
|
||||
allEntries.add("rootFolder/level1Folder1/");
|
||||
|
||||
level1Folder2 = testNodes.createNode(rootFolder, "level1Folder2", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());
|
||||
assertTrue(NODE_SERVICE.hasAspect(level1Folder2, ContentModel.ASPECT_CLASSIFIABLE));
|
||||
allEntries.add("rootFolder/level1Folder2/");
|
||||
|
||||
testNodes.createNode(rootFolder, "level1EmptyFolder", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());
|
||||
createdNode = testNodes.createNode(rootFolder, "level1EmptyFolder", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());
|
||||
assertTrue(NODE_SERVICE.hasAspect(createdNode, ContentModel.ASPECT_CLASSIFIABLE));
|
||||
allEntries.add("rootFolder/level1EmptyFolder/");
|
||||
|
||||
testNodes.createNodeWithTextContent(level1Folder1, "level2File.txt", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName(), "Level 2 file content");
|
||||
createdNode = testNodes.createNodeWithTextContent(level1Folder1, "level2File.txt", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName(), "Level 2 file content");
|
||||
assertTrue(NODE_SERVICE.hasAspect(createdNode, ContentModel.ASPECT_CLASSIFIABLE));
|
||||
allEntries.add("rootFolder/level1Folder1/level2File.txt");
|
||||
|
||||
testNodes.createNodeWithTextContent(level1Folder2, "level2File.txt", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName(), "Level 2 file content");
|
||||
createdNode = testNodes.createNodeWithTextContent(level1Folder2, "level2File.txt", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName(), "Level 2 file content");
|
||||
assertTrue(NODE_SERVICE.hasAspect(createdNode, ContentModel.ASPECT_CLASSIFIABLE));
|
||||
allEntries.add("rootFolder/level1Folder2/level2File.txt");
|
||||
|
||||
secondaryNode = testNodes.createNodeWithTextContent(COMPANY_HOME, "secondaryNodeFile.txt", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName(), "Secondary node");
|
||||
@@ -240,6 +272,7 @@ public class DownloadServiceIntegrationTest
|
||||
// Add the lock and version aspects to the created node
|
||||
NODE_SERVICE.addAspect(fileToCheckout, ContentModel.ASPECT_VERSIONABLE, null);
|
||||
NODE_SERVICE.addAspect(fileToCheckout, ContentModel.ASPECT_LOCKABLE, null);
|
||||
assertTrue(NODE_SERVICE.hasAspect(fileToCheckout, ContentModel.ASPECT_CLASSIFIABLE));
|
||||
|
||||
allEntries.add("rootFolder/level1Folder2/fileToCheckout.txt");
|
||||
PERMISSION_SERVICE.setPermission(level1Folder2, TEST_USER.getUsername(), PermissionService.ALL_PERMISSIONS, true);
|
||||
|
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* #%L
|
||||
* Alfresco Repository
|
||||
* %%
|
||||
* Copyright (C) 2005 - 2022 Alfresco Software Limited
|
||||
* %%
|
||||
* This file is part of the Alfresco software.
|
||||
* If the software was purchased under a paid Alfresco license, the terms of
|
||||
* the paid license agreement will prevail. Otherwise, the software is
|
||||
* provided under the following open source license terms:
|
||||
*
|
||||
* Alfresco is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Alfresco is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
|
||||
* #L%
|
||||
*/
|
||||
package org.alfresco.repo.template;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.util.Map;
|
||||
|
||||
import freemarker.template.Configuration;
|
||||
import freemarker.template.Template;
|
||||
import freemarker.template.TemplateException;
|
||||
import freemarker.template.TemplateExceptionHandler;
|
||||
import junit.framework.TestCase;
|
||||
|
||||
public class UnsafeMethodsTest extends TestCase
|
||||
{
|
||||
private static final String TEST_TEMPLATES_PACKAGE = "/org/alfresco/repo/template/templates/";
|
||||
private static final String ALLOWED_TEXT = ": ALLOWED";
|
||||
private static final String BLOCKED_TEXT = ": BLOCKED";
|
||||
private static final String EXPECTED_RESULT = "Freemarker Unsafe Methods Testing\n" +
|
||||
"=================================\n" +
|
||||
"java.lang.Thread.getId(): ALLOWED\n" +
|
||||
"java.lang.Thread.interrupt(): BLOCKED\n" +
|
||||
"java.lang.Thread.currentThread(): BLOCKED\n";
|
||||
|
||||
private final Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
|
||||
|
||||
public void testUnsafeMethods() throws Exception
|
||||
{
|
||||
configuration.setClassForTemplateLoading(getClass(), TEST_TEMPLATES_PACKAGE);
|
||||
configuration.setDefaultEncoding("UTF-8");
|
||||
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
|
||||
Template template = configuration.getTemplate("unsafemethods.ftl");
|
||||
|
||||
Thread currentThread = Thread.currentThread();
|
||||
Map<String, Object> model = Map.of(
|
||||
"allowedText", ALLOWED_TEXT,
|
||||
"blockedText", BLOCKED_TEXT,
|
||||
"thread", currentThread);
|
||||
|
||||
String result = applyTemplate(template, model);
|
||||
|
||||
assertFalse(currentThread.isInterrupted());
|
||||
assertEquals(EXPECTED_RESULT, result);
|
||||
}
|
||||
|
||||
private String applyTemplate(Template template, Map<String, Object> inputModel ) throws TemplateException, IOException
|
||||
{
|
||||
try (StringWriter stringWriter = new StringWriter())
|
||||
{
|
||||
template.process(inputModel, stringWriter);
|
||||
return stringWriter.toString();
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,5 @@
|
||||
Freemarker Unsafe Methods Testing
|
||||
=================================
|
||||
java.lang.Thread.getId()<#if (thread.getId())??>${allowedText}<#else>${blockedText}</#if>
|
||||
java.lang.Thread.interrupt()<#if (thread.interrupt())??>${allowedText}<#else>${blockedText}</#if>
|
||||
java.lang.Thread.currentThread()<#if (thread.currentThread())??>${allowedText}<#else>${blockedText}</#if>
|
Reference in New Issue
Block a user