Revert to original code structure pre-mavenization

* merges from previous branches are now possible without tree conflicts
  * added back missing commits when structure was changed (r59445, r59446) .. see RM-765
  * updated Maven POM's to use existing code structure
  * NOTE: r59454 and r59473 may have been missed in this update .. will go back and re-add



git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/modules/recordsmanagement/HEAD@59491 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Roy Wetherall
2014-01-08 06:38:59 +00:00
parent a94dc1c586
commit 8cc416f2d2
886 changed files with 535 additions and 361 deletions

View File

@@ -0,0 +1,46 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test;
import org.alfresco.module.org_alfresco_module_rm.test.action.CreateRecordActionTest;
import org.alfresco.module.org_alfresco_module_rm.test.action.FileToActionTest;
import org.alfresco.module.org_alfresco_module_rm.test.action.HideRecordActionTest;
import org.alfresco.module.org_alfresco_module_rm.test.action.RejectActionTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* RM test suite
*
* @author Roy Wetherall
* @since 2.1
*/
@RunWith(Suite.class)
@SuiteClasses(
{
CreateRecordActionTest.class,
HideRecordActionTest.class,
RejectActionTest.class,
FileToActionTest.class
})
public class ActionTestSuite
{
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* Convenience test suite that runs all the tests.
*
* @author Roy Wetherall
* @since 2.1
*/
@RunWith(Suite.class)
@SuiteClasses(
{
ActionTestSuite.class,
CapabilitiesTestSuite.class,
ServicesTestSuite.class,
WebScriptTestSuite.class,
IssueTestSuite.class
})
public class AllTestSuite
{
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test;
import org.alfresco.module.org_alfresco_module_rm.test.capabilities.CompositeCapabilityTest;
import org.alfresco.module.org_alfresco_module_rm.test.capabilities.DeclarativeCapabilityTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* RM test suite
*
* @author Roy Wetherall
*/
@RunWith(Suite.class)
@SuiteClasses(
{
DeclarativeCapabilityTest.class,
CompositeCapabilityTest.class
})
public class CapabilitiesTestSuite
{
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test;
import org.alfresco.module.org_alfresco_module_rm.test.issue.RM1008Test;
import org.alfresco.module.org_alfresco_module_rm.test.issue.RM1027Test;
import org.alfresco.module.org_alfresco_module_rm.test.issue.RM1030Test;
import org.alfresco.module.org_alfresco_module_rm.test.issue.RM1039Test;
import org.alfresco.module.org_alfresco_module_rm.test.issue.RM452Test;
import org.alfresco.module.org_alfresco_module_rm.test.issue.RM804Test;
import org.alfresco.module.org_alfresco_module_rm.test.issue.RM994Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* Issue test suite
*
* @author Roy Wetherall
* @since 2.1
*/
@RunWith(Suite.class)
@SuiteClasses(
{
RM452Test.class,
RM994Test.class,
RM1008Test.class,
RM1030Test.class,
RM1027Test.class,
RM1039Test.class,
RM804Test.class
})
public class IssueTestSuite
{
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test;
import org.alfresco.module.org_alfresco_module_rm.test.service.CapabilityServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.DataSetServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.DispositionServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.ExtendedActionServiceTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.ExtendedSecurityServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.FilePlanPermissionServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.FilePlanRoleServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.FilePlanServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.FreezeServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.ModelSecurityServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.RecordServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.RecordsManagementActionServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.RecordsManagementAdminServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.RecordsManagementAuditServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.RecordsManagementQueryDAOImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.RecordsManagementSearchServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.ReportServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.VitalRecordServiceImplTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* RM test suite
*
* @author Roy Wetherall
*/
@RunWith(Suite.class)
@SuiteClasses(
{
ExtendedSecurityServiceImplTest.class,
ModelSecurityServiceImplTest.class,
RecordsManagementActionServiceImplTest.class,
ExtendedActionServiceTest.class,
DispositionServiceImplTest.class,
RecordsManagementActionServiceImplTest.class,
RecordsManagementAdminServiceImplTest.class,
RecordsManagementAuditServiceImplTest.class,
//RecordsManagementEventServiceImplTest.class,
RecordsManagementSearchServiceImplTest.class,
VitalRecordServiceImplTest.class,
DataSetServiceImplTest.class,
FreezeServiceImplTest.class,
RecordServiceImplTest.class,
CapabilityServiceImplTest.class,
FilePlanRoleServiceImplTest.class,
FilePlanServiceImplTest.class,
FilePlanPermissionServiceImplTest.class,
ReportServiceImplTest.class,
RecordsManagementQueryDAOImplTest.class
})
public class ServicesTestSuite
{
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.ActionDefinitionsRestApiTest;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.CapabilitiesRestApiTest;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.DataSetRestApiTest;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.DispositionRestApiTest;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.EmailMapKeysRestApiTest;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.EmailMapScriptTest;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.EventRestApiTest;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.RMCaveatConfigScriptTest;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.RMConstraintScriptTest;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.RmAuthoritiesRestApiTest;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.RmClassesRestApiTest;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.RmPropertiesRestApiTest;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.RoleRestApiTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* RM WebScript test suite
*
* @author Roy Wetherall
*/
@RunWith(Suite.class)
@SuiteClasses(
{
DispositionRestApiTest.class,
EventRestApiTest.class,
RMCaveatConfigScriptTest.class,
RMConstraintScriptTest.class,
//RmRestApiTest.class,
RoleRestApiTest.class,
DataSetRestApiTest.class,
EmailMapScriptTest.class,
EmailMapKeysRestApiTest.class,
CapabilitiesRestApiTest.class,
ActionDefinitionsRestApiTest.class,
RmClassesRestApiTest.class,
RmPropertiesRestApiTest.class,
RmAuthoritiesRestApiTest.class
})
public class WebScriptTestSuite
{
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.action;
import org.alfresco.module.org_alfresco_module_rm.action.dm.CreateRecordAction;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.security.AccessStatus;
/**
* Record service implementation unit test.
*
* @author Roy Wetherall
*/
public class CreateRecordActionTest extends BaseRMTestCase
{
@Override
protected boolean isUserTest()
{
return true;
}
@Override
protected boolean isCollaborationSiteTest()
{
return true;
}
public void testCreateRecordAction()
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(dmDocument, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(filePlan, RMPermissionModel.VIEW_RECORDS));
Action action = actionService.createAction(CreateRecordAction.NAME);
action.setParameterValue(CreateRecordAction.PARAM_HIDE_RECORD, false);
action.setParameterValue(CreateRecordAction.PARAM_FILE_PLAN, filePlan);
actionService.executeAction(action, dmDocument);
return null;
}
public void test(Void result) throws Exception
{
assertTrue(recordService.isRecord(dmDocument));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(dmDocument, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(filePlan, RMPermissionModel.VIEW_RECORDS));
};
},
dmCollaborator);
}
}

View File

@@ -0,0 +1,295 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.action;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.action.impl.FileToAction;
import org.alfresco.module.org_alfresco_module_rm.capability.Capability;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.AccessStatus;
import org.springframework.util.StringUtils;
/**
* FileTo action unit test
*
* @author Roy Wetherall
* @since 2.1
*/
public class FileToActionTest extends BaseRMTestCase
{
private static final String PATH = "rmcontainer/rmfolder";
private static final String PATH2 = "/rmcontainer/rmfolder";
private static final String PATH_BAD = "monkey/rmfolder";
private static final String PATH_CREATE = "rmcontainer/newrmfolder";
private static final String PATH_SUB1 = "rmcontainer/${node.cm:title}";
@Override
protected boolean isCollaborationSiteTest()
{
return true;
}
@Override
protected boolean isUserTest()
{
return true;
}
public void testFileToNodeRef()
{
initRecord();
doTestInTransaction(new Test<Void>()
{
public Void run()
{
NodeRef unfiledContainer = filePlanService.getUnfiledContainer(filePlan);
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(unfiledContainer, RMPermissionModel.FILING));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(rmFolder, RMPermissionModel.FILING));
Capability capability = capabilityService.getCapability("FileUnfiledRecords");
assertNotNull(capability);
assertEquals(AccessStatus.ALLOWED, capability.hasPermission(dmDocument));
// set parameters
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(FileToAction.PARAM_DESTINATION_RECORD_FOLDER, rmFolder);
// execute file-to action
rmActionService.executeRecordsManagementAction(dmDocument, FileToAction.NAME, params);
// check things have gone according to plan
assertTrue(recordService.isRecord(dmDocument));
assertTrue(recordService.isFiled(dmDocument));
// is the record folder the primary parent of the filed record
NodeRef parent = nodeService.getPrimaryParent(dmDocument).getParentRef();
assertEquals(rmFolder, parent);
return null;
}
}, rmAdminName);
}
private void initRecord()
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
nodeService.setProperty(dmDocument, ContentModel.PROP_TITLE, "mytestvalue");
// create record from document
recordService.createRecord(filePlan, dmDocument);
// check things have gone according to plan
assertTrue(recordService.isRecord(dmDocument));
assertFalse(recordService.isFiled(dmDocument));
// is the unfiled container the primary parent of the filed record
NodeRef parent = nodeService.getPrimaryParent(dmDocument).getParentRef();
assertEquals(filePlanService.getUnfiledContainer(filePlan), parent);
return null;
}
}, dmCollaborator);
}
public void testFileToPath()
{
initRecord();
doTestInTransaction(new Test<Void>()
{
public Void run()
{
// set parameters
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(FileToAction.PARAM_PATH, PATH);
// execute file-to action
rmActionService.executeRecordsManagementAction(dmDocument, FileToAction.NAME, params);
// check things have gone according to plan
assertTrue(recordService.isRecord(dmDocument));
assertTrue(recordService.isFiled(dmDocument));
// is the record folder the primary parent of the filed record
NodeRef parent = nodeService.getPrimaryParent(dmDocument).getParentRef();
assertEquals(rmFolder, parent);
return null;
}
}, rmAdminName);
}
public void testFileToPath2()
{
initRecord();
doTestInTransaction(new Test<Void>()
{
public Void run()
{
// set parameters
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(FileToAction.PARAM_PATH, PATH2);
// execute file-to action
rmActionService.executeRecordsManagementAction(dmDocument, FileToAction.NAME, params);
// check things have gone according to plan
assertTrue(recordService.isRecord(dmDocument));
assertTrue(recordService.isFiled(dmDocument));
// is the record folder the primary parent of the filed record
NodeRef parent = nodeService.getPrimaryParent(dmDocument).getParentRef();
assertEquals(rmFolder, parent);
return null;
}
}, rmAdminName);
}
public void testCreate() throws Exception
{
initRecord();
createRecord(PATH_CREATE, "newrmfolder");
}
public void testCreateSub() throws Exception
{
initRecord();
createRecord(PATH_SUB1, "mytestvalue", "rmcontainer/mytestvalue");
}
private void createRecord(String path, String name)
{
createRecord(path, name, path);
}
private void createRecord(final String path, final String name, final String resolvedPath)
{
doTestInTransaction(new Test<Void>()
{
public Void run() throws Exception
{
String[] pathValues = StringUtils.tokenizeToStringArray(resolvedPath, "/");
// show the folder doesn't exist to begin with
FileInfo createdRecordFolder = fileFolderService.resolveNamePath(filePlan, new ArrayList<String>(Arrays.asList(pathValues)), false);
assertNull(createdRecordFolder);
// set parameters
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(FileToAction.PARAM_PATH, path);
params.put(FileToAction.PARAM_CREATE_RECORD_FOLDER, true);
// execute file-to action
rmActionService.executeRecordsManagementAction(dmDocument, FileToAction.NAME, params);
// show the folder has now been created
createdRecordFolder = fileFolderService.resolveNamePath(filePlan, new ArrayList<String>(Arrays.asList(pathValues)), false);
assertNotNull(createdRecordFolder);
assertEquals(name, createdRecordFolder.getName());
NodeRef createdRecordFolderNodeRef = createdRecordFolder.getNodeRef();
// check things have gone according to plan
assertTrue(recordService.isRecord(dmDocument));
assertTrue(recordService.isFiled(dmDocument));
// is the record folder the primary parent of the filed record
NodeRef parent = nodeService.getPrimaryParent(dmDocument).getParentRef();
assertEquals(createdRecordFolderNodeRef, parent);
return null;
}
}, rmAdminName);
}
public void failureTests() throws Exception
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
// create record from document
recordService.createRecord(filePlan, dmDocument);
// check things have gone according to plan
assertTrue(recordService.isRecord(dmDocument));
assertFalse(recordService.isFiled(dmDocument));
// is the unfiled container the primary parent of the filed record
NodeRef parent = nodeService.getPrimaryParent(dmDocument).getParentRef();
assertEquals(filePlanService.getUnfiledContainer(filePlan), parent);
return null;
}
}, dmCollaborator);
doTestInTransaction(new FailureTest
(
"Path is invalid and record create not set."
)
{
@Override
public void run() throws Exception
{
// set parameters
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(FileToAction.PARAM_PATH, PATH_BAD);
// execute file-to action
rmActionService.executeRecordsManagementAction(dmDocument, FileToAction.NAME, params);
}
});
doTestInTransaction(new FailureTest
(
"Path is for a new folder, but create not set."
)
{
@Override
public void run() throws Exception
{
// set parameters
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(FileToAction.PARAM_PATH, PATH_CREATE);
// execute file-to action
rmActionService.executeRecordsManagementAction(dmDocument, FileToAction.NAME, params);
}
});
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.action;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.action.dm.CreateRecordAction;
import org.alfresco.module.org_alfresco_module_rm.action.dm.HideRecordAction;
import org.alfresco.module.org_alfresco_module_rm.role.Role;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.repository.NodeRef;
/**
* Hide Record Action Unit Test
*
* @author Tuna Aksoy
* @since 2.1
*/
public class HideRecordActionTest extends BaseRMTestCase
{
@Override
protected boolean isUserTest()
{
return true;
}
@Override
protected boolean isCollaborationSiteTest()
{
return true;
}
public void testHideRecordAction()
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
// The user must have the appropriate rights
Role role = filePlanRoleService.getRole(filePlan, "RecordsManager");
authorityService.addAuthority(role.getRoleGroupName(), dmCollaborator);
return null;
}
},
AuthenticationUtil.getAdminUserName());
doTestInTransaction(new Test<Void>()
{
public Void run()
{
// Create a document so that the user has the write permissions for that document
NodeRef doc = fileFolderService.create(dmFolder, "testfile.txt", ContentModel.TYPE_CONTENT).getNodeRef();
// Create a record from that document
Action createAction = actionService.createAction(CreateRecordAction.NAME);
createAction.setParameterValue(CreateRecordAction.PARAM_FILE_PLAN, filePlan);
actionService.executeAction(createAction, doc);
// Check if the document is a record now
assertTrue(recordService.isRecord(doc));
// The record should have the original location information
assertNotNull(nodeService.getProperty(doc, PROP_RECORD_ORIGINATING_LOCATION));
// Check the parents. In this case the document should have two parents (doclib and fileplan)
assertTrue(nodeService.getParentAssocs(doc).size() == 2);
// Hide the document. The user has the write permissions so he should be able to hide it
Action hideAction = actionService.createAction(HideRecordAction.NAME);
actionService.executeAction(hideAction, doc);
// The document should be removed from the collaboration site
assertTrue(nodeService.getParentAssocs(doc).size() == 1);
return null;
}
},
dmCollaborator);
}
}

View File

@@ -0,0 +1,114 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.action;
import org.alfresco.module.org_alfresco_module_rm.action.dm.CreateRecordAction;
import org.alfresco.module.org_alfresco_module_rm.action.impl.RejectAction;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.service.cmr.action.Action;
/**
* Reject Action Unit Test
*
* @author Tuna Aksoy
* @since 2.1
*/
public class RejectActionTest extends BaseRMTestCase
{
/** Reject reason */
private final String REJECT_REASON = "rejectReason:Not valid!£$%^&*()_+";
@Override
protected boolean isUserTest()
{
return true;
}
@Override
protected boolean isCollaborationSiteTest()
{
return true;
}
public void testRejectAction()
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
// Create a record from the document
Action createAction = actionService.createAction(CreateRecordAction.NAME);
createAction.setParameterValue(CreateRecordAction.PARAM_FILE_PLAN, filePlan);
actionService.executeAction(createAction, dmDocument);
// Check if the document is a record now
assertTrue(recordService.isRecord(dmDocument));
// The record should have the original location information
assertNotNull(nodeService.getProperty(dmDocument, PROP_RECORD_ORIGINATING_LOCATION));
// Check the parents. In this case the document should have two parents (doclib and fileplan)
assertTrue(nodeService.getParentAssocs(dmDocument).size() == 2);
return null;
}
},
dmCollaborator);
doTestInTransaction(new FailureTest("Cannot reject a record without a reason.", IllegalArgumentException.class)
{
public void run()
{
// The test should fail if the reject reason is not supplied
Action rejectAction = actionService.createAction(RejectAction.NAME);
actionService.executeAction(rejectAction, dmDocument);
}
},
dmCollaborator);
doTestInTransaction(new Test<Void>()
{
public Void run()
{
// Create the reject action and add the reject reason
Action rejectAction = actionService.createAction(RejectAction.NAME);
rejectAction.setParameterValue(RejectAction.PARAM_REASON, REJECT_REASON);
actionService.executeAction(rejectAction, dmDocument);
// The "record" aspect should be removed
assertFalse(nodeService.hasAspect(dmDocument, ASPECT_RECORD));
// The "file plan component" should be removed
assertFalse(nodeService.hasAspect(dmDocument, ASPECT_FILE_PLAN_COMPONENT));
// The "identifier" property should be removed
assertNull(nodeService.getProperty(dmDocument, PROP_IDENTIFIER));
// The record should be removed from the file plan
assertTrue(nodeService.getParentAssocs(dmDocument).size() == 1);
// The extended reader information should be removed
assertNull(extendedSecurityService.getExtendedReaders(dmDocument));
return null;
}
},
dmCollaborator);
}
}

View File

@@ -0,0 +1,163 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.capabilities;
import org.alfresco.module.org_alfresco_module_rm.capability.Capability;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.AccessStatus;
/**
* Declarative capability unit test
*
* @author Roy Wetherall
*/
public class CompositeCapabilityTest extends BaseRMTestCase
{
private NodeRef record;
private NodeRef declaredRecord;
@Override
protected boolean isUserTest()
{
return true;
}
@Override
protected void setupTestDataImpl()
{
super.setupTestDataImpl();
// Pre-filed content
record = utils.createRecord(rmFolder, "record.txt");
declaredRecord = utils.createRecord(rmFolder, "declaredRecord.txt");
}
@Override
protected void setupTestData()
{
super.setupTestData();
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
utils.declareRecord(declaredRecord);
return null;
}
});
}
@Override
protected void tearDownImpl()
{
super.tearDownImpl();
}
@Override
protected void setupTestUsersImpl(NodeRef filePlan)
{
super.setupTestUsersImpl(filePlan);
// Give all the users file permission objects
for (String user : testUsers)
{
filePlanPermissionService.setPermission(rmContainer, user, RMPermissionModel.FILING);
}
}
public void testUpdate()
{
final Capability capability = capabilityService.getCapability("Update");
assertNotNull(capability);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.ALLOWED, capability.hasPermission(rmContainer));
assertEquals(AccessStatus.ALLOWED, capability.hasPermission(rmFolder));
assertEquals(AccessStatus.ALLOWED, capability.hasPermission(record));
assertEquals(AccessStatus.ALLOWED, capability.hasPermission(declaredRecord));
return null;
}
}, recordsManagerName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmContainer));
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(record));
assertEquals(AccessStatus.DENIED, capability.hasPermission(declaredRecord));
return null;
}
}, userName);
}
public void testUpdateProperties()
{
final Capability capability = capabilityService.getCapability("UpdateProperties");
assertNotNull(capability);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.ALLOWED, capability.hasPermission(rmContainer));
assertEquals(AccessStatus.ALLOWED, capability.hasPermission(rmFolder));
assertEquals(AccessStatus.ALLOWED, capability.hasPermission(record));
assertEquals(AccessStatus.ALLOWED, capability.hasPermission(declaredRecord));
return null;
}
}, recordsManagerName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmContainer));
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(record));
assertEquals(AccessStatus.DENIED, capability.hasPermission(declaredRecord));
return null;
}
}, userName);
}
}

View File

@@ -0,0 +1,486 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.capabilities;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sf.acegisecurity.vote.AccessDecisionVoter;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.capability.Capability;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.capability.declarative.CapabilityCondition;
import org.alfresco.module.org_alfresco_module_rm.capability.declarative.DeclarativeCompositeCapability;
import org.alfresco.module.org_alfresco_module_rm.capability.declarative.DeclarativeCapability;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanComponentKind;
import org.alfresco.module.org_alfresco_module_rm.role.Role;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.AccessStatus;
/**
* Declarative capability unit test
*
* @author Roy Wetherall
*/
public class DeclarativeCapabilityTest extends BaseRMTestCase
{
private NodeRef record;
private NodeRef declaredRecord;
private NodeRef undeclaredRecord;
private NodeRef recordFolderContainsFrozen;
private NodeRef frozenRecord;
private NodeRef frozenRecord2;
private NodeRef frozenRecordFolder;
private NodeRef closedFolder;
private NodeRef moveToFolder;
private NodeRef moveToCategory;
@Override
protected boolean isUserTest()
{
return true;
}
@Override
protected void setupTestDataImpl()
{
super.setupTestDataImpl();
// Pre-filed content
record = utils.createRecord(rmFolder, "record.txt");
declaredRecord = utils.createRecord(rmFolder, "declaredRecord.txt");
undeclaredRecord = utils.createRecord(rmFolder, "undeclaredRecord.txt");
// Closed folder
closedFolder = recordFolderService.createRecordFolder(rmContainer, "closedFolder");
utils.closeFolder(closedFolder);
// Frozen artifacts
recordFolderContainsFrozen = recordFolderService.createRecordFolder(rmContainer, "containsFrozen");
frozenRecord = utils.createRecord(rmFolder, "frozenRecord.txt");
frozenRecord2 = utils.createRecord(recordFolderContainsFrozen, "frozen2.txt");
frozenRecordFolder = recordFolderService.createRecordFolder(rmContainer, "frozenRecordFolder");
// MoveTo artifacts
moveToFolder = recordFolderService.createRecordFolder(rmContainer, "moveToFolder");
moveToCategory = filePlanService.createRecordCategory(rmContainer, "moveToCategory");
}
@Override
protected void setupTestData()
{
super.setupTestData();
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
utils.declareRecord(declaredRecord);
utils.declareRecord(frozenRecord);
utils.declareRecord(frozenRecord2);
utils.freeze(frozenRecord);
utils.freeze(frozenRecordFolder);
utils.freeze(frozenRecord2);
return null;
}
});
}
@Override
protected void tearDownImpl()
{
// Unfreeze stuff so it can be deleted
utils.unfreeze(frozenRecord);
utils.unfreeze(frozenRecordFolder);
utils.unfreeze(frozenRecord2);
super.tearDownImpl();
}
@Override
protected void setupTestUsersImpl(NodeRef filePlan)
{
super.setupTestUsersImpl(filePlan);
// Give all the users file permission objects
for (String user : testUsers)
{
filePlanPermissionService.setPermission(rmFolder, user, RMPermissionModel.FILING);
filePlanPermissionService.setPermission(moveToFolder, user, RMPermissionModel.READ_RECORDS);
filePlanPermissionService.setPermission(moveToCategory, user, RMPermissionModel.READ_RECORDS);
}
}
public void testDeclarativeCapabilities()
{
Set<Capability> capabilities = capabilityService.getCapabilities();
for (Capability capability : capabilities)
{
if (capability instanceof DeclarativeCapability &&
capability instanceof DeclarativeCompositeCapability == false &&
capability.isPrivate() == false &&
capability.getName().equals("MoveRecords") == false &&
capability.getName().equals("DeleteLinks") == false &&
capability.getName().equals("ChangeOrDeleteReferences") == false)
{
testDeclarativeCapability((DeclarativeCapability)capability);
}
}
}
private void testDeclarativeCapability(final DeclarativeCapability capability)
{
for (String user : testUsers)
{
testDeclarativeCapability(capability, user, filePlan);
testDeclarativeCapability(capability, user, rmContainer);
testDeclarativeCapability(capability, user, rmFolder);
testDeclarativeCapability(capability, user, record);
}
}
private void testDeclarativeCapability(final DeclarativeCapability capability, final String userName, final NodeRef filePlanComponent)
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
AccessStatus accessStatus = capability.hasPermission(filePlanComponent);
Set<Role> roles = filePlanRoleService.getRolesByUser(filePlan, userName);
if (roles.isEmpty() == true)
{
assertEquals("User " + userName + " has no RM role so we expect access to be denied for capability " + capability.getName(),
AccessStatus.DENIED,
accessStatus);
}
else
{
// Do the kind check here ...
FilePlanComponentKind actualKind = filePlanService.getFilePlanComponentKind(filePlanComponent);
List<String> kinds = capability.getKinds();
if (kinds == null ||
kinds.contains(actualKind.toString()) == true)
{
Map<String, Boolean> conditions = capability.getConditions();
boolean conditionResult = getConditionResult(filePlanComponent, conditions);
assertEquals("User is expected to only have one role.", 1, roles.size());
Role role = new ArrayList<Role>(roles).get(0);
assertNotNull(role);
Set<Capability> roleCapabilities = role.getCapabilities();
if (roleCapabilities.contains(capability) == true && conditionResult == true)
{
assertEquals("User " + userName + " has the role " + role.getDisplayLabel() +
" so we expect access to be allowed for capability " + capability.getName() + " on the object " +
(String)nodeService.getProperty(filePlanComponent, ContentModel.PROP_NAME),
AccessStatus.ALLOWED,
accessStatus);
}
else
{
assertEquals("User " + userName + " has the role " + role.getDisplayLabel() + " so we expect access to be denied for capability " + capability.getName(),
AccessStatus.DENIED,
accessStatus);
}
}
else
{
// Expect fail since the kind is not expected by the capability
assertEquals("NodeRef is of kind" + actualKind + " so we expect access to be denied for capability " + capability.getName(),
AccessStatus.DENIED,
accessStatus);
}
}
return null;
}
}, userName);
}
private boolean getConditionResult(NodeRef nodeRef, Map<String, Boolean> conditions)
{
boolean result = true;
if (conditions != null && conditions.size() != 0)
{
for (Map.Entry<String, Boolean> entry : conditions.entrySet())
{
// Get the condition bean
CapabilityCondition condition = (CapabilityCondition)applicationContext.getBean(entry.getKey());
assertNotNull("Invalid condition name.", condition);
boolean actual = condition.evaluate(nodeRef);
if (actual != entry.getValue().booleanValue())
{
result = false;
break;
}
}
}
return result;
}
/** Specific declarative capability tests */
public void testCreateRecordCapability()
{
final Capability capability = capabilityService.getCapability("CreateRecords");
assertNotNull(capability);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmContainer));
assertEquals(AccessStatus.ALLOWED, capability.hasPermission(rmFolder));
assertEquals(AccessStatus.ALLOWED, capability.hasPermission(record));
assertEquals(AccessStatus.DENIED, capability.hasPermission(declaredRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecordFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(recordFolderContainsFrozen));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(closedFolder));
return null;
}
}, recordsManagerName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmContainer));
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(record));
assertEquals(AccessStatus.DENIED, capability.hasPermission(declaredRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecordFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(recordFolderContainsFrozen));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(closedFolder));
return null;
}
}, rmUserName);
}
public void testMoveRecordCapability()
{
// grab the move record capability
final Capability capability = capabilityService.getCapability("MoveRecords");
assertNotNull(capability);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// first take a look at just the record
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmContainer));
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmFolder));
assertEquals(AccessStatus.UNDETERMINED, capability.hasPermission(record));
assertEquals(AccessStatus.UNDETERMINED, capability.hasPermission(declaredRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecordFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(recordFolderContainsFrozen));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(closedFolder));
assertEquals(AccessStatus.UNDETERMINED, capability.hasPermission(undeclaredRecord));
// now lets take a look when we know what the destination is
// NOTE: should be denied since we do not have file permission on the destination folder
// despite having the capability!
assertEquals(AccessDecisionVoter.ACCESS_DENIED, capability.evaluate(record, moveToFolder));
assertEquals(AccessDecisionVoter.ACCESS_DENIED, capability.evaluate(declaredRecord, moveToFolder));
assertEquals(AccessDecisionVoter.ACCESS_DENIED, capability.evaluate(undeclaredRecord, moveToFolder));
assertEquals(AccessDecisionVoter.ACCESS_DENIED, capability.evaluate(frozenRecord, moveToFolder));
return null;
}
}, recordsManagerName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
for (String user : testUsers)
{
filePlanPermissionService.setPermission(moveToFolder, user, RMPermissionModel.FILING);
}
return null;
}
}, rmAdminName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// first take a look at just the record
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmContainer));
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmFolder));
assertEquals(AccessStatus.UNDETERMINED, capability.hasPermission(record));
assertEquals(AccessStatus.UNDETERMINED, capability.hasPermission(declaredRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecordFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(recordFolderContainsFrozen));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(closedFolder));
assertEquals(AccessStatus.UNDETERMINED, capability.hasPermission(undeclaredRecord));
// now lets take a look when we know what the destination is
// NOTE: should be allowed now since we have filling permission on the destination folder
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, capability.evaluate(record, moveToFolder));
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, capability.evaluate(declaredRecord, moveToFolder));
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, capability.evaluate(undeclaredRecord, moveToFolder));
assertEquals(AccessDecisionVoter.ACCESS_DENIED, capability.evaluate(frozenRecord, moveToFolder));
return null;
}
}, recordsManagerName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// first take a look at just the record
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmContainer));
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(record));
assertEquals(AccessStatus.DENIED, capability.hasPermission(declaredRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecordFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(recordFolderContainsFrozen));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(closedFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(undeclaredRecord));
// now lets take a look when we know what the destination is
// NOTE: should be allowed now since we have filling permission on the destination folder
assertEquals(AccessDecisionVoter.ACCESS_DENIED, capability.evaluate(record, moveToFolder));
assertEquals(AccessDecisionVoter.ACCESS_DENIED, capability.evaluate(declaredRecord, moveToFolder));
assertEquals(AccessDecisionVoter.ACCESS_DENIED, capability.evaluate(undeclaredRecord, moveToFolder));
assertEquals(AccessDecisionVoter.ACCESS_DENIED, capability.evaluate(frozenRecord, moveToFolder));
return null;
}
}, rmUserName);
}
public void testMoveRecordFolderCapability()
{
// grab the move record capability
final Capability capability = capabilityService.getCapability("MoveRecordFolder");
assertNotNull(capability);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// first take a look at just the record
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmContainer));
assertEquals(AccessStatus.UNDETERMINED, capability.hasPermission(rmFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(record));
assertEquals(AccessStatus.DENIED, capability.hasPermission(declaredRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecordFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(recordFolderContainsFrozen));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(closedFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(undeclaredRecord));
assertEquals(AccessDecisionVoter.ACCESS_DENIED, capability.evaluate(rmFolder, moveToCategory));
return null;
}
}, recordsManagerName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
for (String user : testUsers)
{
filePlanPermissionService.setPermission(moveToCategory, user, RMPermissionModel.FILING);
}
return null;
}
}, rmAdminName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmContainer));
assertEquals(AccessStatus.UNDETERMINED, capability.hasPermission(rmFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(record));
assertEquals(AccessStatus.DENIED, capability.hasPermission(declaredRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecordFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(recordFolderContainsFrozen));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(closedFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(undeclaredRecord));
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, capability.evaluate(rmFolder, moveToCategory));
return null;
}
}, recordsManagerName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmContainer));
assertEquals(AccessStatus.DENIED, capability.hasPermission(rmFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(record));
assertEquals(AccessStatus.DENIED, capability.hasPermission(declaredRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecordFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(recordFolderContainsFrozen));
assertEquals(AccessStatus.DENIED, capability.hasPermission(frozenRecord));
assertEquals(AccessStatus.DENIED, capability.hasPermission(closedFolder));
assertEquals(AccessStatus.DENIED, capability.hasPermission(undeclaredRecord));
assertEquals(AccessDecisionVoter.ACCESS_DENIED, capability.evaluate(rmFolder, moveToCategory));
return null;
}
}, rmUserName);
}
}

View File

@@ -0,0 +1,358 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.issue;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.capability.Capability;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionSchedule;
import org.alfresco.module.org_alfresco_module_rm.role.FilePlanRoleService;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.AccessStatus;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.util.GUID;
/**
* System test for RM-1008
*
* @author Roy Wetherall
* @since 2.1
*/
public class RM1008Test extends BaseRMTestCase
{
private String myUser;
@Override
protected boolean isRecordTest()
{
return true;
}
@Override
protected boolean isUserTest()
{
return true;
}
@Override
protected void setupTestUsersImpl(NodeRef filePlan)
{
super.setupTestUsersImpl(filePlan);
myUser = GUID.generate();
createPerson(myUser);
filePlanRoleService.assignRoleToAuthority(filePlan, FilePlanRoleService.ROLE_USER, myUser);
}
public void testContainers() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
NodeRef holdContainer = filePlanService.getHoldContainer(filePlan);
assertNotNull(holdContainer);
NodeRef transferContainer = filePlanService.getTransferContainer(filePlan);
assertNotNull(transferContainer);
Capability viewRecords = capabilityService.getCapability("ViewRecords");
assertNotNull(viewRecords);
assertEquals(AccessStatus.ALLOWED, viewRecords.hasPermission(holdContainer));
assertEquals(AccessStatus.ALLOWED, viewRecords.hasPermission(transferContainer));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(holdContainer, RMPermissionModel.FILING));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(transferContainer, RMPermissionModel.FILING));
return null;
}
}, rmAdminName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
NodeRef holdContainer = filePlanService.getHoldContainer(filePlan);
assertNotNull(holdContainer);
NodeRef transferContainer = filePlanService.getTransferContainer(filePlan);
assertNotNull(transferContainer);
Capability viewRecords = capabilityService.getCapability("ViewRecords");
assertNotNull(viewRecords);
assertEquals(AccessStatus.ALLOWED, viewRecords.hasPermission(holdContainer));
assertEquals(AccessStatus.ALLOWED, viewRecords.hasPermission(transferContainer));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(holdContainer, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(transferContainer, RMPermissionModel.FILING));
return null;
}
}, myUser);
}
public void testHold()
{
final NodeRef hold = doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
// create hold object
freezeService.freeze("test", rmFolder);
Set<NodeRef> holds = freezeService.getHolds(filePlan);
return holds.iterator().next();
}
}, rmAdminName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
Capability viewRecords = capabilityService.getCapability("ViewRecords");
assertNotNull(viewRecords);
assertEquals(AccessStatus.ALLOWED, viewRecords.hasPermission(hold));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(hold, RMPermissionModel.FILING));
return null;
}
}, rmAdminName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
Capability viewRecords = capabilityService.getCapability("ViewRecords");
assertNotNull(viewRecords);
assertEquals(AccessStatus.ALLOWED, viewRecords.hasPermission(hold));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(hold, RMPermissionModel.FILING));
return null;
}
}, myUser);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
filePlanPermissionService.setPermission(filePlan, myUser, FILING);
return null;
}
}, rmAdminName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
Capability viewRecords = capabilityService.getCapability("ViewRecords");
assertNotNull(viewRecords);
assertEquals(AccessStatus.ALLOWED, viewRecords.hasPermission(hold));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(hold, RMPermissionModel.FILING));
return null;
}
}, myUser);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
filePlanPermissionService.deletePermission(filePlan, myUser, FILING);
return null;
}
}, rmAdminName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
Capability viewRecords = capabilityService.getCapability("ViewRecords");
assertNotNull(viewRecords);
assertEquals(AccessStatus.ALLOWED, viewRecords.hasPermission(hold));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(hold, RMPermissionModel.FILING));
return null;
}
}, myUser);
}
public void testTransfer()
{
final NodeRef transferFolder = doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
NodeRef transferCat = filePlanService.createRecordCategory(filePlan, "transferCat");
Map<QName, Serializable> dsProps = new HashMap<QName, Serializable>(3);
dsProps.put(PROP_DISPOSITION_AUTHORITY, "test");
dsProps.put(PROP_DISPOSITION_INSTRUCTIONS, "test");
dsProps.put(PROP_RECORD_LEVEL_DISPOSITION, false);
DispositionSchedule dispositionSchedule = dispositionService.createDispositionSchedule(transferCat, dsProps);
Map<QName, Serializable> adParams = new HashMap<QName, Serializable>(3);
adParams.put(PROP_DISPOSITION_ACTION_NAME, "cutoff");
adParams.put(PROP_DISPOSITION_DESCRIPTION, "test");
adParams.put(PROP_DISPOSITION_PERIOD, "immediately|0");
dispositionService.addDispositionActionDefinition(dispositionSchedule, adParams);
adParams = new HashMap<QName, Serializable>(3);
adParams.put(PROP_DISPOSITION_ACTION_NAME, "transfer");
adParams.put(PROP_DISPOSITION_DESCRIPTION, "test");
adParams.put(PROP_DISPOSITION_PERIOD, "immediately|0");
dispositionService.addDispositionActionDefinition(dispositionSchedule, adParams);
return recordFolderService.createRecordFolder(transferCat, "transferFolder");
}
});
final NodeRef transfer = doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
rmActionService.executeRecordsManagementAction(transferFolder, "cutoff");
rmActionService.executeRecordsManagementAction(transferFolder, "transfer");
NodeRef transferContainer = filePlanService.getTransferContainer(filePlan);
List<ChildAssociationRef> childAssocs = nodeService.getChildAssocs(transferContainer, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
return childAssocs.get(0).getChildRef();
}
@Override
public void test(NodeRef result) throws Exception
{
assertNotNull(result);
assertEquals(TYPE_TRANSFER, nodeService.getType(result));
}
});
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
Capability viewRecords = capabilityService.getCapability("ViewRecords");
assertNotNull(viewRecords);
assertEquals(AccessStatus.ALLOWED, viewRecords.hasPermission(transfer));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(transfer, RMPermissionModel.FILING));
return null;
}
}, rmAdminName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
Capability viewRecords = capabilityService.getCapability("ViewRecords");
assertNotNull(viewRecords);
assertEquals(AccessStatus.ALLOWED, viewRecords.hasPermission(transfer));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(transfer, RMPermissionModel.FILING));
return null;
}
}, myUser);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
filePlanPermissionService.setPermission(filePlan, myUser, FILING);
return null;
}
}, rmAdminName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
Capability viewRecords = capabilityService.getCapability("ViewRecords");
assertNotNull(viewRecords);
assertEquals(AccessStatus.ALLOWED, viewRecords.hasPermission(transfer));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(transfer, RMPermissionModel.FILING));
return null;
}
}, myUser);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
filePlanPermissionService.deletePermission(filePlan, myUser, FILING);
return null;
}
}, rmAdminName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
Capability viewRecords = capabilityService.getCapability("ViewRecords");
assertNotNull(viewRecords);
assertEquals(AccessStatus.ALLOWED, viewRecords.hasPermission(transfer));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(transfer, RMPermissionModel.FILING));
return null;
}
}, myUser);
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.issue;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.NodeRef;
/**
* Unit test for RM-1027 .. can't copy a closed folder
*
* @author Roy Wetherall
* @since 2.1
*/
public class RM1027Test extends BaseRMTestCase
{
public void testCopyingAClosedFolder() throws Exception
{
final NodeRef recordFolder = doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
// create a folder and close it
NodeRef recordFolder = recordFolderService.createRecordFolder(rmContainer, "My Closed Record Folder");
utils.closeFolder(recordFolder);
assertTrue((Boolean)nodeService.getProperty(recordFolder, PROP_IS_CLOSED));
return recordFolder;
}
});
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run() throws Exception
{
// create a destination for the copy
NodeRef destination = filePlanService.createRecordCategory(filePlan, "Copy Destination");
// try and copy the closed record folder
FileInfo copyInfo = fileFolderService.copy(recordFolder, destination, null);
return copyInfo.getNodeRef();
}
@Override
public void test(NodeRef copy) throws Exception
{
assertNotNull(copy);
assertNotNull(nodeService.getProperty(copy, PROP_IDENTIFIER));
assertFalse((Boolean)nodeService.getProperty(copy, PROP_IS_CLOSED));
}
});
}
public void testCopyingAFolderWithADispositionSchedule() throws Exception
{
final NodeRef recordFolder = doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
// create a folder
NodeRef recordFolder = recordFolderService.createRecordFolder(rmContainer, "My Closed Record Folder");
// show that the default disposition schedule has been applied
assertTrue(nodeService.hasAspect(recordFolder, ASPECT_DISPOSITION_LIFECYCLE));
return recordFolder;
}
});
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run() throws Exception
{
// create a destination for the copy
NodeRef destination = filePlanService.createRecordCategory(filePlan, "Copy Destination");
// try and copy the closed record folder
FileInfo copyInfo = fileFolderService.copy(recordFolder, destination, null);
return copyInfo.getNodeRef();
}
@Override
public void test(NodeRef copy) throws Exception
{
assertNotNull(copy);
assertNotNull(nodeService.getProperty(copy, PROP_IDENTIFIER));
assertFalse(nodeService.hasAspect(copy, ASPECT_DISPOSITION_LIFECYCLE));
}
});
}
}

View File

@@ -0,0 +1,145 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.issue;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.service.cmr.repository.NodeRef;
/**
* Unit test for RM-1030 .. can't freeze a record folder that already has a frozen record contained within
*
* @author Roy Wetherall
* @since 2.1
*/
public class RM1030Test extends BaseRMTestCase
{
@Override
protected boolean isRecordTest()
{
return true;
}
public void testRM1030() throws Exception
{
final NodeRef recordHold = doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
// show there are no holds when we start
Set<NodeRef> holds = freezeService.getHolds(filePlan);
assertNotNull(holds);
assertEquals(0, holds.size());
// freeze record contained within the record folder
NodeRef hold = freezeService.freeze("in true life for serious", recordOne);
assertNotNull(hold);
return hold;
}
@Override
public void test(NodeRef hold) throws Exception
{
// show the record is frozen
assertTrue(freezeService.isFrozen(recordOne));
// count the number of holds
Set<NodeRef> holds = freezeService.getHolds(filePlan);
assertNotNull(holds);
assertEquals(1, holds.size());
}
});
final NodeRef recordFolderHold = doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
// freeze the record folder that contains the frozen record
NodeRef folderHold = freezeService.freeze("innit but", rmFolder);
assertNotNull(folderHold);
return folderHold;
}
@Override
public void test(NodeRef hold) throws Exception
{
// show that the record and the record folder are frozen
assertTrue(freezeService.isFrozen(recordOne));
assertTrue(freezeService.isFrozen(rmFolder));
// count the number of holds
Set<NodeRef> holds = freezeService.getHolds(filePlan);
assertNotNull(holds);
assertEquals(2, holds.size());
}
});
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// relinquish the record folder hold
freezeService.relinquish(recordFolderHold);
return null;
}
@Override
public void test(Void result) throws Exception
{
assertTrue(freezeService.isFrozen(recordOne));
assertFalse(freezeService.isFrozen(rmFolder));
Set<NodeRef> holds = freezeService.getHolds(filePlan);
assertNotNull(holds);
assertEquals(1, holds.size());
}
});
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// relinquish the record hold
freezeService.relinquish(recordHold);
return null;
}
@Override
public void test(Void result) throws Exception
{
assertFalse(freezeService.isFrozen(recordOne));
assertFalse(freezeService.isFrozen(rmFolder));
Set<NodeRef> holds = freezeService.getHolds(filePlan);
assertNotNull(holds);
assertEquals(0, holds.size());
}
});
}
}

View File

@@ -0,0 +1,181 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.issue;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import net.sf.acegisecurity.vote.AccessDecisionVoter;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.action.impl.CompleteEventAction;
import org.alfresco.module.org_alfresco_module_rm.action.impl.CutOffAction;
import org.alfresco.module.org_alfresco_module_rm.capability.Capability;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionAction;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.module.org_alfresco_module_rm.test.util.CommonRMTestUtils;
import org.alfresco.service.cmr.repository.NodeRef;
/**
* Unit test for RM-1039 ... can't move a folder into a category with a disposition schedule
*
* @author Roy Wetherall
* @since 2.1
*/
public class RM1039Test extends BaseRMTestCase
{
@Override
protected boolean isRecordTest()
{
return true;
}
// try and move a folder from no disposition schedule to a disposition schedule
public void testMoveRecordFolderFromNoDisToDis() throws Exception
{
final NodeRef recordFolder = doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
// create a record category (no disposition schedule)
NodeRef recordCategory = filePlanService.createRecordCategory(filePlan, "Caitlin Reed");
// create a record folder
return recordFolderService.createRecordFolder(recordCategory, "Grace Wetherall");
}
@Override
public void test(NodeRef result) throws Exception
{
assertNotNull(result);
assertNull(dispositionService.getDispositionSchedule(result));
assertFalse(nodeService.hasAspect(result, ASPECT_DISPOSITION_LIFECYCLE));
}
});
final NodeRef record = doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
// create a record
return fileFolderService.create(recordFolder, "mytest.txt", ContentModel.TYPE_CONTENT).getNodeRef();
}
@Override
public void test(NodeRef result) throws Exception
{
assertNotNull(result);
assertNull(dispositionService.getDispositionSchedule(result));
assertFalse(nodeService.hasAspect(result, ASPECT_DISPOSITION_LIFECYCLE));
}
});
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run() throws Exception
{
Capability capability = capabilityService.getCapability("CreateModifyDestroyFolders");
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, capability.evaluate(recordFolder));
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, capability.evaluate(recordFolder, rmContainer));
// take a look at the move capability
Capability moveCapability = capabilityService.getCapability("Move");
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, moveCapability.evaluate(recordFolder, rmContainer));
// move the node
return fileFolderService.move(recordFolder, rmContainer, null).getNodeRef();
}
@Override
public void test(NodeRef result) throws Exception
{
assertNotNull(result);
assertNotNull(dispositionService.getDispositionSchedule(result));
assertTrue(nodeService.hasAspect(result, ASPECT_DISPOSITION_LIFECYCLE));
DispositionAction dispositionAction = dispositionService.getNextDispositionAction(result);
assertNotNull(dispositionAction);
assertNull(dispositionAction.getAsOfDate());
assertEquals("cutoff", dispositionAction.getName());
assertEquals(1, dispositionAction.getEventCompletionDetails().size());
// take a look at the record and check things are as we would expect
assertFalse(nodeService.hasAspect(record, ASPECT_DISPOSITION_LIFECYCLE));
}
});
}
// move from a disposition schedule to another .. both record folder level
// move from a disposition schedule to another .. from record to folder level
// try and move a cutoff folder
public void testMoveCutoffRecordFolder() throws Exception
{
final NodeRef destination = doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
// create a record category (no disposition schedule)
return filePlanService.createRecordCategory(filePlan, "Caitlin Reed");
}
});
final NodeRef testFolder = doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
// create folder
NodeRef testFolder = recordFolderService.createRecordFolder(rmContainer, "Peter Edward Francis");
// complete event
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(CompleteEventAction.PARAM_EVENT_NAME, CommonRMTestUtils.DEFAULT_EVENT_NAME);
rmActionService.executeRecordsManagementAction(testFolder, CompleteEventAction.NAME, params);
// cutoff folder
rmActionService.executeRecordsManagementAction(testFolder, CutOffAction.NAME);
// take a look at the move capability
Capability moveCapability = capabilityService.getCapability("Move");
assertEquals(AccessDecisionVoter.ACCESS_DENIED, moveCapability.evaluate(testFolder, destination));
return testFolder;
}
});
doTestInTransaction(new FailureTest()
{
@Override
public void run() throws Exception
{
fileFolderService.move(testFolder, destination, null).getNodeRef();
}
});
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.issue;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.module.org_alfresco_module_rm.test.util.TestService;
/**
* System test for RM-452
*
* See alfresco.extension.rm-method-security.properties
*
* @author Roy Wetherall
* @since 2.1
*/
public class RM452Test extends BaseRMTestCase
{
private TestService testService;
@Override
protected void initServices()
{
super.initServices();
testService = (TestService)applicationContext.getBean("TestService");
}
@Override
protected boolean isCollaborationSiteTest()
{
return true;
}
@Override
protected boolean isRecordTest()
{
return true;
}
public void testRM452() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertNotNull(folder);
assertNotNull(recordOne);
assertFalse(filePlanService.isFilePlanComponent(folder));
assertTrue(filePlanService.isFilePlanComponent(recordOne));
// call methodOne with non-RM artifact .. expect success
testService.testMethodOne(folder);
// call methodTwo with non-RM artifact .. expect success
testService.testMethodTwo(folder);
// call methodOne with an RM artifact .. expect success
testService.testMethodOne(recordOne);
return null;
}
});
doTestInTransaction(new FailureTest
(
"Shouldn't be able to call testMethodTwo on TestService, because override RM security for method is not configred.",
AlfrescoRuntimeException.class
)
{
@Override
public void run() throws Exception
{
// call methodTwo with an RM artifact .. expect failure
testService.testMethodTwo(recordOne);
}
});
}
}

View File

@@ -0,0 +1,189 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.issue;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.service.cmr.security.AccessStatus;
import org.alfresco.service.cmr.site.SiteRole;
/**
* Unit test for RM-804 .. site managers are able to delete file plans
*
* @author Roy Wetherall
* @since 2.1
*/
public class RM804Test extends BaseRMTestCase
{
@Override
protected void initServices()
{
super.initServices();
}
@Override
protected boolean isCollaborationSiteTest()
{
return true;
}
@Override
protected boolean isUserTest()
{
return true;
}
public void testUsersHaveDeletePermissionsOnFilePlan() throws Exception
{
// as rmuser
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.ALLOWED, capabilityService.getCapabilityAccessState(filePlan, "Delete"));
return null;
}
}, "rmadmin");
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.ALLOWED, capabilityService.getCapabilityAccessState(filePlan, "Delete"));
return null;
}
}, "admin");
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.ALLOWED, capabilityService.getCapabilityAccessState(filePlan, "Delete"));
return null;
}
}, rmAdminName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, capabilityService.getCapabilityAccessState(filePlan, "Delete"));
return null;
}
}, rmUserName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, capabilityService.getCapabilityAccessState(filePlan, "Delete"));
return null;
}
}, userName);
}
public void testTryAndDeleteSiteAsSiteManagerOnly()
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
siteService.setMembership(siteId, userName, SiteRole.SiteManager.toString());
return null;
}
}, "admin");
doTestInTransaction(new FailureTest
(
"Should not be able to delete site as a site manager only.",
AlfrescoRuntimeException.class
)
{
@Override
public void run() throws Exception
{
siteService.deleteSite(siteId);
}
}, userName);
// give the user a RM role (but not sufficient to delete the file plan node ref)
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
filePlanRoleService.assignRoleToAuthority(filePlan, ROLE_NAME_USER, userName);
return null;
}
}, "admin");
doTestInTransaction(new FailureTest
(
"Should not be able to delete site as a site manager with an RM role that doesn't have the capability.",
AlfrescoRuntimeException.class
)
{
@Override
public void run() throws Exception
{
siteService.deleteSite(siteId);
}
}, userName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
filePlanRoleService.assignRoleToAuthority(filePlan, ROLE_NAME_ADMINISTRATOR, userName);
return null;
}
}, "admin");
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
siteService.deleteSite(siteId);
return null;
}
}, userName);
}
}

View File

@@ -0,0 +1,116 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.issue;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
/**
* See https://issues.alfresco.com/jira/browse/RM-981.
*
* Instance of the repository needs to be running on localhost:8080 before executing this
* system test.
*
* @author Roy Wetherall
*/
public class RM981SystemTest extends TestCase
{
public void testRM981() throws Exception
{
ExecutorService pool = Executors.newFixedThreadPool(2);
SecureRandom rnd = new SecureRandom();
List<String> data = new ArrayList<String>();
for (int i = 0; i < 100; i++)
{
String definitionname = "test_" + i + "_" + rnd.nextInt(Integer.MAX_VALUE);
data.add(definitionname);
}
for (String definitionname : data)
{
pool.submit(new SendRequest(definitionname));
}
pool.shutdown();
pool.awaitTermination(60L, TimeUnit.SECONDS);
}
class SendRequest implements Runnable
{
private String definitionname;
public SendRequest(String definitionname)
{
this.definitionname = definitionname;
}
@Override
public void run()
{
try
{
URL url = new URL("http://localhost:8080/alfresco/service/api/rma/admin/customreferencedefinitions");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Authorization", "Basic YWRtaW46YWRtaW4=");
String body = "{\"referenceType\":\"bidirectional\",\"label\":\"" + definitionname + "\"}";
OutputStream out = conn.getOutputStream();
out.write(body.getBytes("UTF-8"));
out.flush();
out.close();
int status = conn.getResponseCode();
if (status != 200)
{
System.out.println("Reproduced");
System.out.println("---------------------------------");
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
reader.close();
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
}

View File

@@ -0,0 +1,126 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.issue;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.module.org_alfresco_module_rm.vital.VitalRecordDefinition;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.Period;
/**
* System test for RM-994
*
* @author Roy Wetherall
* @since 2.1
*/
public class RM994Test extends BaseRMTestCase
{
@Override
protected void initServices()
{
super.initServices();
}
@Override
protected boolean isCollaborationSiteTest()
{
return true;
}
@Override
protected boolean isRecordTest()
{
return true;
}
public void testRM944() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
checkVitalRecordNotSet(rmContainer);
checkVitalRecordNotSet(rmFolder);
checkVitalRecordNotSet(recordOne);
assertNull(nodeService.getProperty(recordOne, PROP_REVIEW_AS_OF));
vitalRecordService.setVitalRecordDefintion(rmContainer, true, new Period("month|1"));
return null;
}
});
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
checkVitalRecordSet(rmContainer);
checkVitalRecordSet(rmFolder);
checkVitalRecordSet(recordOne);
assertNotNull(nodeService.getProperty(recordOne, PROP_REVIEW_AS_OF));
recordService.createRecord(filePlan, dmDocument, true);
assertTrue(recordService.isRecord(dmDocument));
checkVitalRecordNotSet(dmDocument);
fileFolderService.move(dmDocument, rmFolder, null);
checkVitalRecordSet(dmDocument);
return null;
}
}, "admin");
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
checkVitalRecordSet(dmDocument);
return null;
}
});
}
private void checkVitalRecordSet(NodeRef nodeRef)
{
VitalRecordDefinition def = vitalRecordService.getVitalRecordDefinition(nodeRef);
assertNotNull(def);
assertTrue(def.isEnabled());
assertEquals("month", def.getReviewPeriod().getPeriodType());
assertEquals("1", def.getReviewPeriod().getExpression());
}
private void checkVitalRecordNotSet(NodeRef nodeRef)
{
VitalRecordDefinition recordDef = vitalRecordService.getVitalRecordDefinition(nodeRef);
if (recordDef != null)
{
assertFalse(recordDef.isEnabled());
assertEquals("none", recordDef.getReviewPeriod().getPeriodType());
assertNull(recordDef.getNextReviewDate());
}
}
}

View File

@@ -0,0 +1,151 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.jscript;
import java.io.Serializable;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.repo.jscript.app.JSONConversionComponent;
import org.alfresco.service.cmr.repository.NodeRef;
import org.apache.commons.lang.ArrayUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @author Roy Wetherall
*/
public class JSONConversionComponentTest extends BaseRMTestCase
{
private JSONConversionComponent converter;
private NodeRef record;
@Override
protected void initServices()
{
super.initServices();
converter = (JSONConversionComponent)applicationContext.getBean("jsonConversionComponent");
}
@Override
protected void setupTestDataImpl()
{
super.setupTestDataImpl();
// Create records
record = utils.createRecord(rmFolder, "testRecord.txt");
}
public void testJSON() throws Exception
{
doTestInTransaction(new JSONTest
(
filePlan,
new String[]{"isRmNode", "true", "boolean"},
new String[]{"rmNode.kind", "FILE_PLAN"}
){});
doTestInTransaction(new JSONTest
(
rmContainer,
new String[]{"isRmNode", "true", "boolean"},
new String[]{"rmNode.kind", "RECORD_CATEGORY"}
){});
doTestInTransaction(new JSONTest
(
rmFolder,
new String[]{"isRmNode", "true", "boolean"},
new String[]{"rmNode.kind", "RECORD_FOLDER"}
){});
doTestInTransaction(new JSONTest
(
record,
new String[]{"isRmNode", "true", "boolean"},
new String[]{"rmNode.kind", "RECORD"}
){});
}
class JSONTest extends Test<JSONObject>
{
private NodeRef nodeRef;
private String[][] testValues;
public JSONTest(NodeRef nodeRef, String[] ... testValues)
{
this.nodeRef = nodeRef;
this.testValues = testValues;
}
@Override
public JSONObject run() throws Exception
{
String json = converter.toJSON(nodeRef, true);
System.out.println(json);
return new JSONObject(json);
}
@Override
public void test(JSONObject result) throws Exception
{
for (String[] testValue : testValues)
{
String key = testValue[0];
String type = "string";
if (testValue.length == 3)
{
type = testValue[2];
}
Serializable value = convertValue(testValue[1], type);
Serializable actualValue = (Serializable)getValue(result, key);
assertEquals("The key " + key + " did not have the expected value.", value, actualValue);
}
}
private Serializable convertValue(String stringValue, String type)
{
Serializable value = stringValue;
if (type.equals("boolean") == true)
{
value = new Boolean(stringValue);
}
return value;
}
private Object getValue(JSONObject jsonObject, String key) throws JSONException
{
return getValue(jsonObject, key.split("\\."));
}
private Object getValue(JSONObject jsonObject, String[] key) throws JSONException
{
if (key.length == 1)
{
return jsonObject.get(key[0]);
}
else
{
return getValue(jsonObject.getJSONObject(key[0]),
(String[])ArrayUtils.subarray(key, 1, key.length));
}
}
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.security;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
/**
* Tests method level security of core alfresco services.
*
* @author Roy Wetherall
* @since 2.0
*/
public class MethodSecurityTest extends BaseRMTestCase implements RMPermissionModel
{
/**
* Indicate this is a user test.
*
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#isUserTest()
*/
@Override
protected boolean isUserTest()
{
return true;
}
/**
* Test node service security access
*/
public void testNodeService()
{
doTestInTransaction(new FailureTest
(
"We don't have permission to access this node."
)
{
@Override
public void run()
{
nodeService.getProperties(rmContainer);
}
}, rmUserName);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
filePlanPermissionService.setPermission(rmContainer, rmUserName, READ_RECORDS);
return null;
}
@Override
public void test(Void result) throws Exception
{
nodeService.getProperties(rmContainer);
}
}, rmUserName);
}
}

View File

@@ -0,0 +1,187 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.capability.Capability;
import org.alfresco.module.org_alfresco_module_rm.capability.CapabilityService;
import org.alfresco.module.org_alfresco_module_rm.capability.Group;
import org.alfresco.module.org_alfresco_module_rm.capability.GroupImpl;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
/**
* Test class for testing the methods in {@link CapabilityService}
*
* @author Tuna Aksoy
* @since 2.1
*/
public class CapabilityServiceImplTest extends BaseRMTestCase
{
public void testGetCapability() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
// FIXME
return null;
}
});
}
public void testGetCapabilities() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
// FIXME
return null;
}
});
}
public void testGetCapabilityAccessState() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
// FIXME
return null;
}
});
}
public void testGetCapabilitiesAccessState() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
// FIXME
return null;
}
});
}
public void testGetAddRemoveGroups() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
Group auditGroup = capabilityService.getGroup("audit");
assertNotNull(auditGroup);
assertEquals(10, auditGroup.getIndex());
assertEquals("Audit", auditGroup.getTitle());
assertEquals("audit", auditGroup.getId());
return null;
}
});
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
int initialSize = capabilityService.getGroups().size();
GroupImpl testGroup = new GroupImpl();
testGroup.setId("testGroup");
testGroup.setIndex(140);
testGroup.setTitle("Test group");
capabilityService.addGroup(testGroup);
assertEquals(initialSize+1, capabilityService.getGroups().size());
Group group = capabilityService.getGroup("testGroup");
assertNotNull(group);
assertTrue(group.getId().equalsIgnoreCase("testGroup"));
assertTrue(group.getTitle().equalsIgnoreCase("Test group"));
assertTrue(group.getIndex() == 140);
return null;
}
});
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
Group testGroup = capabilityService.getGroup("testGroup");
assertNotNull(testGroup);
int initialSize = capabilityService.getGroups().size();
capabilityService.removeGroup(testGroup);
assertEquals(initialSize-1, capabilityService.getGroups().size());
return null;
}
});
}
public void testGetCapabilitiesByGroup() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
List<Group> groups = capabilityService.getGroups();
assertNotNull(groups);
Group auditGroup = groups.get(0);
assertNotNull(auditGroup);
List<Capability> auditCapabilities = capabilityService.getCapabilitiesByGroup(auditGroup);
assertNotNull(auditCapabilities);
int vitalRecordCapabilitiesSize = auditCapabilities.size();
assertTrue(vitalRecordCapabilitiesSize > 1);
for (int i = 1; i == vitalRecordCapabilitiesSize; i++)
{
Capability capability = auditCapabilities.get(i);
assertNotNull(capability);
assertEquals(i * 10, capability.getIndex());
}
Group vitalRecordsGroup = groups.get(groups.size() - 1);
assertNotNull(vitalRecordsGroup);
List<Capability> vitalRecordCapabilities = capabilityService.getCapabilitiesByGroupId(vitalRecordsGroup.getId());
assertNotNull(vitalRecordCapabilities);
vitalRecordCapabilitiesSize = vitalRecordCapabilities.size();
assertTrue(vitalRecordCapabilitiesSize > 0);
return null;
}
});
}
}

View File

@@ -0,0 +1,146 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.module.org_alfresco_module_rm.email.CustomEmailMappingService;
import org.alfresco.module.org_alfresco_module_rm.email.CustomMapping;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
/**
* Custom EMail Mapping Service
*
* @author Roy Wetherall
* @since 2.0
*/
public class CustomEMailMappingServiceImplTest extends BaseRMTestCase
{
private CustomEmailMappingService eMailMappingService;
@Override
protected void initServices()
{
super.initServices();
eMailMappingService = (CustomEmailMappingService)applicationContext.getBean("customEmailMappingService");
}
@Override
protected boolean isUserTest()
{
return true;
}
@Override
protected void setUp() throws Exception
{
super.setUp();
eMailMappingService.registerEMailMappingKey("EmailMappingKeyTest1");
eMailMappingService.registerEMailMappingKey("EmailMappingKeyTest2");
}
public void testCRUD() throws Exception
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
// Check the initial custom mapping size
assertTrue(checkCustomMappingsSize(20));
String firstKey = eMailMappingService.getEmailMappingKeys().get(0);
// Add a custom mapping
eMailMappingService.addCustomMapping(firstKey, "cm:monkeyFace");
// Check the new size
assertTrue(checkCustomMappingsSize(21));
// Check the new added custom mapping
CustomMapping monkeyMapping = getCustomMapping(firstKey, "cm:monkeyFace");
assertNotNull(monkeyMapping);
assertEquals(firstKey, monkeyMapping.getFrom());
assertEquals("cm:monkeyFace", monkeyMapping.getTo());
// Delete the new added custom mapping
eMailMappingService.deleteCustomMapping(firstKey, "cm:monkeyFace");
// Check the size after deletion
assertTrue(checkCustomMappingsSize(20));
// Check the custom mapping after deletion if it exists
assertNull(getCustomMapping(firstKey, "cm:monkeyFace"));
// Check the email mapping keys size
// There are 6 "standard" EmailMappingKeys + 2 CustomEmailMappingKeys are added on setUp
assertTrue(checkEmailMappingKeysSize(8));
try
{
eMailMappingService.addCustomMapping(" ", "cm:monkeyFace");
fail("Should not get here. Invalid data.");
}
catch (AlfrescoRuntimeException are)
{
assertNotNull(are); //Must throw this exception
assertTrue(are.getMessage().contains("Invalid values for"));
}
try
{
eMailMappingService.addCustomMapping("monkey", " ");
fail("Should not get here. Invalid data.");
}
catch (AlfrescoRuntimeException are)
{
assertNotNull(are); //Must throw this exception
assertTrue(are.getMessage().contains("Invalid values for"));
}
eMailMappingService.addCustomMapping(firstKey, "cm:monkeyFace"); //valid key
return null;
}
}, rmAdminName);
}
private CustomMapping getCustomMapping(String from, String to)
{
CustomMapping result = null;
for (CustomMapping customMapping : eMailMappingService.getCustomMappings())
{
if (customMapping.getFrom().equalsIgnoreCase(from) && customMapping.getTo().equalsIgnoreCase(to))
{
result = customMapping;
break;
}
}
return result;
}
private boolean checkCustomMappingsSize(int expected)
{
return expected == eMailMappingService.getCustomMappings().size() ? true : false;
}
private boolean checkEmailMappingKeysSize(int expected)
{
return expected == eMailMappingService.getEmailMappingKeys().size() ? true : false;
}
}

View File

@@ -0,0 +1,264 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.dataset.DataSet;
import org.alfresco.module.org_alfresco_module_rm.dataset.DataSetService;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionSchedule;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.module.org_alfresco_module_rm.vital.VitalRecordDefinition;
import org.alfresco.service.cmr.repository.NodeRef;
/**
* Dataset Service Test
*
* @author Tuna Aksoy
* @since 2.1
*/
public class DataSetServiceImplTest extends BaseRMTestCase
{
/** Id of the test data set*/
private static final String DATA_SET_ID = "testExampleData";
/**
* @see DataSetService#getDataSets()
*/
public void testGetDataSets() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
Map<String, DataSet> dataSets = dataSetService.getDataSets();
// Test the data sets
assertNotNull(dataSets);
// At least the test data set must exist
assertTrue(dataSets.size() >= 1);
// The test data set must be in the list of available data sets
assertNotNull(dataSets.get(DATA_SET_ID));
for (Map.Entry<String, DataSet> entry : dataSets.entrySet())
{
// Test the key
String key = entry.getKey();
assertNotNull(key);
// Test the value
DataSet dataSet = entry.getValue();
assertNotNull(dataSet);
// Test the id
String id = dataSet.getId();
assertNotNull(id);
assertEquals(id, key);
// Test the label
String label = dataSet.getLabel();
assertNotNull(label);
// Test the path
String path = dataSet.getPath();
assertNotNull(path);
}
return null;
}
});
}
/**
* @see DataSetService#loadDataSet(String, org.alfresco.service.cmr.repository.NodeRef)
*/
public void testLoadDataSet() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
// Test the file plan before importing the data sets
testFilePlanBeforeImportingDataSet();
// Load the data set into the specified file plan
dataSetService.loadDataSet(filePlan, DATA_SET_ID);
// Test the file plan after importing the data sets
testFilePlanAfterImportingDataSet();
return null;
}
/**
* Helper method for testing the test file plan before importing the data
*/
private void testFilePlanBeforeImportingDataSet()
{
// There should not be any categories before importing
assertNull(nodeService.getChildByName(filePlan, ContentModel.ASSOC_CONTAINS, "TestRecordCategory1"));
assertNull(nodeService.getChildByName(filePlan, ContentModel.ASSOC_CONTAINS, "TestRecordCategory2"));
// The aspect should exist before loading a data set
assertNull(nodeService.getProperty(filePlan, PROP_LOADED_DATA_SET_IDS));
// At the beginning the file plan is empty. So there should not be any data sets
assertTrue(dataSetService.getLoadedDataSets(filePlan).size() == 0);
assertFalse(dataSetService.isLoadedDataSet(filePlan, DATA_SET_ID));
assertTrue(dataSetService.getDataSets(filePlan, true).size() > 0);
assertTrue(dataSetService.getDataSets(filePlan, false).size() > 0);
}
/**
* Helper method for testing the test file plan after importing the data
*/
private void testFilePlanAfterImportingDataSet()
{
// Test the "first level" categories after importing if they exist
// TestRecordCategory1
NodeRef recCat1 = nodeService.getChildByName(filePlan, ContentModel.ASSOC_CONTAINS, "TestRecordCategory1");
assertNotNull(recCat1);
List<NodeRef> recCat1ImmediateChildren = filePlanService.getAllContained(recCat1);
assertTrue(recCat1ImmediateChildren.size() == 3);
List<NodeRef> recCat1AllChildren = filePlanService.getAllContained(recCat1, true);
assertTrue(recCat1AllChildren.size() == 6);
DispositionSchedule recCat1DispositionSchedule = dispositionService.getDispositionSchedule(recCat1);
assertNull(recCat1DispositionSchedule);
// TestRecordCategory2
NodeRef recCat2 = nodeService.getChildByName(filePlan, ContentModel.ASSOC_CONTAINS, "TestRecordCategory2");
assertNotNull(recCat2);
List<NodeRef> recCat2ImmediateChildren = filePlanService.getAllContained(recCat2);
assertTrue(recCat2ImmediateChildren.size() == 2);
List<NodeRef> recCat2AllChildren = filePlanService.getAllContained(recCat2, true);
assertTrue(recCat2AllChildren.size() == 4);
DispositionSchedule recCat2DispositionSchedule = dispositionService.getDispositionSchedule(recCat2);
assertNull(recCat2DispositionSchedule);
// TestRecordCategory1: Test the "second level" categories and record folders
NodeRef recCat11 = nodeService.getChildByName(recCat1, ContentModel.ASSOC_CONTAINS, "TestRecordCategory11");
assertNotNull(recCat11);
List<NodeRef> recCat11ImmediateChilderen = filePlanService.getAllContained(recCat11);
assertTrue(recCat11ImmediateChilderen.size() == 2);
List<NodeRef> recCat11Childeren = filePlanService.getAllContained(recCat11, true);
assertTrue(recCat11Childeren.size() == 2);
assertNotNull(nodeService.getChildByName(recCat11, ContentModel.ASSOC_CONTAINS, "TestRecordFolder1"));
assertNotNull(nodeService.getChildByName(recCat11, ContentModel.ASSOC_CONTAINS, "TestRecordFolder2"));
VitalRecordDefinition recCat11VitalRecordDefinition = vitalRecordService.getVitalRecordDefinition(recCat11);
assertNotNull(recCat11VitalRecordDefinition);
assertTrue(recCat11VitalRecordDefinition.getReviewPeriod().getExpression().equals("1"));
assertNotNull(recCat11VitalRecordDefinition.getNextReviewDate());
NodeRef recCat12 = nodeService.getChildByName(recCat1, ContentModel.ASSOC_CONTAINS, "TestRecordCategory12");
assertNotNull(recCat12);
List<NodeRef> recCat12ImmediateChildren = filePlanService.getAllContained(recCat12);
assertTrue(recCat12ImmediateChildren.size() == 1);
List<NodeRef> recCat12Children = filePlanService.getAllContained(recCat12, true);
assertTrue(recCat12Children.size() == 1);
assertNotNull(nodeService.getChildByName(recCat12, ContentModel.ASSOC_CONTAINS, "TestRecordFolder3"));
DispositionSchedule recCat12DispositionSchedule = dispositionService.getDispositionSchedule(recCat12);
assertNotNull(recCat12DispositionSchedule);
assertTrue(recCat12DispositionSchedule.getDispositionInstructions().equals("Cut off every 3 months, hold 3 months, then destroy."));
assertTrue(recCat12DispositionSchedule.getDispositionAuthority().equals("T0-000-00-1 item 002"));
assertTrue(recCat12DispositionSchedule.getDispositionActionDefinitions().size() == 2);
assertNotNull(recCat12DispositionSchedule.getDispositionActionDefinitionByName("cutoff"));
assertNotNull(recCat12DispositionSchedule.getDispositionActionDefinitionByName("destroy"));
NodeRef recCat13 = nodeService.getChildByName(recCat1, ContentModel.ASSOC_CONTAINS, "TestRecordCategory13");
assertNotNull(recCat13);
List<NodeRef> recCat13ImmediateChildren = filePlanService.getAllContained(recCat13);
assertTrue(recCat13ImmediateChildren.size() == 0);
DispositionSchedule recCat13DispositionSchedule = dispositionService.getDispositionSchedule(recCat13);
assertNotNull(recCat13DispositionSchedule);
// TestRecordCategory2: Test the "second level" categories and record folders
NodeRef recCat21 = nodeService.getChildByName(recCat2, ContentModel.ASSOC_CONTAINS, "TestRecordCategory21");
assertNotNull(recCat21);
List<NodeRef> recCat21ImmediateChildren = filePlanService.getAllContained(recCat21);
assertTrue(recCat21ImmediateChildren.size() == 0);
DispositionSchedule recCat21DispositionSchedule = dispositionService.getDispositionSchedule(recCat21);
assertNotNull(recCat21DispositionSchedule);
NodeRef recCat22 = nodeService.getChildByName(recCat2, ContentModel.ASSOC_CONTAINS, "TestRecordCategory22");
assertNotNull(recCat22);
List<NodeRef> recCat22ImmediateChildren = filePlanService.getAllContained(recCat22);
assertTrue(recCat22ImmediateChildren.size() == 2);
List<NodeRef> recCat22Children = filePlanService.getAllContained(recCat22, true);
assertTrue(recCat22Children.size() == 2);
assertNotNull(nodeService.getChildByName(recCat22, ContentModel.ASSOC_CONTAINS, "TestRecordFolder4"));
assertNotNull(nodeService.getChildByName(recCat22, ContentModel.ASSOC_CONTAINS, "TestRecordFolder5"));
DispositionSchedule recCat22DispositionSchedule = dispositionService.getDispositionSchedule(recCat22);
assertNotNull(recCat22DispositionSchedule);
// After loading the data set into the file plan the custom aspect should contain the id of the loaded data set
Serializable nodeProperty = nodeService.getProperty(filePlan, PROP_LOADED_DATA_SET_IDS);
assertNotNull(nodeProperty);
@SuppressWarnings("unchecked")
ArrayList<String> loadedDataSetIds = (ArrayList<String>)nodeProperty;
assertTrue(loadedDataSetIds.size() == 1);
assertTrue(loadedDataSetIds.contains(DATA_SET_ID));
// The data set has been loaded into the file plan, so the file plan should contain the data set id
Map<String, DataSet> loadedDataSets = dataSetService.getLoadedDataSets(filePlan);
assertTrue(loadedDataSets.size() == 1);
assertTrue(loadedDataSets.containsKey(DATA_SET_ID));
assertTrue(dataSetService.isLoadedDataSet(filePlan, DATA_SET_ID));
assertTrue(dataSetService.getDataSets(filePlan, true).size() > 0);
assertTrue(dataSetService.getDataSets(filePlan, false).size() > 1);
}
});
}
/**
* @see DataSetService#existsDataSet(String)
*/
public void testExistsDataSet() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
// Test if a data set with the specified data set id exists
assertTrue(dataSetService.existsDataSet(DATA_SET_ID));
assertFalse(dataSetService.existsDataSet("AnotherDataSetId"));
return null;
}
});
}
/*
* INFO:
*
* The tests for
*
* DataSetService#getDataSets(NodeRef, boolean)
* DataSetService#getLoadedDataSets(NodeRef)
* DataSetService#isLoadedDataSet(NodeRef, String)
*
* will be executed in testFilePlanBeforeImportingDataSet() and testFilePlanAfterImportingDataSet().
*/
}

View File

@@ -0,0 +1,172 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.module.org_alfresco_module_rm.test.util.TestActionPropertySubs;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ActionDefinition;
/**
* Extended action service test.
*
* @author Roy Wetherall
* @since 2.1
*/
public class ExtendedActionServiceTest extends BaseRMTestCase
{
/** Action names */
public static final String TEST_ACTION = "testAction";
public static final String TEST_ACTION_2 = "testAction2";
public static final String TEST_DM_ACTION = "testDMAction";
public static final String RECORD_ONLY_ACTION = "recordOnlyAction";
public static final String RECORD_AND_FOLDER_ONLY_ACTION = "recordandFolderOnlyAction";
public static final String DELEGATE_ACTION = "rmDelegateAction";
@Override
protected boolean isUserTest()
{
return true;
}
@Override
protected boolean isCollaborationSiteTest()
{
return true;
}
@Override
protected boolean isRecordTest()
{
return true;
}
// NOTE: temporarily disabled test ... now that RM actions are no longer registered with the action service, aplicability
// may no longer be relevant ... possibly something to back out??
public void xtestAvailableActions()
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
List<ActionDefinition> result = actionService.getActionDefinitions(recordOne);
assertNotNull(result);
assertFalse(containsAction(result, TEST_ACTION));
assertTrue(containsAction(result, TEST_ACTION_2));
assertFalse(containsAction(result, TEST_DM_ACTION));
assertTrue(containsAction(result, RECORD_ONLY_ACTION));
assertTrue(containsAction(result, RECORD_AND_FOLDER_ONLY_ACTION));
assertTrue(containsAction(result, DELEGATE_ACTION));
result = actionService.getActionDefinitions(rmFolder);
assertNotNull(result);
assertFalse(containsAction(result, TEST_ACTION));
assertTrue(containsAction(result, TEST_ACTION_2));
assertFalse(containsAction(result, TEST_DM_ACTION));
assertFalse(containsAction(result, RECORD_ONLY_ACTION));
assertTrue(containsAction(result, RECORD_AND_FOLDER_ONLY_ACTION));
assertFalse(containsAction(result, DELEGATE_ACTION));
result = actionService.getActionDefinitions(rmContainer);
assertNotNull(result);
assertFalse(containsAction(result, TEST_ACTION));
assertTrue(containsAction(result, TEST_ACTION_2));
assertFalse(containsAction(result, TEST_DM_ACTION));
assertFalse(containsAction(result, RECORD_ONLY_ACTION));
assertFalse(containsAction(result, RECORD_AND_FOLDER_ONLY_ACTION));
assertFalse(containsAction(result, DELEGATE_ACTION));
result = actionService.getActionDefinitions(dmDocument);
assertNotNull(result);
assertFalse(containsAction(result, TEST_ACTION));
assertFalse(containsAction(result, TEST_ACTION_2));
assertTrue(containsAction(result, TEST_DM_ACTION));
assertFalse(containsAction(result, RECORD_ONLY_ACTION));
assertFalse(containsAction(result, RECORD_AND_FOLDER_ONLY_ACTION));
assertFalse(containsAction(result, DELEGATE_ACTION));
result = actionService.getActionDefinitions(dmFolder);
assertNotNull(result);
assertFalse(containsAction(result, TEST_ACTION));
assertFalse(containsAction(result, TEST_ACTION_2));
assertTrue(containsAction(result, TEST_DM_ACTION));
assertFalse(containsAction(result, RECORD_ONLY_ACTION));
assertFalse(containsAction(result, RECORD_AND_FOLDER_ONLY_ACTION));
assertFalse(containsAction(result, DELEGATE_ACTION));
return null;
}
});
}
private boolean containsAction(List<ActionDefinition> list, String actionName)
{
boolean result = false;
for (ActionDefinition actionDefinition : list)
{
if (actionDefinition.getName().equals(actionName) == true)
{
result = true;
break;
}
}
return result;
}
public void testActionPropertySubstitution() throws Exception
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
Action action = actionService.createAction(TestActionPropertySubs.NAME);
action.setParameterValue("dayShort", "${date.day.short}");
action.setParameterValue("dayShort2", "${date.day}");
action.setParameterValue("dayLong", "${date.day.long}");
action.setParameterValue("dayNumber", "${date.day.number}");
action.setParameterValue("dayYear", "${date.day.year}");
action.setParameterValue("monthShort", "${date.month.short}");
action.setParameterValue("monthShort2", "${date.month}");
action.setParameterValue("monthLong", "${date.month.long}");
action.setParameterValue("monthNumber", "${date.month.number}");
action.setParameterValue("yearShort", "${date.year.short}");
action.setParameterValue("yearShort2", "${date.year}");
action.setParameterValue("yearLong", "${date.year.long}");
action.setParameterValue("yearWeek", "${date.year.week}");
action.setParameterValue("name", "${node.cm:name}");
action.setParameterValue("company", "${message.test.company}");
action.setParameterValue("combo", "${date.year.long}/${date.month.short}/${node.cm:name}-${message.test.company}.txt");
actionService.executeAction(action, rmFolder);
return null;
}
});
}
}

View File

@@ -0,0 +1,240 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.util.GUID;
/**
* Records management security service test.
*
* @author Roy Wetherall
*/
public class ExtendedSecurityServiceImplTest extends BaseRMTestCase
{
private NodeRef record;
private NodeRef recordToo;
private NodeRef moveRecordCategory;
private NodeRef moveRecordFolder;
@Override
protected boolean isUserTest()
{
return true;
}
@Override
protected void setupTestDataImpl()
{
super.setupTestDataImpl();
record = utils.createRecord(rmFolder, "record.txt");
recordToo = utils.createRecord(rmFolder, "recordToo.txt");
moveRecordCategory = filePlanService.createRecordCategory(filePlan, "moveRecordCategory");
moveRecordFolder = recordFolderService.createRecordFolder(moveRecordCategory, "moveRecordFolder");
}
private String createTestUser()
{
return doTestInTransaction(new Test<String>()
{
public String run()
{
String userName = GUID.generate();
createPerson(userName);
return userName;
}
}, AuthenticationUtil.getSystemUserName());
}
public void testExtendedSecurity()
{
final String monkey = createTestUser();
final String elephant = createTestUser();
final String snake = createTestUser();
doTestInTransaction(new Test<Void>()
{
public Void run()
{
assertFalse(extendedSecurityService.hasExtendedSecurity(filePlan));
assertFalse(extendedSecurityService.hasExtendedSecurity(rmContainer));
assertFalse(extendedSecurityService.hasExtendedSecurity(rmFolder));
assertFalse(extendedSecurityService.hasExtendedSecurity(record));
assertNull(extendedSecurityService.getExtendedReaders(record));
assertNull(extendedSecurityService.getExtendedWriters(record));
Set<String> extendedReaders = new HashSet<String>(2);
extendedReaders.add(monkey);
extendedReaders.add(elephant);
extendedSecurityService.addExtendedSecurity(record, extendedReaders, null);
Map<String, Integer> testMap = new HashMap<String, Integer>(2);
testMap.put(monkey, Integer.valueOf(1));
testMap.put(elephant, Integer.valueOf(1));
checkExtendedReaders(filePlan, testMap);
checkExtendedReaders(rmContainer, testMap);
checkExtendedReaders(rmFolder, testMap);
checkExtendedReaders(record, testMap);
Set<String> extendedReadersToo = new HashSet<String>(2);
extendedReadersToo.add(monkey);
extendedReadersToo.add(snake);
extendedSecurityService.addExtendedSecurity(recordToo, extendedReadersToo, null);
Map<String, Integer> testMapToo = new HashMap<String, Integer>(2);
testMapToo.put(monkey, Integer.valueOf(1));
testMapToo.put(snake, Integer.valueOf(1));
Map<String, Integer> testMapThree = new HashMap<String, Integer>(3);
testMapThree.put(monkey, Integer.valueOf(2));
testMapThree.put(elephant, Integer.valueOf(1));
testMapThree.put(snake, Integer.valueOf(1));
checkExtendedReaders(filePlan, testMapThree);
checkExtendedReaders(rmContainer, testMapThree);
checkExtendedReaders(rmFolder, testMapThree);
checkExtendedReaders(recordToo, testMapToo);
// test remove (with no parent inheritance)
Set<String> removeMap1 = new HashSet<String>(2);
removeMap1.add(elephant);
removeMap1.add(monkey);
extendedSecurityService.removeExtendedSecurity(rmFolder, removeMap1, null, false);
Map<String, Integer> testMapFour = new HashMap<String, Integer>(2);
testMapFour.put(monkey, Integer.valueOf(1));
testMapFour.put(snake, Integer.valueOf(1));
checkExtendedReaders(filePlan, testMapThree);
checkExtendedReaders(rmContainer, testMapThree);
checkExtendedReaders(rmFolder, testMapFour);
checkExtendedReaders(recordToo, testMapToo);
// test remove (apply to parents)
Set<String> removeMap2 = new HashSet<String>(1);
removeMap2.add(snake);
extendedSecurityService.removeExtendedSecurity(recordToo, removeMap2, null, true);
testMapThree.remove(snake);
testMapFour.remove(snake);
testMapToo.remove(snake);
checkExtendedReaders(filePlan, testMapThree);
checkExtendedReaders(rmContainer, testMapThree);
checkExtendedReaders(rmFolder, testMapFour);
checkExtendedReaders(recordToo, testMapToo);
return null;
}
});
}
public void testMove()
{
final String monkey = createTestUser();
final String elephant = createTestUser();
doTestInTransaction(new Test<Void>()
{
Map<String, Integer> testMap = new HashMap<String, Integer>(2);
public Void run() throws Exception
{
testMap.put(monkey, Integer.valueOf(1));
testMap.put(elephant, Integer.valueOf(1));
assertFalse(extendedSecurityService.hasExtendedSecurity(filePlan));
assertFalse(extendedSecurityService.hasExtendedSecurity(rmContainer));
assertFalse(extendedSecurityService.hasExtendedSecurity(rmFolder));
assertFalse(extendedSecurityService.hasExtendedSecurity(record));
assertFalse(extendedSecurityService.hasExtendedSecurity(moveRecordCategory));
assertFalse(extendedSecurityService.hasExtendedSecurity(moveRecordFolder));
assertNull(extendedSecurityService.getExtendedReaders(record));
Set<String> extendedReaders = new HashSet<String>(2);
extendedReaders.add(monkey);
extendedReaders.add(elephant);
extendedSecurityService.addExtendedSecurity(record, extendedReaders, null);
checkExtendedReaders(filePlan, testMap);
checkExtendedReaders(rmContainer, testMap);
checkExtendedReaders(rmFolder, testMap);
checkExtendedReaders(record, testMap);
assertFalse(extendedSecurityService.hasExtendedSecurity(moveRecordCategory));
assertFalse(extendedSecurityService.hasExtendedSecurity(moveRecordFolder));
fileFolderService.move(record, moveRecordFolder, "movedRecord");
return null;
}
@Override
public void test(Void result) throws Exception
{
checkExtendedReaders(filePlan, testMap);
assertFalse(extendedSecurityService.hasExtendedSecurity(rmContainer));
// assertEquals(0, extendedSecurityService.getExtendedReaders(rmFolder).size());
checkExtendedReaders(moveRecordCategory, testMap);
checkExtendedReaders(moveRecordFolder, testMap);
checkExtendedReaders(record, testMap);
}
});
}
@SuppressWarnings("unchecked")
private void checkExtendedReaders(NodeRef nodeRef, Map<String, Integer> testMap)
{
assertTrue(extendedSecurityService.hasExtendedSecurity(nodeRef));
Map<String, Integer> readersMap = (Map<String,Integer>)nodeService.getProperty(nodeRef, PROP_READERS);
assertNotNull(readersMap);
assertEquals(testMap.size(), readersMap.size());
for (Map.Entry<String, Integer> entry: testMap.entrySet())
{
assertTrue(readersMap.containsKey(entry.getKey()));
assertEquals(entry.getKey(), entry.getValue(), readersMap.get(entry.getKey()));
}
Set<String> readers = extendedSecurityService.getExtendedReaders(nodeRef);
assertNotNull(readers);
assertEquals(testMap.size(), readers.size());
}
}

View File

@@ -0,0 +1,524 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.role.FilePlanRoleService;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.AccessStatus;
import org.springframework.extensions.webscripts.GUID;
/**
* File plan permission service unit test
*
* @author Roy Wetherall
* @since 2.1
*/
public class FilePlanPermissionServiceImplTest extends BaseRMTestCase
{
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#isUserTest()
*/
@Override
protected boolean isUserTest()
{
return true;
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#isRecordTest()
*/
@Override
protected boolean isRecordTest()
{
return true;
}
/**
* Helper to create test user
*/
private String createTestUser()
{
return doTestInTransaction(new Test<String>()
{
@Override
public String run()
{
String userName = GUID.generate();
createPerson(userName);
filePlanRoleService.assignRoleToAuthority(filePlan, FilePlanRoleService.ROLE_USER, userName);
return userName;
}
}, AuthenticationUtil.getSystemUserName());
}
/**
* Helper to set permission
*/
private void setPermission(final NodeRef nodeRef, final String userName, final String permission)
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
filePlanPermissionService.setPermission(nodeRef, userName, permission);
return null;
}
});
}
/**
* Helper to delete permission
*/
private void deletePermission(final NodeRef nodeRef, final String userName, final String permission)
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
filePlanPermissionService.deletePermission(nodeRef, userName, permission);
return null;
}
});
}
/**
* test set/delete permissions on file plan
*/
public void testSetDeletePermissionFilePlan() throws Exception
{
String userName = createTestUser();
assertPermissions(userName,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.DENIED, // category read
AccessStatus.DENIED, // category file
AccessStatus.DENIED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.DENIED, // record read
AccessStatus.DENIED); // record file
setPermission(filePlan, userName, RMPermissionModel.FILING);
assertPermissions(userName,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.ALLOWED, // fileplan file
AccessStatus.ALLOWED, // category read
AccessStatus.ALLOWED, // category file
AccessStatus.ALLOWED, // record folder read
AccessStatus.ALLOWED, // record folder file
AccessStatus.ALLOWED, // record read
AccessStatus.ALLOWED); // record file
deletePermission(filePlan, userName, RMPermissionModel.FILING);
assertPermissions(userName,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.DENIED, // category read
AccessStatus.DENIED, // category file
AccessStatus.DENIED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.DENIED, // record read
AccessStatus.DENIED); // record file
//what happens if we try and remove READ for a normal user on the file plan ???
deletePermission(filePlan, userName, RMPermissionModel.READ_RECORDS);
// nothing .. user still has read on file plan .. only removing the user from all roles will remove read on file plan
assertPermissions(userName,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.DENIED, // category read
AccessStatus.DENIED, // category file
AccessStatus.DENIED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.DENIED, // record read
AccessStatus.DENIED); // record file
}
/**
* Test set/delete permission on record categorty
*/
public void testSetDeletePermissionRecordCategory() throws Exception
{
String userName = createTestUser();
assertPermissions(userName,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.DENIED, // category read
AccessStatus.DENIED, // category file
AccessStatus.DENIED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.DENIED, // record read
AccessStatus.DENIED); // record file
setPermission(rmContainer, userName, RMPermissionModel.FILING);
assertPermissions(userName,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.ALLOWED, // category read
AccessStatus.ALLOWED, // category file
AccessStatus.ALLOWED, // record folder read
AccessStatus.ALLOWED, // record folder file
AccessStatus.ALLOWED, // record read
AccessStatus.ALLOWED); // record file
deletePermission(rmContainer, userName, RMPermissionModel.FILING);
assertPermissions(userName,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.DENIED, // category read
AccessStatus.DENIED, // category file
AccessStatus.DENIED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.DENIED, // record read
AccessStatus.DENIED); // record file
}
/**
* Test set/delete permission on record folder
*/
public void testSetDeletePermissionRecordFolder() throws Exception
{
String userName = createTestUser();
assertPermissions(userName,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.DENIED, // category read
AccessStatus.DENIED, // category file
AccessStatus.DENIED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.DENIED, // record read
AccessStatus.DENIED); // record file
setPermission(rmFolder, userName, RMPermissionModel.FILING);
assertPermissions(userName,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.ALLOWED, // category read
AccessStatus.DENIED, // category file
AccessStatus.ALLOWED, // record folder read
AccessStatus.ALLOWED, // record folder file
AccessStatus.ALLOWED, // record read
AccessStatus.ALLOWED); // record file
deletePermission(rmFolder, userName, RMPermissionModel.FILING);
assertPermissions(userName,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.ALLOWED, // category read
AccessStatus.DENIED, // category file
AccessStatus.DENIED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.DENIED, // record read
AccessStatus.DENIED); // record file
}
/**
* Test set/delete permission on record
*/
public void testSetDeletePermissionRecord() throws Exception
{
String userName = createTestUser();
assertPermissions(userName,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.DENIED, // category read
AccessStatus.DENIED, // category file
AccessStatus.DENIED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.DENIED, // record read
AccessStatus.DENIED); // record file
setPermission(recordOne, userName, RMPermissionModel.FILING);
assertPermissions(userName,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.ALLOWED, // category read
AccessStatus.DENIED, // category file
AccessStatus.ALLOWED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.ALLOWED, // record read
AccessStatus.ALLOWED); // record file
deletePermission(recordOne, userName, RMPermissionModel.FILING);
assertPermissions(userName,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.ALLOWED, // category read
AccessStatus.DENIED, // category file
AccessStatus.ALLOWED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.DENIED, // record read
AccessStatus.DENIED); // record file
}
public void testMoveRecord() throws Exception
{
String userOne = createTestUser();
String userTwo = createTestUser();
String userThree = createTestUser();
final NodeRef otherFolder = doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
return recordFolderService.createRecordFolder(rmContainer, "otherFolder");
}
});
assertPermissions(userOne,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.DENIED, // category read
AccessStatus.DENIED, // category file
AccessStatus.DENIED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.DENIED, // record read
AccessStatus.DENIED); // record file
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(otherFolder, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(otherFolder, RMPermissionModel.FILING));
return null;
}
}, userOne);
assertPermissions(userTwo,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.DENIED, // category read
AccessStatus.DENIED, // category file
AccessStatus.DENIED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.DENIED, // record read
AccessStatus.DENIED); // record file
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(otherFolder, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(otherFolder, RMPermissionModel.FILING));
return null;
}
}, userTwo);
assertPermissions(userThree,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.DENIED, // category read
AccessStatus.DENIED, // category file
AccessStatus.DENIED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.DENIED, // record read
AccessStatus.DENIED); // record file
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(otherFolder, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(otherFolder, RMPermissionModel.FILING));
return null;
}
}, userThree);
setPermission(rmFolder, userOne, RMPermissionModel.FILING);
setPermission(otherFolder, userTwo, RMPermissionModel.FILING);
setPermission(recordOne, userThree, RMPermissionModel.FILING);
assertPermissions(userOne,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.ALLOWED, // category read
AccessStatus.DENIED, // category file
AccessStatus.ALLOWED, // record folder read
AccessStatus.ALLOWED, // record folder file
AccessStatus.ALLOWED, // record read
AccessStatus.ALLOWED); // record file
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(otherFolder, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(otherFolder, RMPermissionModel.FILING));
return null;
}
}, userOne);
assertPermissions(userTwo,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.ALLOWED, // category read
AccessStatus.DENIED, // category file
AccessStatus.DENIED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.DENIED, // record read
AccessStatus.DENIED); // record file
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(otherFolder, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(otherFolder, RMPermissionModel.FILING));
return null;
}
}, userTwo);
assertPermissions(userThree,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.ALLOWED, // category read
AccessStatus.DENIED, // category file
AccessStatus.ALLOWED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.ALLOWED, // record read
AccessStatus.ALLOWED); // record file
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(otherFolder, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(otherFolder, RMPermissionModel.FILING));
return null;
}
}, userThree);
// move the record!
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
fileFolderService.move(recordOne, otherFolder, "movedRecord.txt");
return null;
}
});
assertPermissions(userOne,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.ALLOWED, // category read
AccessStatus.DENIED, // category file
AccessStatus.ALLOWED, // record folder read
AccessStatus.ALLOWED, // record folder file
AccessStatus.DENIED, // record read
AccessStatus.DENIED); // record file
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(otherFolder, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(otherFolder, RMPermissionModel.FILING));
return null;
}
}, userOne);
assertPermissions(userTwo,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.ALLOWED, // category read
AccessStatus.DENIED, // category file
AccessStatus.DENIED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.ALLOWED, // record read
AccessStatus.ALLOWED); // record file
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(otherFolder, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(otherFolder, RMPermissionModel.FILING));
return null;
}
}, userTwo);
assertPermissions(userThree,
AccessStatus.ALLOWED, // fileplan read
AccessStatus.DENIED, // fileplan file
AccessStatus.ALLOWED, // category read
AccessStatus.DENIED, // category file
AccessStatus.ALLOWED, // record folder read
AccessStatus.DENIED, // record folder file
AccessStatus.ALLOWED, // record read
AccessStatus.ALLOWED); // record file
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(otherFolder, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(otherFolder, RMPermissionModel.FILING));
return null;
}
}, userThree);
}
/**
* Helper to assert permissions for passed user
*/
private void assertPermissions(final String userName, final AccessStatus ... accessStatus)
{
assertEquals(8, accessStatus.length);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals("Everyone who has a role has read permissions on the file plan",
accessStatus[0], permissionService.hasPermission(filePlan, RMPermissionModel.READ_RECORDS));
assertEquals(accessStatus[1], permissionService.hasPermission(filePlan, RMPermissionModel.FILING));
assertEquals(accessStatus[2], permissionService.hasPermission(rmContainer, RMPermissionModel.READ_RECORDS));
assertEquals(accessStatus[3], permissionService.hasPermission(rmContainer, RMPermissionModel.FILING));
assertEquals(accessStatus[4], permissionService.hasPermission(rmFolder, RMPermissionModel.READ_RECORDS));
assertEquals(accessStatus[5], permissionService.hasPermission(rmFolder, RMPermissionModel.FILING));
assertEquals(accessStatus[6], permissionService.hasPermission(recordOne, RMPermissionModel.READ_RECORDS));
assertEquals(accessStatus[7], permissionService.hasPermission(recordOne, RMPermissionModel.FILING));
return null;
}
}, userName);
}
}

View File

@@ -0,0 +1,222 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.util.HashSet;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.capability.Capability;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.role.FilePlanRoleService;
import org.alfresco.module.org_alfresco_module_rm.role.Role;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
/**
* File plan role service unit test
*
* @author Roy Wetherall
* @since 2.1
*/
public class FilePlanRoleServiceImplTest extends BaseRMTestCase
{
@Override
protected boolean isUserTest()
{
return true;
}
public void testGetAllRolesContainerGroup() throws Exception
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
String allRolesGroup = filePlanRoleService.getAllRolesContainerGroup(filePlan);
assertNotNull(allRolesGroup);
return null;
}
});
}
public void testGetRoles() throws Exception
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
Set<Role> roles = filePlanRoleService.getRoles(filePlan);
assertNotNull(roles);
assertTrue(roles.size() != 0);
Set<Role> rolesIncludingSystemRoles = filePlanRoleService.getRoles(filePlan, true);
assertNotNull(rolesIncludingSystemRoles);
assertTrue(roles.size() != 0);
assertTrue(roles.size() == rolesIncludingSystemRoles.size());
Set<Role> rolesWithoutSystemRoles = filePlanRoleService.getRoles(filePlan, false);
assertNotNull(rolesWithoutSystemRoles);
assertTrue(rolesWithoutSystemRoles.size() != 0);
assertTrue(rolesIncludingSystemRoles.size() > rolesWithoutSystemRoles.size());
assertTrue(rolesIncludingSystemRoles.size() == rolesWithoutSystemRoles.size() + FilePlanRoleService.SYSTEM_ROLES.size());
return null;
}
});
}
public void testRolesByUser() throws Exception
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
Set<Role> roles = filePlanRoleService.getRolesByUser(filePlan, rmUserName);
assertNotNull(roles);
assertEquals(1, roles.size());
Set<Role> rolesIncludingSystemRoles = filePlanRoleService.getRolesByUser(filePlan, rmUserName, true);
assertNotNull(rolesIncludingSystemRoles);
assertEquals(1, rolesIncludingSystemRoles.size());
assertEquals(roles.size(), rolesIncludingSystemRoles.size());
return null;
}
});
}
public void testGetRole() throws Exception
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
Role role = filePlanRoleService.getRole(filePlan, ROLE_NAME_POWER_USER);
assertNotNull(role);
assertEquals(ROLE_NAME_POWER_USER, role.getName());
role = filePlanRoleService.getRole(filePlan, "donkey");
assertNull(role);
return null;
}
});
}
public void testExistsRole() throws Exception
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
assertTrue(filePlanRoleService.existsRole(filePlan, ROLE_NAME_POWER_USER));
assertFalse(filePlanRoleService.existsRole(filePlan, "donkey"));
return null;
}
});
}
public void testCreateUpdateDeleteRole() throws Exception
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
assertFalse(filePlanRoleService.existsRole(filePlan, "Michelle Holt"));
Set<Capability> caps = new HashSet<Capability>(2);
caps.add(capabilityService.getCapability(RMPermissionModel.ACCESS_AUDIT));
caps.add(capabilityService.getCapability(RMPermissionModel.ADD_MODIFY_EVENT_DATES));
Role role = filePlanRoleService.createRole(filePlan, "Michelle Holt", "Michelle Holt", caps);
assertNotNull(role);
assertEquals("Michelle Holt", role.getName());
assertEquals(2, role.getCapabilities().size());
assertTrue(filePlanRoleService.existsRole(filePlan, "Michelle Holt"));
caps.add(capabilityService.getCapability(RMPermissionModel.AUTHORIZE_ALL_TRANSFERS));
role = filePlanRoleService.updateRole(filePlan, "Michelle Holt", "Michelle Wetherall", caps);
assertNotNull(role);
assertEquals("Michelle Holt", role.getName());
assertEquals(3, role.getCapabilities().size());
assertTrue(filePlanRoleService.existsRole(filePlan, "Michelle Holt"));
filePlanRoleService.deleteRole(filePlan, "Michelle Holt");
assertFalse(filePlanRoleService.existsRole(filePlan, "Michelle Holt"));
return null;
}
});
}
/**
* {@link FilePlanRoleService#assignRoleToAuthority(org.alfresco.service.cmr.repository.NodeRef, String, String)}
* {@link FilePlanRoleService#getAuthorities(org.alfresco.service.cmr.repository.NodeRef, String)
*/
public void testAuthorityAssignment() throws Exception
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
Set<Role> roles = filePlanRoleService.getRolesByUser(filePlan, rmUserName);
assertNotNull(roles);
assertEquals(1, roles.size());
Set<String> authorities = filePlanRoleService.getUsersAssignedToRole(filePlan, ROLE_NAME_RECORDS_MANAGER);
assertNotNull(authorities);
assertEquals(1, authorities.size());
authorities = filePlanRoleService.getGroupsAssignedToRole(filePlan, ROLE_NAME_RECORDS_MANAGER);
assertNotNull(authorities);
assertEquals(0, authorities.size());
authorities = filePlanRoleService.getAllAssignedToRole(filePlan, ROLE_NAME_RECORDS_MANAGER);
assertNotNull(authorities);
assertEquals(1, authorities.size());
filePlanRoleService.assignRoleToAuthority(filePlan, ROLE_NAME_RECORDS_MANAGER, rmUserName);
roles = filePlanRoleService.getRolesByUser(filePlan, rmUserName);
assertNotNull(roles);
assertEquals(2, roles.size());
authorities = filePlanRoleService.getUsersAssignedToRole(filePlan, ROLE_NAME_RECORDS_MANAGER);
assertNotNull(authorities);
assertEquals(2, authorities.size());
authorities = filePlanRoleService.getGroupsAssignedToRole(filePlan, ROLE_NAME_RECORDS_MANAGER);
assertNotNull(authorities);
assertEquals(0, authorities.size());
authorities = filePlanRoleService.getAllAssignedToRole(filePlan, ROLE_NAME_RECORDS_MANAGER);
assertNotNull(authorities);
assertEquals(2, authorities.size());
return null;
}
});
}
}

View File

@@ -0,0 +1,537 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanComponentKind;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanService;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.site.SiteVisibility;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.GUID;
/**
* File plan service unit test
*
* @author Roy Wetherall
* @since 2.1
*/
public class FilePlanServiceImplTest extends BaseRMTestCase
{
/**
* Pull in collaboration test data
*/
@Override
protected boolean isCollaborationSiteTest()
{
return true;
}
/**
* {@link FilePlanService#isFilePlan(org.alfresco.service.cmr.repository.NodeRef)}
*/
public void testIsFilePlan()
{
doTestInTransaction(new VoidTest()
{
public void runImpl() throws Exception
{
assertTrue(filePlanService.isFilePlan(filePlan));
assertFalse(filePlanService.isFilePlan(rmContainer));
assertFalse(filePlanService.isFilePlan(dmDocument));
}
});
}
/**
* {@link FilePlanService#getFilePlan(org.alfresco.service.cmr.repository.NodeRef)}
*/
public void testGetFilePlans()
{
doTestInTransaction(new VoidTest()
{
public void runImpl() throws Exception
{
assertEquals(filePlan, filePlanService.getFilePlan(filePlan));
assertEquals(filePlan, filePlanService.getFilePlan(rmContainer));
assertEquals(filePlan, filePlanService.getFilePlan(rmFolder));
assertNull(filePlanService.getFilePlan(dmDocument));
}
});
}
/**
* {@link FilePlanService#getFilePlanBySiteId(String)}
*/
public void testGetFilePlanBySiteId()
{
doTestInTransaction(new VoidTest()
{
public void runImpl() throws Exception
{
assertEquals(filePlan, filePlanService.getFilePlanBySiteId(siteId));
assertNull(filePlanService.getFilePlanBySiteId("rubbish"));
String siteId = GUID.generate();
siteService.createSite("anything", siteId, "title", "descrition", SiteVisibility.PUBLIC);
assertNull(filePlanService.getFilePlanBySiteId(siteId));
}
});
}
/**
* @see FilePlanService#isFilePlanComponent(org.alfresco.service.cmr.repository.NodeRef)
*/
public void testIsFilePlanComponent() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
assertTrue("The rm root container should be a rm component", filePlanService.isFilePlanComponent(filePlan));
assertTrue("The rm container should be a rm component", filePlanService.isFilePlanComponent(rmContainer));
assertTrue("The rm folder should be a rm component", filePlanService.isFilePlanComponent(rmFolder));
return null;
}
});
}
/**
* @see FilePlanService#getFilePlanComponentKind(NodeRef)
*/
public void testGetFilePlanComponentKind() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run() throws Exception
{
return utils.createRecord(rmFolder, "testRecord.txt");
}
@Override
public void test(NodeRef result) throws Exception
{
assertEquals(FilePlanComponentKind.FILE_PLAN, filePlanService.getFilePlanComponentKind(filePlan));
assertEquals(FilePlanComponentKind.RECORD_CATEGORY, filePlanService.getFilePlanComponentKind(rmContainer));
assertEquals(FilePlanComponentKind.RECORD_FOLDER, filePlanService.getFilePlanComponentKind(rmFolder));
assertEquals(FilePlanComponentKind.RECORD, filePlanService.getFilePlanComponentKind(result));
// TODO HOLD and TRANSFER
assertNull(filePlanService.getFilePlanComponentKind(folder));
}
});
}
/**
* @see FilePlanService#isRecordCategory(NodeRef)
*/
public void testIsRecordCategory() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
assertFalse("This should not be a record category.", filePlanService.isRecordCategory(filePlan));
assertTrue("This is a record category.", filePlanService.isRecordCategory(rmContainer));
assertFalse("This should not be a record category.", filePlanService.isRecordCategory(rmFolder));
return null;
}
});
}
/**
* @see FilePlanService#createFilePlan(org.alfresco.service.cmr.repository.NodeRef, String)
* @see FilePlanService#createFilePlan(org.alfresco.service.cmr.repository.NodeRef, String, org.alfresco.service.namespace.QName)
*/
public void testCreateFilePlan() throws Exception
{
// Create default type of root
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
String id = setString("id", GUID.generate());
return filePlanService.createFilePlan(folder, id);
}
@Override
public void test(NodeRef result)
{
assertNotNull("Unable to create records management root", result);
basicRMContainerCheck(result, getString("id"), TYPE_FILE_PLAN);
}
});
// Create specific type of root
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
String id = setString("id", GUID.generate());
return filePlanService.createFilePlan(folder, id, TYPE_FILE_PLAN);
}
@Override
public void test(NodeRef result)
{
assertNotNull("Unable to create records management root", result);
basicRMContainerCheck(result, getString("id"), TYPE_FILE_PLAN);
}
});
// Failure: creating root in existing hierarchy
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
filePlanService.createFilePlan(rmContainer, GUID.generate());
}
});
// Failure: type no extended from root container
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
filePlanService.createFilePlan(folder, GUID.generate(), TYPE_FOLDER);
}
});
}
/**
* A basic test of a records management container
*
* @param nodeRef node reference
* @param name name of the container
* @param type the type of container
*/
private void basicRMContainerCheck(NodeRef nodeRef, String name, QName type)
{
// Check the basic details
assertEquals(name, nodeService.getProperty(nodeRef, PROP_NAME));
assertNotNull("RM id has not been set", nodeService.getProperty(nodeRef, PROP_IDENTIFIER));
assertEquals(type, nodeService.getType(nodeRef));
}
/**
* @see FilePlanService#createRecordCategory(NodeRef, String)
* @see FilePlanService#createRecordCategory(NodeRef, String, org.alfresco.service.namespace.QName)
*/
public void testCreateRecordCategory() throws Exception
{
// Create container (in root)
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
String id = setString("id", GUID.generate());
return filePlanService.createRecordCategory(filePlan, id);
}
@Override
public void test(NodeRef result)
{
assertNotNull("Unable to create records management container", result);
basicRMContainerCheck(result, getString("id"), TYPE_RECORD_CATEGORY);
}
});
// Create container (in container)
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
String id = setString("id", GUID.generate());
return filePlanService.createRecordCategory(rmContainer, id);
}
@Override
public void test(NodeRef result)
{
assertNotNull("Unable to create records management container", result);
basicRMContainerCheck(result, getString("id"), TYPE_RECORD_CATEGORY);
}
});
// TODO need a custom type of container!
// Create container of a given type
// doTestInTransaction(new Test<NodeRef>()
// {
// @Override
// public NodeRef run()
// {
// String id = setString("id", GUID.generate());
// return rmService.createRecordCategory(filePlan, id, TYPE_RECORD_SERIES);
// }
//
// @Override
// public void test(NodeRef result)
// {
// assertNotNull("Unable to create records management container", result);
// basicRMContainerCheck(result, getString("id"), TYPE_RECORD_SERIES);
// }
// });
// Fail Test: parent is not a container
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
filePlanService.createRecordCategory(folder, GUID.generate());
}
});
// Fail Test: type is not a sub-type of rm:recordsManagementContainer
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
filePlanService.createRecordCategory(filePlan, GUID.generate(), TYPE_FOLDER);
}
});
}
/**
* @see FilePlanService#getAllContained(NodeRef)
* @see FilePlanService#getAllContained(NodeRef, boolean)
*/
public void testGetAllContained() throws Exception
{
// Get all contained test
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// Add to the test data
NodeRef series = filePlanService.createRecordCategory(rmContainer, "rmSeries");
NodeRef seriesChildFolder = recordFolderService.createRecordFolder(series, "seriesRecordFolder");
NodeRef seriesChildContainer = filePlanService.createRecordCategory(series, "childContainer");
// Put in model
setNodeRef("series", series);
setNodeRef("seriesChildFolder", seriesChildFolder);
setNodeRef("seriesChildContainer", seriesChildContainer);
return null;
}
@Override
public void test(Void result) throws Exception
{
List<NodeRef> nodes = filePlanService.getAllContained(rmContainer);
assertNotNull(nodes);
assertEquals(2, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
assertTrue(nodes.contains(rmFolder));
nodes = filePlanService.getAllContained(rmContainer, false);
assertNotNull(nodes);
assertEquals(2, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
assertTrue(nodes.contains(rmFolder));
nodes = filePlanService.getAllContained(rmContainer, true);
assertNotNull(nodes);
assertEquals(4, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
assertTrue(nodes.contains(rmFolder));
assertTrue(nodes.contains(getNodeRef("seriesChildFolder")));
assertTrue(nodes.contains(getNodeRef("seriesChildContainer")));
}
});
// Failure: call on record folder
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
filePlanService.getAllContained(rmFolder);
}
});
}
/**
* @see FilePlanService#getContainedRecordCategories(NodeRef)
* @see FilePlanService#getContainedRecordCategories(NodeRef, boolean)
*/
public void testGetContainedRecordCategories() throws Exception
{
// Test getting all contained containers
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// Add to the test data
NodeRef series = filePlanService.createRecordCategory(rmContainer, "rmSeries");
NodeRef seriesChildFolder = recordFolderService.createRecordFolder(series, "seriesRecordFolder");
NodeRef seriesChildContainer = filePlanService.createRecordCategory(series, "childContainer");
// Put in model
setNodeRef("series", series);
setNodeRef("seriesChildFolder", seriesChildFolder);
setNodeRef("seriesChildContainer", seriesChildContainer);
return null;
}
@Override
public void test(Void result) throws Exception
{
List<NodeRef> nodes = filePlanService.getContainedRecordCategories(rmContainer);
assertNotNull(nodes);
assertEquals(1, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
nodes = filePlanService.getContainedRecordCategories(rmContainer, false);
assertNotNull(nodes);
assertEquals(1, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
nodes = filePlanService.getContainedRecordCategories(rmContainer, true);
assertNotNull(nodes);
assertEquals(2, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
assertTrue(nodes.contains(getNodeRef("seriesChildContainer")));
}
});
// Failure: call on record folder
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
filePlanService.getContainedRecordCategories(rmFolder);
}
});
}
/**
* @see FilePlanService#getContainedRecordFolders(NodeRef)
* @see FilePlanService#getContainedRecordFolders(NodeRef, boolean)
*/
public void testGetContainedRecordFolders() throws Exception
{
// Test getting all contained record folders
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// Add to the test data
NodeRef series = filePlanService.createRecordCategory(rmContainer, "rmSeries");
NodeRef seriesChildFolder = recordFolderService.createRecordFolder(series, "seriesRecordFolder");
NodeRef seriesChildContainer = filePlanService.createRecordCategory(series, "childContainer");
// Put in model
setNodeRef("series", series);
setNodeRef("seriesChildFolder", seriesChildFolder);
setNodeRef("seriesChildContainer", seriesChildContainer);
return null;
}
@Override
public void test(Void result) throws Exception
{
List<NodeRef> nodes = filePlanService.getContainedRecordFolders(rmContainer);
assertNotNull(nodes);
assertEquals(1, nodes.size());
assertTrue(nodes.contains(rmFolder));
nodes = filePlanService.getContainedRecordFolders(rmContainer, false);
assertNotNull(nodes);
assertEquals(1, nodes.size());
assertTrue(nodes.contains(rmFolder));
nodes = filePlanService.getContainedRecordFolders(rmContainer, true);
assertNotNull(nodes);
assertEquals(2, nodes.size());
assertTrue(nodes.contains(rmFolder));
assertTrue(nodes.contains(getNodeRef("seriesChildFolder")));
}
});
// Failure: call on record folder
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
filePlanService.getContainedRecordFolders(rmFolder);
}
});
}
/**
* Test to create a simple multi-hierarchy record taxonomy
*/
public void testCreateSimpleHierarchy()
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// Create 3 level hierarchy
NodeRef levelOne = setNodeRef("container1", filePlanService.createRecordCategory(filePlan, "container1"));
assertNotNull("Unable to create container", levelOne);
NodeRef levelTwo = setNodeRef("container2", filePlanService.createRecordCategory(levelOne, "container2"));
assertNotNull("Unable to create container", levelTwo);
NodeRef levelThree = setNodeRef("container3", filePlanService.createRecordCategory(levelTwo, "container3"));
assertNotNull("Unable to create container", levelThree);
NodeRef levelThreeRecordFolder = setNodeRef("recordFolder3", recordFolderService.createRecordFolder(levelThree, "recordFolder3"));
assertNotNull("Unable to create record folder", levelThreeRecordFolder);
return null;
}
@Override
public void test(Void result)
{
// Test that the hierarchy has been created correctly
basicRMContainerCheck(getNodeRef("container1"), "container1", TYPE_RECORD_CATEGORY);
basicRMContainerCheck(getNodeRef("container2"), "container2", TYPE_RECORD_CATEGORY);
basicRMContainerCheck(getNodeRef("container3"), "container3", TYPE_RECORD_CATEGORY);
basicRMContainerCheck(getNodeRef("recordFolder3"), "recordFolder3", TYPE_RECORD_FOLDER);
// TODO need to check that the parents and children can be retrieved correctly
}
});
}
}

View File

@@ -0,0 +1,225 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.service.cmr.repository.NodeRef;
/**
* Freeze service implementation test.
*
* @author Tuna Aksoy
* @since 2.1
*/
public class FreezeServiceImplTest extends BaseRMTestCase
{
@Override
protected boolean isRecordTest()
{
return true;
}
/**
* Test freeze service methods
*/
public void testFreezeService() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
assertTrue(recordService.isRecord(recordOne));
assertTrue(recordService.isRecord(recordTwo));
assertTrue(recordService.isRecord(recordThree));
assertTrue(recordService.isRecord(recordFour));
assertTrue(filePlanService.isFilePlanComponent(recordOne));
assertTrue(filePlanService.isFilePlanComponent(recordTwo));
assertTrue(filePlanService.isFilePlanComponent(recordThree));
assertTrue(filePlanService.isFilePlanComponent(recordFour));
// Freeze a record
freezeService.freeze("FreezeReason", recordOne);
assertTrue(freezeService.hasFrozenChildren(rmFolder));
// Check the hold exists
Set<NodeRef> holdAssocs = freezeService.getHolds(filePlan);
assertNotNull(holdAssocs);
assertEquals(1, holdAssocs.size());
NodeRef holdNodeRef = holdAssocs.iterator().next();
assertTrue(freezeService.isHold(holdNodeRef));
assertEquals("FreezeReason", freezeService.getReason(holdNodeRef));
Set<NodeRef> frozenNodes = freezeService.getFrozen(holdNodeRef);
assertNotNull(frozenNodes);
assertEquals(1, frozenNodes.size());
// Check the nodes are frozen
assertTrue(freezeService.isFrozen(recordOne));
assertNotNull(freezeService.getFreezeDate(recordOne));
assertNotNull(freezeService.getFreezeInitiator(recordOne));
assertFalse(freezeService.isFrozen(recordTwo));
assertFalse(freezeService.isFrozen(recordThree));
// Update the freeze reason
freezeService.updateReason(holdNodeRef, "NewFreezeReason");
// Check the hold has been updated
assertEquals("NewFreezeReason", freezeService.getReason(holdNodeRef));
// Freeze a number of records
Set<NodeRef> records = new HashSet<NodeRef>();
records.add(recordOne);
records.add(recordTwo);
records.add(recordThree);
NodeRef newHold = freezeService.freeze("Freeze a set of nodes", records);
assertNotNull(newHold);
assertTrue(freezeService.isHold(newHold));
// Check the holds exist
holdAssocs = freezeService.getHolds(filePlan);
assertNotNull(holdAssocs);
assertEquals(2, holdAssocs.size());
for (NodeRef hold : holdAssocs)
{
String reason = freezeService.getReason(hold);
if (reason.equals("Freeze a set of nodes"))
{
assertEquals(newHold, hold);
frozenNodes = freezeService.getFrozen(hold);
assertNotNull(frozenNodes);
assertEquals(3, frozenNodes.size());
}
else if (reason.equals("NewFreezeReason"))
{
frozenNodes = freezeService.getFrozen(hold);
assertNotNull(frozenNodes);
assertEquals(1, frozenNodes.size());
}
else
{
throw new AlfrescoRuntimeException("The reason '" + reason + "' was not found in the existing holds.");
}
}
// Check the nodes are frozen
final List<NodeRef> testRecords = Arrays.asList(new NodeRef[]{recordOne, recordTwo, recordThree});
for (NodeRef nr : testRecords)
{
assertTrue(freezeService.isFrozen(nr));
assertNotNull(freezeService.getFreezeDate(nr));
assertNotNull(freezeService.getFreezeInitiator(nr));
}
// Unfreeze a node
freezeService.unFreeze(recordThree);
// Check the holds
holdAssocs = freezeService.getHolds(filePlan);
assertNotNull(holdAssocs);
assertEquals(2, holdAssocs.size());
for (NodeRef hold : holdAssocs)
{
String reason = freezeService.getReason(hold);
if (reason.equals("Freeze a set of nodes"))
{
frozenNodes = freezeService.getFrozen(hold);
assertNotNull(frozenNodes);
assertEquals(2, frozenNodes.size());
}
else if (reason.equals("NewFreezeReason"))
{
frozenNodes = freezeService.getFrozen(hold);
assertNotNull(frozenNodes);
assertEquals(1, frozenNodes.size());
}
else
{
throw new AlfrescoRuntimeException("The reason '" + reason + "' was not found in the existing holds.");
}
}
// Check the nodes are frozen
assertTrue(freezeService.isFrozen(recordOne));
assertNotNull(freezeService.getFreezeDate(recordOne));
assertNotNull(freezeService.getFreezeInitiator(recordOne));
assertTrue(freezeService.isFrozen(recordTwo));
assertNotNull(freezeService.getFreezeDate(recordTwo));
assertNotNull(freezeService.getFreezeInitiator(recordTwo));
assertFalse(freezeService.isFrozen(recordThree));
assertFalse(freezeService.isFrozen(recordFour));
// Relinquish the first hold
holdNodeRef = holdAssocs.iterator().next();
freezeService.relinquish(holdNodeRef);
// Check the existing hold
holdAssocs = freezeService.getHolds(filePlan);
assertNotNull(holdAssocs);
assertEquals(1, holdAssocs.size());
// Relinquish the second hold
holdNodeRef = holdAssocs.iterator().next();
freezeService.unFreeze(freezeService.getFrozen(holdNodeRef));
// All holds should be deleted
holdAssocs = freezeService.getHolds(filePlan);
assertEquals(0, holdAssocs.size());
// Check the nodes are unfrozen
assertFalse(freezeService.isFrozen(recordOne));
assertFalse(freezeService.isFrozen(recordTwo));
assertFalse(freezeService.isFrozen(recordThree));
assertFalse(freezeService.isFrozen(recordFour));
assertFalse(freezeService.hasFrozenChildren(rmFolder));
// Test freezing nodes, adding them to an existing hold
NodeRef hold = freezeService.freeze("AnotherFreezeReason", recordFour);
freezeService.freeze(hold, recordOne);
Set<NodeRef> nodes = new HashSet<NodeRef>();
nodes.add(recordTwo);
nodes.add(recordThree);
freezeService.freeze(hold, nodes);
assertTrue(freezeService.hasFrozenChildren(rmFolder));
// Check the hold
holdAssocs = freezeService.getHolds(filePlan);
assertNotNull(holdAssocs);
assertEquals(1, holdAssocs.size());
// Relinquish the first hold
freezeService.relinquish(holdAssocs.iterator().next());
// Check the nodes are unfrozen
assertFalse(freezeService.isFrozen(recordOne));
assertFalse(freezeService.isFrozen(recordTwo));
assertFalse(freezeService.isFrozen(recordThree));
assertFalse(freezeService.isFrozen(recordFour));
assertFalse(freezeService.hasFrozenChildren(rmFolder));
return null;
}
});
}
}

View File

@@ -0,0 +1,269 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.model.security.ModelAccessDeniedException;
import org.alfresco.module.org_alfresco_module_rm.model.security.ModelSecurityService;
import org.alfresco.module.org_alfresco_module_rm.model.security.ProtectedAspect;
import org.alfresco.module.org_alfresco_module_rm.model.security.ProtectedProperty;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.service.namespace.QName;
/**
* Model security service test.
*
* @author Roy Wetherall
* @since 2.1
*/
public class ModelSecurityServiceImplTest extends BaseRMTestCase
{
private static final QName CUSTOM_ASPECT = QName.createQName("http://www.alfresco.org/model/rmtest/1.0", "customAspect");
private static final QName CUSTOM_PROTECTED_ASPECT = QName.createQName("http://www.alfresco.org/model/rmtest/1.0", "customProtectedAspect");
private static final QName CUSTOM_PROPERTY = QName.createQName("http://www.alfresco.org/model/rmtest/1.0", "customProperty");
private static final QName CUSTOM_PROTECTED_PROPERTY = QName.createQName("http://www.alfresco.org/model/rmtest/1.0", "customProtectedProperty");
/** Model security service */
private ModelSecurityService modelSecurityService;
private boolean enabled;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#isUserTest()
*/
@Override
protected boolean isUserTest()
{
return true;
}
@Override
protected boolean isFillingForAllUsers()
{
return true;
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#initServices()
*/
@Override
protected void initServices()
{
super.initServices();
modelSecurityService = (ModelSecurityService)applicationContext.getBean("ModelSecurityService");
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#setupTestDataImpl()
*/
@Override
protected void setupTestDataImpl()
{
super.setupTestDataImpl();
enabled = modelSecurityService.isEnabled();
modelSecurityService.setEnabled(true);
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#tearDownImpl()
*/
@Override
protected void tearDownImpl()
{
super.tearDownImpl();
modelSecurityService.setEnabled(enabled);
}
/**
* test - getProtectedAspects(), isProtectedAspect(), getProtectedAspect()
*/
public void testProtectedAspects() throws Exception
{
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
Set<QName> protectedAspects = modelSecurityService.getProtectedAspects();
assertNotNull(protectedAspects);
assertFalse(protectedAspects.isEmpty());
assertTrue(protectedAspects.contains(CUSTOM_PROTECTED_ASPECT));
assertFalse(protectedAspects.contains(CUSTOM_ASPECT));
assertTrue(modelSecurityService.isProtectedAspect(CUSTOM_PROTECTED_ASPECT));
assertFalse(modelSecurityService.isProtectedAspect(CUSTOM_ASPECT));
ProtectedAspect protectedAspect = modelSecurityService.getProtectedAspect(CUSTOM_ASPECT);
assertNull(protectedAspect);
protectedAspect = modelSecurityService.getProtectedAspect(CUSTOM_PROTECTED_ASPECT);
assertNotNull(protectedAspect);
assertNotNull(protectedAspect.getQName());
assertNotNull(protectedAspect.getCapabilities());
}
});
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
assertTrue(modelSecurityService.isProtectedAspect(CUSTOM_PROTECTED_ASPECT));
assertFalse(modelSecurityService.canEditProtectedAspect(rmFolder, CUSTOM_PROTECTED_ASPECT));
}
}, powerUserName);
doTestInTransaction(new FailureTest
(
"Normal rm user should not have the permissions to add the protected aspect.",
ModelAccessDeniedException.class
)
{
@Override
public void run() throws Exception
{
// try and add the aspect
nodeService.addAspect(rmFolder, CUSTOM_PROTECTED_ASPECT, null);
}
}, powerUserName);
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
assertTrue(modelSecurityService.canEditProtectedAspect(rmFolder, CUSTOM_PROTECTED_ASPECT));
// try and add the aspect
nodeService.addAspect(rmFolder, CUSTOM_PROTECTED_ASPECT, null);
assertTrue(nodeService.hasAspect(rmFolder, CUSTOM_PROTECTED_ASPECT));
}
}, rmAdminName);
// check protected aspect via removeAspect
doTestInTransaction(new FailureTest
(
"Normal rm user should not have the permissions to remove the custom aspect.",
ModelAccessDeniedException.class
)
{
@Override
public void run() throws Exception
{
nodeService.removeAspect(rmFolder, CUSTOM_PROTECTED_ASPECT);
}
}, powerUserName);
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
nodeService.removeAspect(rmFolder, CUSTOM_PROTECTED_ASPECT);
assertFalse(nodeService.hasAspect(rmFolder, CUSTOM_PROTECTED_ASPECT));
}
}, rmAdminName);
}
/**
* test - getProtectedProperties(), isProtectedProperty(), getProtectedProperty()
*/
public void testProtectedProperties() throws Exception
{
doTestInTransaction(new VoidTest()
{
public void runImpl()
{
Set<QName> protectedProperties = modelSecurityService.getProtectedProperties();
assertNotNull(protectedProperties);
assertFalse(protectedProperties.isEmpty());
assertTrue(protectedProperties.contains(CUSTOM_PROTECTED_PROPERTY));
assertFalse(protectedProperties.contains(CUSTOM_PROPERTY));
assertTrue(modelSecurityService.isProtectedProperty(CUSTOM_PROTECTED_PROPERTY));
assertFalse(modelSecurityService.isProtectedProperty(CUSTOM_PROPERTY));
ProtectedProperty protectedProperty = modelSecurityService.getProtectedProperty(CUSTOM_PROPERTY);
assertNull(protectedProperty);
protectedProperty = modelSecurityService.getProtectedProperty(CUSTOM_PROTECTED_PROPERTY);
assertNotNull(protectedProperty);
assertNotNull(protectedProperty.getQName());
assertNotNull(protectedProperty.getCapabilities());
}
});
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
assertTrue(modelSecurityService.canEditProtectedProperty(rmFolder, CUSTOM_PROTECTED_PROPERTY));
}
}, rmAdminName);
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
assertFalse(modelSecurityService.canEditProtectedProperty(rmFolder, CUSTOM_PROTECTED_PROPERTY));
}
}, powerUserName);
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
assertTrue(modelSecurityService.isProtectedProperty(CUSTOM_PROTECTED_PROPERTY));
assertFalse(modelSecurityService.canEditProtectedProperty(rmFolder, CUSTOM_PROTECTED_PROPERTY));
}
}, powerUserName);
doTestInTransaction(new FailureTest
(
"Should not have the permissions to edit protected property.",
ModelAccessDeniedException.class
)
{
@Override
public void run() throws Exception
{
nodeService.setProperty(rmFolder, CUSTOM_PROTECTED_PROPERTY, "hello");
}
}, powerUserName);
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
assertTrue(modelSecurityService.canEditProtectedProperty(rmFolder, CUSTOM_PROTECTED_PROPERTY));
nodeService.setProperty(rmFolder, CUSTOM_PROTECTED_PROPERTY, "hello");
assertEquals("hello", nodeService.getProperty(rmFolder, CUSTOM_PROTECTED_PROPERTY));
}
}, rmAdminName);
}
}

View File

@@ -0,0 +1,612 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.UserTransaction;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.caveat.RMCaveatConfigService;
import org.alfresco.module.org_alfresco_module_rm.caveat.RMCaveatConfigServiceImpl;
import org.alfresco.module.org_alfresco_module_rm.dod5015.DOD5015Model;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.AuthorityType;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.BaseSpringTest;
import org.alfresco.util.PropertyMap;
/**
* Test of RM Caveat (Admin facing scripts)
*
* @author Mark Rogers
*/
public class RMCaveatConfigServiceImplTest extends BaseSpringTest implements DOD5015Model
{
protected static StoreRef SPACES_STORE = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
private NodeRef filePlan;
private NodeService nodeService;
private TransactionService transactionService;
private RMCaveatConfigService caveatConfigService;
private MutableAuthenticationService authenticationService;
private PersonService personService;
private AuthorityService authorityService;
// example base test data for supplemental markings list
protected final static String NOFORN = "NOFORN"; // Not Releasable to Foreign Nationals/Governments/Non-US Citizens
protected final static String NOCONTRACT = "NOCONTRACT"; // Not Releasable to Contractors or Contractor/Consultants
protected final static String FOUO = "FOUO"; // For Official Use Only
protected final static String FGI = "FGI"; // Foreign Government Information
protected final static String RM_LIST = "rmc:smList"; // existing pre-defined list
protected final static String RM_LIST_ALT = "rmc:anoList";
@Override
protected void onSetUpInTransaction() throws Exception
{
super.onSetUpInTransaction();
// Get the service required in the tests
this.nodeService = (NodeService)this.applicationContext.getBean("NodeService"); // use upper 'N'odeService (to test access config interceptor)
this.authenticationService = (MutableAuthenticationService)this.applicationContext.getBean("AuthenticationService");
this.personService = (PersonService)this.applicationContext.getBean("PersonService");
this.authorityService = (AuthorityService)this.applicationContext.getBean("AuthorityService");
this.caveatConfigService = (RMCaveatConfigServiceImpl)this.applicationContext.getBean("caveatConfigService");
this.transactionService = (TransactionService)this.applicationContext.getBean("TransactionService");
// Set the current security context as admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
// Get the test data
setUpTestData();
}
private void setUpTestData()
{
}
@Override
protected void onTearDownInTransaction() throws Exception
{
try
{
UserTransaction txn = transactionService.getUserTransaction(false);
txn.begin();
this.nodeService.deleteNode(filePlan);
txn.commit();
}
catch (Exception e)
{
// Nothing
//System.out.println("DID NOT DELETE FILE PLAN!");
}
}
@Override
protected void onTearDownAfterTransaction() throws Exception
{
// TODO Auto-generated method stub
super.onTearDownAfterTransaction();
}
public void testSetup()
{
// NOOP
}
/**
* Test of Caveat Config
*
* @throws Exception
*/
public void testAddRMConstraintList() throws Exception
{
setComplete();
endTransaction();
cleanCaveatConfigData();
startNewTransaction();
/**
* Now remove the entire list (rma:smList);
*/
logger.debug("test remove entire list rmc:smList");
caveatConfigService.deleteRMConstraint(RM_LIST);
/**
* Now add the list again
*/
logger.debug("test add back rmc:smList");
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
/**
* Negative test - add a list that already exists
*/
logger.debug("try to create duplicate list rmc:smList");
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
/**
* Negative test - remove a list that does not exist
*/
logger.debug("test remove entire list rmc:smList");
caveatConfigService.deleteRMConstraint(RM_LIST);
try
{
caveatConfigService.deleteRMConstraint(RM_LIST);
fail("unknown constraint should have thrown an exception");
}
catch (Exception e)
{
// expect to go here
}
/**
* Negative test - add a constraint to property that does not exist
*/
logger.debug("test property does not exist");
try
{
caveatConfigService.addRMConstraint("rma:mer", "", new String[0]);
fail("unknown property should have thrown an exception");
}
catch (Exception e)
{
// expect to go here
}
endTransaction();
cleanCaveatConfigData();
}
/**
* Test of addRMConstraintListValue
*
* @throws Exception
*/
public void testAddRMConstraintListValue() throws Exception
{
setComplete();
endTransaction();
cleanCaveatConfigData();
setupCaveatConfigData();
startNewTransaction();
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
/**
* Add a user to the list
*/
List<String> values = new ArrayList<String>();
values.add(NOFORN);
values.add(NOCONTRACT);
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "jrogers", values);
/**
* Add another value to that list
*/
caveatConfigService.addRMConstraintListValue(RM_LIST, "jrogers", FGI);
/**
* Negative test - attempt to add a duplicate value
*/
caveatConfigService.addRMConstraintListValue(RM_LIST, "jrogers", FGI);
/**
* Negative test - attempt to add to a list that does not exist
*/
try
{
caveatConfigService.addRMConstraintListValue(RM_LIST_ALT, "mhouse", FGI);
fail("exception not thrown");
}
catch (Exception re)
{
// should go here
}
/**
* Negative test - attempt to add to a list that does exist and user that does not exist
*/
try
{
caveatConfigService.addRMConstraintListValue(RM_LIST, "mhouse", FGI);
fail("exception not thrown");
}
catch (Exception e)
{
// should go here
}
}
/**
* Test of UpdateRMConstraintListAuthority
*
* @throws Exception
*/
public void testUpdateRMConstraintListAuthority() throws Exception
{
setComplete();
endTransaction();
cleanCaveatConfigData();
setupCaveatConfigData();
startNewTransaction();
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
/**
* Add a user to the list
*/
List<String> values = new ArrayList<String>();
values.add(NOFORN);
values.add(NOCONTRACT);
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "jrogers", values);
/**
* Add to a authority that already exists
* Should replace existing authority
*/
List<String> updatedValues = new ArrayList<String>();
values.add(FGI);
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "jrogers", updatedValues);
/**
* Add a group to the list
*/
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "Engineering", values);
/**
* Add to a list that does not exist
* Should create a new list
*/
caveatConfigService.deleteRMConstraint(RM_LIST);
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "jrogers", values);
/**
* Add to a authority that already exists
* Should replace existing authority
*/
endTransaction();
cleanCaveatConfigData();
}
/**
* Test of RemoveRMConstraintListAuthority
*
* @throws Exception
*/
public void testRemoveRMConstraintListAuthority() throws Exception
{
setComplete();
endTransaction();
cleanCaveatConfigData();
setupCaveatConfigData();
startNewTransaction();
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
List<String> values = new ArrayList<String>();
values.add(FGI);
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "jrogers", values);
/**
* Remove a user from a list
*/
caveatConfigService.removeRMConstraintListAuthority(RM_LIST, "jrogers");
/**
* Negative test - remove a user that does not exist
*/
caveatConfigService.removeRMConstraintListAuthority(RM_LIST, "jrogers");
/**
* Negative test - remove a user from a list that does not exist.
* Should create a new list
*/
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "jrogers", values);
endTransaction();
cleanCaveatConfigData();
}
/**
* Test of Caveat Config
*
* @throws Exception
*/
public void testRMCaveatConfig() throws Exception
{
setComplete();
endTransaction();
cleanCaveatConfigData();
startNewTransaction();
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
List<String> values = new ArrayList<String>();
values.add(NOFORN);
values.add(FOUO);
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "dfranco", values);
values.add(FGI);
values.add(NOCONTRACT);
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "dmartinz", values);
// Test list of allowed values for caveats
List<String> allowedValues = AuthenticationUtil.runAs(new RunAsWork<List<String>>()
{
public List<String> doWork()
{
// get allowed values for given caveat (for current user)
return caveatConfigService.getRMAllowedValues(RM_LIST);
}
}, "dfranco");
assertEquals(2, allowedValues.size());
assertTrue(allowedValues.contains(NOFORN));
assertTrue(allowedValues.contains(FOUO));
allowedValues = AuthenticationUtil.runAs(new RunAsWork<List<String>>()
{
public List<String> doWork()
{
// get allowed values for given caveat (for current user)
return caveatConfigService.getRMAllowedValues(RM_LIST);
}
}, "dmartinz");
assertEquals(4, allowedValues.size());
assertTrue(allowedValues.contains(NOFORN));
assertTrue(allowedValues.contains(NOCONTRACT));
assertTrue(allowedValues.contains(FOUO));
assertTrue(allowedValues.contains(FGI));
/**
//
* Now remove the entire list (rma:smList);
*/
logger.debug("test remove entire list rmc:smList");
caveatConfigService.deleteRMConstraint(RM_LIST);
/**
* Now add the list again
*/
logger.debug("test add back rmc:smList");
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
/**
* Negative test - add a list that already exists
*/
logger.debug("try to create duplicate list rmc:smList");
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
/**
* Negative test - remove a list that does not exist
*/
logger.debug("test remove entire list rmc:smList");
caveatConfigService.deleteRMConstraint(RM_LIST);
try
{
caveatConfigService.deleteRMConstraint(RM_LIST);
fail("unknown constraint should have thrown an exception");
}
catch (Exception e)
{
// expect to go here
}
/**
* Negative test - add a constraint to property that does not exist
*/
logger.debug("test property does not exist");
try
{
caveatConfigService.addRMConstraint("rma:mer", "", new String[0]);
fail("unknown property should have thrown an exception");
}
catch (Exception e)
{
// expect to go here
}
endTransaction();
cleanCaveatConfigData();
}
private void cleanCaveatConfigData()
{
startNewTransaction();
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
deleteUser("jrangel");
deleteUser("dmartinz");
deleteUser("jrogers");
deleteUser("hmcneil");
deleteUser("dfranco");
deleteUser("gsmith");
deleteUser("eharris");
deleteUser("bbayless");
deleteUser("mhouse");
deleteUser("aly");
deleteUser("dsandy");
deleteUser("driggs");
deleteUser("test1");
deleteGroup("Engineering");
deleteGroup("Finance");
deleteGroup("test1");
caveatConfigService.updateOrCreateCaveatConfig("{}"); // empty config !
setComplete();
endTransaction();
}
private void setupCaveatConfigData()
{
startNewTransaction();
// Switch to admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
// Create test users/groups (if they do not already exist)
createUser("jrangel");
createUser("dmartinz");
createUser("jrogers");
createUser("hmcneil");
createUser("dfranco");
createUser("gsmith");
createUser("eharris");
createUser("bbayless");
createUser("mhouse");
createUser("aly");
createUser("dsandy");
createUser("driggs");
createUser("test1");
createGroup("Engineering");
createGroup("Finance");
createGroup("test1");
addToGroup("jrogers", "Engineering");
addToGroup("dfranco", "Finance");
// not in grouo to start with - added later
//addToGroup("gsmith", "Engineering");
//URL url = AbstractContentTransformerTest.class.getClassLoader().getResource("testCaveatConfig2.json"); // from test-resources
//assertNotNull(url);
//File file = new File(url.getFile());
//assertTrue(file.exists());
//caveatConfigService.updateOrCreateCaveatConfig(file);
setComplete();
endTransaction();
}
protected void createUser(String userName)
{
if (! authenticationService.authenticationExists(userName))
{
authenticationService.createAuthentication(userName, "PWD".toCharArray());
}
if (! personService.personExists(userName))
{
PropertyMap ppOne = new PropertyMap(4);
ppOne.put(ContentModel.PROP_USERNAME, userName);
ppOne.put(ContentModel.PROP_FIRSTNAME, "firstName");
ppOne.put(ContentModel.PROP_LASTNAME, "lastName");
ppOne.put(ContentModel.PROP_EMAIL, "email@email.com");
ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");
personService.createPerson(ppOne);
}
}
protected void deleteUser(String userName)
{
if (personService.personExists(userName))
{
personService.deletePerson(userName);
}
}
protected void createGroup(String groupShortName)
{
createGroup(null, groupShortName);
}
protected void createGroup(String parentGroupShortName, String groupShortName)
{
if (parentGroupShortName != null)
{
String parentGroupFullName = authorityService.getName(AuthorityType.GROUP, parentGroupShortName);
if (authorityService.authorityExists(parentGroupFullName) == false)
{
authorityService.createAuthority(AuthorityType.GROUP, groupShortName, groupShortName, null);
authorityService.addAuthority(parentGroupFullName, groupShortName);
}
}
else
{
authorityService.createAuthority(AuthorityType.GROUP, groupShortName, groupShortName, null);
}
}
protected void deleteGroup(String groupShortName)
{
String groupFullName = authorityService.getName(AuthorityType.GROUP, groupShortName);
if (authorityService.authorityExists(groupFullName) == true)
{
authorityService.deleteAuthority(groupFullName);
}
}
protected void addToGroup(String authorityName, String groupShortName)
{
authorityService.addAuthority(authorityService.getName(AuthorityType.GROUP, groupShortName), authorityName);
}
protected void removeFromGroup(String authorityName, String groupShortName)
{
authorityService.removeAuthority(authorityService.getName(AuthorityType.GROUP, groupShortName), authorityName);
}
}

View File

@@ -0,0 +1,821 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.capability.Capability;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.dod5015.DOD5015Model;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.record.RecordService;
import org.alfresco.module.org_alfresco_module_rm.role.FilePlanRoleService;
import org.alfresco.module.org_alfresco_module_rm.role.Role;
import org.alfresco.module.org_alfresco_module_rm.security.ExtendedReaderDynamicAuthority;
import org.alfresco.module.org_alfresco_module_rm.security.ExtendedWriterDynamicAuthority;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.permissions.AccessDeniedException;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.AccessPermission;
import org.alfresco.service.cmr.security.AccessStatus;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.GUID;
/**
* Records Service Implementation Test
*
* @author Roy Wetherall
* @author Tuna Aksoy
* @since 2.1
*/
public class RecordServiceImplTest extends BaseRMTestCase
{
/**
* This is a user test
*
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#isUserTest()
*/
@Override
protected boolean isUserTest()
{
return true;
}
/**
* This is a record test
*
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#isRecordTest()
*/
@Override
protected boolean isRecordTest()
{
return true;
}
/**
* This is a collaboration site test
*/
@Override
protected boolean isCollaborationSiteTest()
{
return true;
}
/**
* @see RecordService#getRecordMetaDataAspects()
*/
public void testGetRecordMetaDataAspects() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
Set<QName> aspects = recordService.getRecordMetaDataAspects();
assertNotNull(aspects);
assertEquals(6, aspects.size());
assertTrue(aspects.containsAll(getAspectList()));
return null;
}
/**
* Helper method for getting a list of record meta data aspects
*
* @return Record meta data aspects as list
*/
private List<QName> getAspectList()
{
QName[] aspects = new QName[]
{
DOD5015Model.ASPECT_DIGITAL_PHOTOGRAPH_RECORD,
DOD5015Model.ASPECT_PDF_RECORD,
DOD5015Model.ASPECT_WEB_RECORD,
DOD5015Model.ASPECT_SCANNED_RECORD,
ASPECT_RECORD_META_DATA,
DOD5015Model.ASPECT_DOD_5015_RECORD
};
return Arrays.asList(aspects);
}
});
}
/**
* @see RecordService#isRecord(org.alfresco.service.cmr.repository.NodeRef)
*/
public void testIsRecord() throws Exception
{
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl()
{
assertFalse(recordService.isRecord(filePlan));
assertFalse(recordService.isRecord(rmContainer));
assertFalse(recordService.isRecord(rmFolder));
assertTrue(recordService.isRecord(recordOne));
assertTrue(recordService.isRecord(recordDeclaredOne));
}
});
}
/**
* @see RecordService#isDeclared(org.alfresco.service.cmr.repository.NodeRef)
*/
public void testIsDeclared() throws Exception
{
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl()
{
assertFalse(recordService.isRecord(filePlan));
assertFalse(recordService.isRecord(rmContainer));
assertFalse(recordService.isRecord(rmFolder));
assertTrue(recordService.isRecord(recordOne));
assertTrue(recordService.isRecord(recordDeclaredOne));
}
});
}
public void testUnfiled() throws Exception
{
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl()
{
assertFalse(recordService.isFiled(filePlan));
assertFalse(recordService.isFiled(rmContainer));
assertFalse(recordService.isFiled(rmFolder));
assertTrue(recordService.isFiled(recordOne));
assertTrue(recordService.isFiled(recordDeclaredOne));
}
});
}
public void testExtendedWriters() throws Exception
{
final ExtendedReaderDynamicAuthority readerDy = (ExtendedReaderDynamicAuthority)applicationContext.getBean("extendedReaderDynamicAuthority");
final ExtendedWriterDynamicAuthority writerDy = (ExtendedWriterDynamicAuthority)applicationContext.getBean("extendedWriterDynamicAuthority");
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertNull(extendedSecurityService.getExtendedReaders(recordOne));
assertNull(extendedSecurityService.getExtendedWriters(recordOne));
assertFalse(readerDy.hasAuthority(recordOne, dmCollaborator));
assertFalse(writerDy.hasAuthority(recordOne, dmCollaborator));
assertFalse(readerDy.hasAuthority(filePlan, dmCollaborator));
assertFalse(writerDy.hasAuthority(filePlan, dmCollaborator));
return null;
}
}, dmCollaborator);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(recordOne, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(recordOne, RMPermissionModel.FILING));
assertFalse(readerDy.hasAuthority(recordOne, dmCollaborator));
assertFalse(writerDy.hasAuthority(recordOne, dmCollaborator));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(filePlan, RMPermissionModel.VIEW_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(filePlan, RMPermissionModel.EDIT_NON_RECORD_METADATA));
assertFalse(readerDy.hasAuthority(filePlan, dmCollaborator));
assertFalse(writerDy.hasAuthority(filePlan, dmCollaborator));
return null;
}
}, dmCollaborator);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
Set<String> writers = new HashSet<String>(1);
writers.add(dmCollaborator);
extendedSecurityService.addExtendedSecurity(recordOne, null, writers);
assertNull(extendedSecurityService.getExtendedReaders(recordOne));
assertFalse(extendedSecurityService.getExtendedWriters(recordOne).isEmpty());
return null;
}
});
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(recordOne, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(recordOne, RMPermissionModel.FILING));
assertFalse(readerDy.hasAuthority(recordOne, dmCollaborator));
assertTrue(writerDy.hasAuthority(recordOne, dmCollaborator));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(filePlan, RMPermissionModel.VIEW_RECORDS));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(filePlan, RMPermissionModel.EDIT_NON_RECORD_METADATA));
return null;
}
}, dmCollaborator);
}
/**
* @see RecordService#createRecord(org.alfresco.service.cmr.repository.NodeRef,
* org.alfresco.service.cmr.repository.NodeRef)
*/
public void testCreateRecord() throws Exception
{
// show that users without WRITE can not create a record from a document
doTestInTransaction(new FailureTest(
"Can not create a record from a document if you do not have WRITE permissions.",
AccessDeniedException.class)
{
public void run() throws Exception
{
recordService.createRecord(filePlan, dmDocument);
}
}, dmConsumer);
// create record from document
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
NodeRef originalLocation = nodeService.getPrimaryParent(dmDocument).getParentRef();
assertFalse(recordService.isRecord(dmDocument));
assertFalse(extendedSecurityService.hasExtendedSecurity(dmDocument));
checkPermissions(READ_RECORDS, AccessStatus.DENIED, // file plan
AccessStatus.DENIED, // unfiled container
AccessStatus.DENIED, // record category
AccessStatus.DENIED, // record folder
AccessStatus.DENIED); // doc/record
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(filePlan,
RMPermissionModel.VIEW_RECORDS));
checkPermissions(FILING, AccessStatus.DENIED, // file plan
AccessStatus.DENIED, // unfiled container
AccessStatus.DENIED, // record category
AccessStatus.DENIED, // record folder
AccessStatus.DENIED); // doc/record
recordService.createRecord(filePlan, dmDocument);
checkPermissions(READ_RECORDS, AccessStatus.ALLOWED, // file
// plan
AccessStatus.ALLOWED, // unfiled container
AccessStatus.DENIED, // record category
AccessStatus.DENIED, // record folder
AccessStatus.ALLOWED); // doc/record
permissionReport();
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(filePlan,
RMPermissionModel.VIEW_RECORDS));
checkPermissions(FILING, AccessStatus.DENIED, // file plan
AccessStatus.DENIED, // unfiled container
AccessStatus.DENIED, // record category
AccessStatus.DENIED, // record folder
AccessStatus.ALLOWED); // doc/record
assertTrue(recordService.isRecord(dmDocument));
assertTrue(extendedSecurityService.hasExtendedSecurity(dmDocument));
assertFalse(recordService.isFiled(dmDocument));
// show that the record has meta-data about it's original
// location
assertTrue(nodeService.hasAspect(dmDocument, ASPECT_RECORD_ORIGINATING_DETAILS));
assertEquals(originalLocation, nodeService.getProperty(dmDocument, PROP_RECORD_ORIGINATING_LOCATION));
assertFalse(originalLocation == nodeService.getPrimaryParent(dmDocument).getParentRef());
// show that the record is linked to it's original location
assertEquals(2, nodeService.getParentAssocs(dmDocument).size());
// ****
// Capability Tests
// ****
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(filePlan,
RMPermissionModel.VIEW_RECORDS));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(filePlan,
RMPermissionModel.EDIT_NON_RECORD_METADATA));
Capability filling = capabilityService.getCapability("FileRecords");
assertEquals(AccessStatus.DENIED, filling.hasPermission(dmDocument));
Capability editRecordMetadata = capabilityService.getCapability("EditNonRecordMetadata");
assertEquals(AccessStatus.ALLOWED, editRecordMetadata.hasPermission(dmDocument));
Capability updateProperties = capabilityService.getCapability("UpdateProperties");
assertEquals(AccessStatus.ALLOWED, updateProperties.hasPermission(dmDocument));
return null;
}
}, dmCollaborator);
// check the consumer's permissions are correct for the newly created
// document
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
checkPermissions(READ_RECORDS, AccessStatus.ALLOWED, // file
// plan
AccessStatus.ALLOWED, // unfiled container
AccessStatus.DENIED, // record category
AccessStatus.DENIED, // record folder
AccessStatus.ALLOWED); // doc/record
checkPermissions(FILING, AccessStatus.DENIED, // file plan
AccessStatus.DENIED, // unfiled container
AccessStatus.DENIED, // record category
AccessStatus.DENIED, // record folder
AccessStatus.DENIED); // doc/record
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(filePlan,
RMPermissionModel.VIEW_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(filePlan,
RMPermissionModel.EDIT_NON_RECORD_METADATA));
Capability filling = capabilityService.getCapability("FileRecords");
assertEquals(AccessStatus.DENIED, filling.hasPermission(dmDocument));
Capability editRecordMetadata = capabilityService.getCapability("EditNonRecordMetadata");
assertEquals(AccessStatus.DENIED, editRecordMetadata.hasPermission(dmDocument));
Capability updateProperties = capabilityService.getCapability("UpdateProperties");
assertEquals(AccessStatus.DENIED, updateProperties.hasPermission(dmDocument));
return null;
}
}, dmConsumer);
}
private void permissionReport()
{
Set<String> writers = extendedSecurityService.getExtendedWriters(dmDocument);
for (String writer : writers)
{
System.out.println("writer: " + writer);
}
System.out.println("Users assigned to extended writers role:");
Set<String> assignedUsers = filePlanRoleService.getUsersAssignedToRole(filePlan, FilePlanRoleService.ROLE_EXTENDED_WRITERS);
for (String assignedUser : assignedUsers)
{
System.out.println(" ... " + assignedUser);
}
Set<AccessPermission> perms = permissionService.getAllSetPermissions(filePlan);
for (AccessPermission perm : perms)
{
if (perm.getPermission().contains(RMPermissionModel.EDIT_NON_RECORD_METADATA))
{
System.out.println(" ... " + perm.getAuthority() + " - " + perm.getPermission() + " - " + perm.getAccessStatus().toString());
}
}
for (AccessPermission perm : perms)
{
if (perm.getPermission().contains(RMPermissionModel.VIEW_RECORDS))
{
System.out.println(" ... " + perm.getAuthority() + " - " + perm.getPermission() + " - " + perm.getAccessStatus().toString());
}
}
}
public void testCreateRecordNoLink() throws Exception
{
// show that users without WRITE can not create a record from a document
doTestInTransaction(new FailureTest(
"Can not create a record from a document if you do not have WRITE permissions.",
AccessDeniedException.class)
{
public void run() throws Exception
{
recordService.createRecord(filePlan, dmDocument, false);
}
}, dmConsumer);
// create record from document
final NodeRef originalLocation = doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
NodeRef originalLocation = nodeService.getPrimaryParent(dmDocument).getParentRef();
//assertFalse(recordService.isRecord(dmDocument));
//assertFalse(extendedSecurityService.hasExtendedSecurity(dmDocument));
checkPermissions(READ_RECORDS, AccessStatus.DENIED, // file plan
AccessStatus.DENIED, // unfiled container
AccessStatus.DENIED, // record category
AccessStatus.DENIED, // record folder
AccessStatus.DENIED); // doc/record
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(filePlan,
RMPermissionModel.VIEW_RECORDS));
checkPermissions(FILING, AccessStatus.DENIED, // file plan
AccessStatus.DENIED, // unfiled container
AccessStatus.DENIED, // record category
AccessStatus.DENIED, // record folder
AccessStatus.DENIED); // doc/record
recordService.createRecord(filePlan, dmDocument, false);
checkPermissions(READ_RECORDS, AccessStatus.DENIED, // file plan
AccessStatus.DENIED, // unfiled container
AccessStatus.DENIED, // record category
AccessStatus.DENIED, // record folder
AccessStatus.DENIED); // doc/record
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(filePlan,
RMPermissionModel.VIEW_RECORDS));
checkPermissions(FILING, AccessStatus.DENIED, // file plan
AccessStatus.DENIED, // unfiled container
AccessStatus.DENIED, // record category
AccessStatus.DENIED, // record folder
AccessStatus.DENIED); // doc/record
return originalLocation;
}
}, dmCollaborator);
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertTrue(recordService.isRecord(dmDocument));
assertFalse(extendedSecurityService.hasExtendedSecurity(dmDocument));
assertFalse(recordService.isFiled(dmDocument));
// show that the record has meta-data about it's original
// location
assertTrue(nodeService.hasAspect(dmDocument, ASPECT_RECORD_ORIGINATING_DETAILS));
assertEquals(originalLocation, nodeService.getProperty(dmDocument, PROP_RECORD_ORIGINATING_LOCATION));
assertFalse(originalLocation == nodeService.getPrimaryParent(dmDocument).getParentRef());
// show that the record is linked to it's original location
assertEquals(1, nodeService.getParentAssocs(dmDocument).size());
return null;
}
}, rmAdminName);
}
public void testFileNewContent() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
NodeRef record = fileFolderService.create(rmFolder, "test101.txt", TYPE_CONTENT).getNodeRef();
ContentWriter writer = contentService.getWriter(record, PROP_CONTENT, true);
writer.setEncoding("UTF-8");
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
writer.putContent("hello world this is some test content");
return record;
}
@Override
public void test(NodeRef record) throws Exception
{
assertTrue(recordService.isRecord(record));
assertTrue(recordService.isFiled(record));
assertNotNull(nodeService.getProperty(record, PROP_DATE_FILED));
}
});
}
public void xtestFileUnfiledrecord() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run() throws Exception
{
recordService.createRecord(filePlan, dmDocument);
assertTrue(recordService.isRecord(dmDocument));
assertFalse(recordService.isFiled(dmDocument));
assertNull(nodeService.getProperty(dmDocument, PROP_DATE_FILED));
fileFolderService.move(dmDocument, rmFolder, "record.txt");
return dmDocument;
}
@Override
public void test(NodeRef record) throws Exception
{
assertTrue(recordService.isRecord(record));
assertTrue(recordService.isFiled(record));
assertNotNull(nodeService.getProperty(record, PROP_DATE_FILED));
}
});
}
public void testFileDirectlyFromCollab() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run() throws Exception
{
assertNull(nodeService.getProperty(dmDocument, PROP_DATE_FILED));
fileFolderService.move(dmDocument, rmFolder, "record.txt");
return dmDocument;
}
@Override
public void test(NodeRef record) throws Exception
{
assertTrue(recordService.isRecord(record));
assertTrue(recordService.isFiled(record));
assertNotNull(nodeService.getProperty(record, PROP_DATE_FILED));
}
}, AuthenticationUtil.getSystemUserName());
}
private void checkPermissions(String permission, AccessStatus filePlanExpected, AccessStatus unfiledExpected,
AccessStatus recordCatExpected, AccessStatus recordFolderExpected, AccessStatus recordExpected)
{
assertEquals(filePlanExpected, permissionService.hasPermission(filePlan, permission));
assertEquals(unfiledExpected, permissionService.hasPermission(unfiledContainer, permission));
assertEquals(recordCatExpected, permissionService.hasPermission(rmContainer, permission));
assertEquals(recordFolderExpected, permissionService.hasPermission(rmFolder, permission));
assertEquals(recordExpected, permissionService.hasPermission(dmDocument, permission));
}
private String createUserWithCapabilties(final String... capabiltyNames)
{
return doTestInTransaction(new Test<String>()
{
@Override
public String run() throws Exception
{
Role role = utils.createRole(filePlan, GUID.generate(), capabiltyNames);
String userName = GUID.generate();
createPerson(userName);
filePlanRoleService.assignRoleToAuthority(filePlan, role.getName(), userName);
return userName;
}
}, AuthenticationUtil.getSystemUserName());
}
/**
* Test {@link RecordService#isPropertyEditable(NodeRef, QName)}
*/
public void testIsPropertyEditable() throws Exception
{
final String nonRecordMetadata = createUserWithCapabilties(
RMPermissionModel.VIEW_RECORDS,
RMPermissionModel.EDIT_NON_RECORD_METADATA);
final String recordMetadata = createUserWithCapabilties(
RMPermissionModel.VIEW_RECORDS,
RMPermissionModel.EDIT_RECORD_METADATA);
final String declaredRecordMetadata = createUserWithCapabilties(
RMPermissionModel.VIEW_RECORDS,
RMPermissionModel.EDIT_DECLARED_RECORD_METADATA);
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
filePlanPermissionService.setPermission(rmFolder, rmUserName, RMPermissionModel.FILING);
filePlanPermissionService.setPermission(rmFolder, nonRecordMetadata, RMPermissionModel.FILING);
filePlanPermissionService.setPermission(rmFolder, recordMetadata, RMPermissionModel.FILING);
filePlanPermissionService.setPermission(rmFolder, declaredRecordMetadata, RMPermissionModel.FILING);
}
});
// test rmadmin
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
assertTrue(recordService.isPropertyEditable(recordOne, RecordsManagementModel.PROP_LOCATION));
assertTrue(recordService.isPropertyEditable(recordOne, PROP_DESCRIPTION));
assertTrue(recordService.isPropertyEditable(recordDeclaredOne, RecordsManagementModel.PROP_LOCATION));
assertFalse(recordService.isPropertyEditable(recordDeclaredOne, PROP_DESCRIPTION));
}
});
// test normal user
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(recordOne, RMPermissionModel.READ_RECORDS));
assertFalse(recordService.isPropertyEditable(recordOne, RecordsManagementModel.PROP_LOCATION));
assertFalse(recordService.isPropertyEditable(recordOne, PROP_DESCRIPTION));
assertFalse(recordService.isPropertyEditable(recordDeclaredOne, RecordsManagementModel.PROP_LOCATION));
assertFalse(recordService.isPropertyEditable(recordDeclaredOne, PROP_DESCRIPTION));
}
}, rmUserName);
// test undeclared record with edit non-record metadata capability
// test declared record with edit non-record metadata capability
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
assertFalse(recordService.isPropertyEditable(recordOne, RecordsManagementModel.PROP_LOCATION));
assertTrue(recordService.isPropertyEditable(recordOne, PROP_DESCRIPTION));
assertFalse(recordService.isPropertyEditable(recordDeclaredOne, RecordsManagementModel.PROP_LOCATION));
assertFalse(recordService.isPropertyEditable(recordDeclaredOne, PROP_DESCRIPTION));
}
}, nonRecordMetadata);
// test undeclared record with edit record metadata capability
// test declared record with edit record metadata capability
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
assertTrue(recordService.isPropertyEditable(recordOne, RecordsManagementModel.PROP_LOCATION));
assertFalse(recordService.isPropertyEditable(recordOne, PROP_DESCRIPTION));
assertFalse(recordService.isPropertyEditable(recordDeclaredOne, RecordsManagementModel.PROP_LOCATION));
assertFalse(recordService.isPropertyEditable(recordDeclaredOne, PROP_DESCRIPTION));
}
}, recordMetadata);
// test undeclared record with edit declared record metadata capability
// test declared record with edit declared record metadata capability
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
assertFalse(recordService.isPropertyEditable(recordOne, RecordsManagementModel.PROP_LOCATION));
assertFalse(recordService.isPropertyEditable(recordOne, PROP_DESCRIPTION));
assertTrue(recordService.isPropertyEditable(recordDeclaredOne, RecordsManagementModel.PROP_LOCATION));
assertFalse(recordService.isPropertyEditable(recordDeclaredOne, PROP_DESCRIPTION));
}
}, declaredRecordMetadata);
}
public void testRecordPropertiesUpdate() throws Exception
{
final String nonRecordMetadata = createUserWithCapabilties(
RMPermissionModel.VIEW_RECORDS,
RMPermissionModel.EDIT_NON_RECORD_METADATA);
final String recordMetadata = createUserWithCapabilties(
RMPermissionModel.VIEW_RECORDS,
RMPermissionModel.EDIT_RECORD_METADATA);
final String declaredRecordMetadata = createUserWithCapabilties(
RMPermissionModel.VIEW_RECORDS,
RMPermissionModel.EDIT_DECLARED_RECORD_METADATA);
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
filePlanPermissionService.setPermission(rmFolder, rmUserName, RMPermissionModel.FILING);
filePlanPermissionService.setPermission(rmFolder, nonRecordMetadata, RMPermissionModel.FILING);
filePlanPermissionService.setPermission(rmFolder, recordMetadata, RMPermissionModel.FILING);
filePlanPermissionService.setPermission(rmFolder, declaredRecordMetadata, RMPermissionModel.FILING);
}
});
// test rmadmin
canEditProperty(recordOne, ContentModel.PROP_DESCRIPTION, rmAdminName);
canEditProperty(recordOne, RecordsManagementModel.PROP_LOCATION, rmAdminName);
cantEditProperty(recordDeclaredOne, ContentModel.PROP_DESCRIPTION, rmAdminName);
canEditProperty(recordDeclaredOne, RecordsManagementModel.PROP_LOCATION, rmAdminName);
// test normal user
cantEditProperty(recordOne, ContentModel.PROP_DESCRIPTION, rmUserName);
cantEditProperty(recordOne, RecordsManagementModel.PROP_LOCATION, rmUserName);
cantEditProperty(recordDeclaredOne, ContentModel.PROP_DESCRIPTION, rmUserName);
cantEditProperty(recordDeclaredOne, RecordsManagementModel.PROP_LOCATION, rmUserName);
// test undeclared record with edit non-record metadata capability
canEditProperty(recordOne, ContentModel.PROP_DESCRIPTION, nonRecordMetadata);
cantEditProperty(recordOne, RecordsManagementModel.PROP_LOCATION, nonRecordMetadata);
// test declared record with edit non-record metadata capability
cantEditProperty(recordDeclaredOne, ContentModel.PROP_DESCRIPTION, nonRecordMetadata);
cantEditProperty(recordDeclaredOne, RecordsManagementModel.PROP_LOCATION, nonRecordMetadata);
// test undeclared record with edit record metadata capability
cantEditProperty(recordOne, ContentModel.PROP_DESCRIPTION, recordMetadata);
canEditProperty(recordOne, RecordsManagementModel.PROP_LOCATION, recordMetadata);
// test declared record with edit record metadata capability
cantEditProperty(recordDeclaredOne, ContentModel.PROP_DESCRIPTION, recordMetadata);
cantEditProperty(recordDeclaredOne, RecordsManagementModel.PROP_LOCATION, recordMetadata);
// test undeclared record with edit declared record metadata capability
cantEditProperty(recordOne, ContentModel.PROP_DESCRIPTION, declaredRecordMetadata);
cantEditProperty(recordOne, RecordsManagementModel.PROP_LOCATION, declaredRecordMetadata);
// test declared record with edit declared record metadata capability
cantEditProperty(recordDeclaredOne, ContentModel.PROP_DESCRIPTION, declaredRecordMetadata);
canEditProperty(recordDeclaredOne, RecordsManagementModel.PROP_LOCATION, declaredRecordMetadata);
}
private void cantEditProperty(final NodeRef nodeRef, final QName property, String user) throws Exception
{
boolean failure = false;
try
{
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
nodeService.setProperty(nodeRef, property, GUID.generate());
}
}, user);
}
catch (Throwable exception)
{
// expected
failure = true;
}
// assert fail not failure
if (failure == false)
{
fail("Property should not have been editable.");
}
}
private void canEditProperty(final NodeRef nodeRef, final QName property, String user) throws Exception
{
doTestInTransaction(new VoidTest()
{
@Override
public void runImpl() throws Exception
{
nodeService.setProperty(nodeRef, property, GUID.generate());
}
}, user);
}
}

View File

@@ -0,0 +1,289 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.RecordsManagementPolicies;
import org.alfresco.module.org_alfresco_module_rm.RecordsManagementPolicies.BeforeRMActionExecution;
import org.alfresco.module.org_alfresco_module_rm.RecordsManagementPolicies.OnRMActionExecution;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementAction;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionService;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.TestAction;
import org.alfresco.module.org_alfresco_module_rm.test.util.TestAction2;
import org.alfresco.repo.policy.JavaBehaviour;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.policy.Behaviour.NotificationFrequency;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.ApplicationContextHelper;
import org.springframework.context.ApplicationContext;
/**
* Records management action service implementation test
*
* @author Roy Wetherall
*/
public class RecordsManagementActionServiceImplTest extends TestCase
implements RecordsManagementModel,
BeforeRMActionExecution,
OnRMActionExecution
{
private static final String[] CONFIG_LOCATIONS = new String[] {
"classpath:alfresco/application-context.xml",
"classpath:test-context.xml"};
private ApplicationContext ctx;
private ServiceRegistry serviceRegistry;
private TransactionService transactionService;
private RetryingTransactionHelper txnHelper;
private NodeService nodeService;
private RecordsManagementActionService rmActionService;
private PolicyComponent policyComponent;
private NodeRef nodeRef;
private List<NodeRef> nodeRefs;
private boolean beforeMarker;
private boolean onMarker;
private boolean inTest;
@Override
protected void setUp() throws Exception
{
ctx = ApplicationContextHelper.getApplicationContext(CONFIG_LOCATIONS);
this.serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
this.transactionService = serviceRegistry.getTransactionService();
this.txnHelper = transactionService.getRetryingTransactionHelper();
this.nodeService = serviceRegistry.getNodeService();
this.rmActionService = (RecordsManagementActionService)ctx.getBean("RecordsManagementActionService");
this.policyComponent = (PolicyComponent)ctx.getBean("policyComponent");
// Set the current security context as admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
RetryingTransactionCallback<Void> setUpCallback = new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
// Create a node we can use for the tests
NodeRef rootNodeRef = nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
nodeRef = nodeService.createNode(
rootNodeRef,
ContentModel.ASSOC_CHILDREN,
QName.createQName(NamespaceService.CONTENT_MODEL_PREFIX, "temp.txt"),
ContentModel.TYPE_CONTENT).getChildRef();
// Create nodeRef list
nodeRefs = new ArrayList<NodeRef>(5);
for (int i = 0; i < 5; i++)
{
nodeRefs.add(
nodeService.createNode(
rootNodeRef,
ContentModel.ASSOC_CHILDREN,
QName.createQName(NamespaceService.CONTENT_MODEL_PREFIX, "temp.txt"),
ContentModel.TYPE_CONTENT).getChildRef());
}
return null;
}
};
txnHelper.doInTransaction(setUpCallback);
beforeMarker = false;
onMarker = false;
inTest = false;
}
@Override
protected void tearDown()
{
AuthenticationUtil.clearCurrentSecurityContext();
}
public void testGetActions()
{
RetryingTransactionCallback<Void> testCallback = new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
getActionsImpl();
return null;
}
};
txnHelper.doInTransaction(testCallback);
}
private void getActionsImpl()
{
List<RecordsManagementAction> result = this.rmActionService.getRecordsManagementActions();
assertNotNull(result);
Map<String, RecordsManagementAction> resultMap = new HashMap<String, RecordsManagementAction>(8);
for (RecordsManagementAction action : result)
{
resultMap.put(action.getName(), action);
}
assertTrue(resultMap.containsKey(TestAction.NAME));
assertTrue(resultMap.containsKey(TestAction2.NAME));
result = this.rmActionService.getDispositionActions();
resultMap = new HashMap<String, RecordsManagementAction>(8);
for (RecordsManagementAction action : result)
{
resultMap.put(action.getName(), action);
}
assertTrue(resultMap.containsKey(TestAction.NAME));
assertFalse(resultMap.containsKey(TestAction2.NAME));
// get some specific actions and check the label
RecordsManagementAction cutoff = this.rmActionService.getDispositionAction("cutoff");
assertNotNull(cutoff);
assertEquals("Cut off", cutoff.getLabel());
RecordsManagementAction freeze = this.rmActionService.getRecordsManagementAction("freeze");
assertNotNull(freeze);
assertEquals("Freeze", freeze.getLabel());
assertEquals("Freeze", freeze.getLabel());
// test non-existent actions
assertNull(this.rmActionService.getDispositionAction("notThere"));
assertNull(this.rmActionService.getRecordsManagementAction("notThere"));
}
public void testExecution()
{
RetryingTransactionCallback<Void> testCallback = new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
executionImpl();
return null;
}
};
txnHelper.doInTransaction(testCallback);
}
public void beforeRMActionExecution(NodeRef nodeRef, String name, Map<String, Serializable> parameters)
{
if (inTest == true)
{
assertEquals(this.nodeRef, nodeRef);
assertEquals(TestAction.NAME, name);
assertEquals(1, parameters.size());
assertTrue(parameters.containsKey(TestAction.PARAM));
assertEquals(TestAction.PARAM_VALUE, parameters.get(TestAction.PARAM));
beforeMarker = true;
}
}
public void onRMActionExecution(NodeRef nodeRef, String name, Map<String, Serializable> parameters)
{
if (inTest == true)
{
assertEquals(this.nodeRef, nodeRef);
assertEquals(TestAction.NAME, name);
assertEquals(1, parameters.size());
assertTrue(parameters.containsKey(TestAction.PARAM));
assertEquals(TestAction.PARAM_VALUE, parameters.get(TestAction.PARAM));
onMarker = true;
}
}
private void executionImpl()
{
inTest = true;
try
{
policyComponent.bindClassBehaviour(
RecordsManagementPolicies.BEFORE_RM_ACTION_EXECUTION,
this,
new JavaBehaviour(this, "beforeRMActionExecution", NotificationFrequency.EVERY_EVENT));
policyComponent.bindClassBehaviour(
RecordsManagementPolicies.ON_RM_ACTION_EXECUTION,
this,
new JavaBehaviour(this, "onRMActionExecution", NotificationFrequency.EVERY_EVENT));
assertFalse(beforeMarker);
assertFalse(onMarker);
assertFalse(this.nodeService.hasAspect(this.nodeRef, ASPECT_RECORD));
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(TestAction.PARAM, TestAction.PARAM_VALUE);
this.rmActionService.executeRecordsManagementAction(this.nodeRef, TestAction.NAME, params);
assertTrue(beforeMarker);
assertTrue(onMarker);
assertTrue(this.nodeService.hasAspect(this.nodeRef, ASPECT_RECORD));
}
finally
{
inTest = false;
}
}
public void testBulkExecution()
{
RetryingTransactionCallback<Void> testCallback = new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
bulkExecutionImpl();
return null;
}
};
txnHelper.doInTransaction(testCallback);
}
private void bulkExecutionImpl()
{
for (NodeRef nodeRef : this.nodeRefs)
{
assertFalse(this.nodeService.hasAspect(nodeRef, ASPECT_RECORD));
}
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(TestAction.PARAM, TestAction.PARAM_VALUE);
this.rmActionService.executeRecordsManagementAction(this.nodeRefs, TestAction.NAME, params);
for (NodeRef nodeRef : this.nodeRefs)
{
assertTrue(this.nodeService.hasAspect(nodeRef, ASPECT_RECORD));
}
}
}

View File

@@ -0,0 +1,936 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.admin.CustomMetadataException;
import org.alfresco.module.org_alfresco_module_rm.admin.RecordsManagementAdminService;
import org.alfresco.module.org_alfresco_module_rm.RecordsManagementPolicies;
import org.alfresco.module.org_alfresco_module_rm.RecordsManagementPolicies.BeforeCreateReference;
import org.alfresco.module.org_alfresco_module_rm.RecordsManagementPolicies.OnCreateReference;
import org.alfresco.module.org_alfresco_module_rm.caveat.RMListOfValuesConstraint;
import org.alfresco.module.org_alfresco_module_rm.caveat.RMListOfValuesConstraint.MatchLogic;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementCustomModel;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.script.CustomReferenceType;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.repo.policy.JavaBehaviour;
import org.alfresco.repo.policy.Behaviour.NotificationFrequency;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.dictionary.AspectDefinition;
import org.alfresco.service.cmr.dictionary.AssociationDefinition;
import org.alfresco.service.cmr.dictionary.Constraint;
import org.alfresco.service.cmr.dictionary.ConstraintDefinition;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.dictionary.PropertyDefinition;
import org.alfresco.service.cmr.repository.AssociationRef;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.util.Pair;
import org.springframework.util.CollectionUtils;
/**
* This test class tests the definition and use of a custom RM elements at the Java services layer.
*
* @author Neil McErlean, janv, Roy Wetherall
*/
public class RecordsManagementAdminServiceImplTest extends BaseRMTestCase
implements RecordsManagementModel,
BeforeCreateReference,
OnCreateReference
{
private final static long testRunID = System.currentTimeMillis();
private List<QName> createdCustomProperties;
private List<QName> madeCustomisable;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#setUp()
*/
@Override
protected void setUp() throws Exception
{
createdCustomProperties = new ArrayList<QName>();
madeCustomisable = new ArrayList<QName>();
super.setUp();
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#setupTestData()
*/
@Override
protected void setupTestData()
{
super.setupTestData();
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
// As system user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
for (QName createdCustomProperty : createdCustomProperties)
{
rmAdminService.removeCustomPropertyDefinition(createdCustomProperty);
}
for (QName customisable : madeCustomisable)
{
rmAdminService.unmakeCustomisable(customisable);
}
return null;
}
});
super.tearDown();
}
/**
* @see RecordsManagementAdminService#getCustomisable()
*/
public void testGetCustomisable() throws Exception
{
// Get the customisable types
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
Set<QName> list = rmAdminService.getCustomisable();
assertNotNull(list);
assertTrue(list.containsAll(
CollectionUtils.arrayToList(new QName[]
{
ASPECT_RECORD,
TYPE_RECORD_FOLDER,
TYPE_NON_ELECTRONIC_DOCUMENT,
TYPE_RECORD_CATEGORY
})));
return null;
}
});
}
/**
* @see RecordsManagementAdminService#isCustomisable(QName)
*/
public void testIsCustomisable() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
assertFalse(rmAdminService.isCustomisable(TYPE_CONTENT));
assertFalse(rmAdminService.isCustomisable(ASPECT_DUBLINCORE));
assertTrue(rmAdminService.isCustomisable(TYPE_RECORD_FOLDER));
assertTrue(rmAdminService.isCustomisable(ASPECT_RECORD));
return null;
}
});
}
/**
* @see RecordsManagementAdminService#existsCustomProperty(QName)
* @see RecordsManagementAdminService#addCustomPropertyDefinition(QName, QName, String, QName, String, String, String, boolean, boolean, boolean, QName)
* @see RecordsManagementAdminService#addCustomPropertyDefinition(QName, QName, String, QName, String, String)
*/
public void testAddCustomPropertyDefinition() throws Exception
{
// Add property to Record (id specified, short version)
doTestInTransaction(new Test<QName>()
{
@Override
public QName run() throws Exception
{
// Check the property does not exist
assertFalse(rmAdminService.existsCustomProperty(QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, "myRecordProp1")));
return rmAdminService.addCustomPropertyDefinition(
QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, "myRecordProp1"),
ASPECT_RECORD,
"Label1",
DataTypeDefinition.TEXT,
"Title",
"Description");
}
@Override
public void test(QName result) throws Exception
{
try
{
// Check the property QName is correct
assertNotNull(result);
assertEquals(QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, "myRecordProp1"), result);
assertTrue(rmAdminService.existsCustomProperty(result));
// Check that property is available as a custom property
Map<QName, PropertyDefinition> propDefs = rmAdminService.getCustomPropertyDefinitions(ASPECT_RECORD);
assertNotNull(propDefs);
assertTrue(propDefs.containsKey(result));
// Check the property definition
PropertyDefinition propDef = propDefs.get(result);
assertNotNull(propDef);
assertEquals(DataTypeDefinition.TEXT, propDef.getDataType().getName());
assertEquals("Description", propDef.getDescription(dictionaryService));
assertEquals("Label1", propDef.getTitle(dictionaryService));
}
finally
{
// Store the created property for cleanup later
createdCustomProperties.add(result);
}
}
});
// Add property to record (no id, short version)
doTestInTransaction(new Test<QName>()
{
@Override
public QName run() throws Exception
{
return rmAdminService.addCustomPropertyDefinition(
null,
ASPECT_RECORD,
"Label2",
DataTypeDefinition.TEXT,
"Title",
"Description");
}
@Override
public void test(QName result) throws Exception
{
try
{
// Check the property QName is correct
assertNotNull(result);
assertEquals(RecordsManagementCustomModel.RM_CUSTOM_URI, result.getNamespaceURI());
assertTrue(rmAdminService.existsCustomProperty(result));
// Check that property is available as a custom property
Map<QName, PropertyDefinition> propDefs = rmAdminService.getCustomPropertyDefinitions(ASPECT_RECORD);
assertNotNull(propDefs);
assertTrue(propDefs.containsKey(result));
// Check the property definition
PropertyDefinition propDef = propDefs.get(result);
assertNotNull(propDef);
assertEquals(DataTypeDefinition.TEXT, propDef.getDataType().getName());
assertEquals("Description", propDef.getDescription(dictionaryService));
assertEquals("Label2", propDef.getTitle(dictionaryService));
}
finally
{
// Store the created property for cleanup later
createdCustomProperties.add(result);
}
}
});
// Add property to record (long version)
doTestInTransaction(new Test<QName>()
{
@Override
public QName run() throws Exception
{
return rmAdminService.addCustomPropertyDefinition(
null,
ASPECT_RECORD,
"Label3",
DataTypeDefinition.TEXT,
"Title",
"Description",
"default",
false,
false,
false,
null);
}
@Override
public void test(QName result) throws Exception
{
try
{
// Check the property QName is correct
assertNotNull(result);
assertEquals(RecordsManagementCustomModel.RM_CUSTOM_URI, result.getNamespaceURI());
assertTrue(rmAdminService.existsCustomProperty(result));
// Check that property is available as a custom property
Map<QName, PropertyDefinition> propDefs = rmAdminService.getCustomPropertyDefinitions(ASPECT_RECORD);
assertNotNull(propDefs);
//assertEquals(3, propDefs.size());
assertTrue(propDefs.containsKey(result));
// Check the property definition
PropertyDefinition propDef = propDefs.get(result);
assertNotNull(propDef);
assertEquals(DataTypeDefinition.TEXT, propDef.getDataType().getName());
assertEquals("Description", propDef.getDescription(dictionaryService));
assertEquals("Label3", propDef.getTitle(dictionaryService));
assertEquals("default", propDef.getDefaultValue());
assertFalse(propDef.isMandatory());
assertFalse(propDef.isMultiValued());
assertFalse(propDef.isProtected());
}
finally
{
// Store the created property for cleanup later
createdCustomProperties.add(result);
}
}
});
// Failure: Add a property with the same name twice
doTestInTransaction(new FailureTest
(
"Can not create a property with the same id twice",
CustomMetadataException.class
)
{
@Override
public void run() throws Exception
{
rmAdminService.addCustomPropertyDefinition(
QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, "myRecordProp1"),
ASPECT_RECORD,
"Label1",
DataTypeDefinition.TEXT,
"Title",
"Description");
}
});
// Failure: Try and add a property to a type that isn't customisable
doTestInTransaction(new FailureTest
(
"Can not add a custom property to a type that isn't registered as customisable",
CustomMetadataException.class
)
{
@Override
public void run() throws Exception
{
rmAdminService.addCustomPropertyDefinition(
QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, "myContentProp"),
TYPE_CONTENT,
"Label1",
DataTypeDefinition.TEXT,
"Title",
"Description");
}
});
}
/**
* @see RecordsManagementAdminService#makeCustomisable(QName)
*/
public void testMakeCustomisable() throws Exception
{
doTestInTransaction(new Test<QName>()
{
@Override
public QName run() throws Exception
{
// Make a type customisable
assertFalse(rmAdminService.isCustomisable(TYPE_CUSTOM_TYPE));
rmAdminService.makeCustomisable(TYPE_CUSTOM_TYPE);
madeCustomisable.add(TYPE_CUSTOM_TYPE);
assertTrue(rmAdminService.isCustomisable(TYPE_CUSTOM_TYPE));
// Add a custom property
return rmAdminService.addCustomPropertyDefinition(
QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, "myNewProperty"),
TYPE_CUSTOM_TYPE,
"Label",
DataTypeDefinition.TEXT,
"Title",
"Description");
}
@Override
public void test(QName result) throws Exception
{
// Check the property QName is correct
assertNotNull(result);
assertEquals(QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, "myNewProperty"), result);
assertTrue(rmAdminService.existsCustomProperty(result));
// Check that property is available as a custom property
Map<QName, PropertyDefinition> propDefs = rmAdminService.getCustomPropertyDefinitions(TYPE_CUSTOM_TYPE);
assertNotNull(propDefs);
assertEquals(1, propDefs.size());
assertTrue(propDefs.containsKey(result));
// Check the property definition
PropertyDefinition propDef = propDefs.get(result);
assertNotNull(propDef);
assertEquals(DataTypeDefinition.TEXT, propDef.getDataType().getName());
assertEquals("Description", propDef.getDescription(dictionaryService));
assertEquals("Label", propDef.getTitle(dictionaryService));
}
});
doTestInTransaction(new Test<QName>()
{
@Override
public QName run() throws Exception
{
// Make an aspect customisable
assertFalse(rmAdminService.isCustomisable(ASPECT_CUSTOM_ASPECT));
rmAdminService.makeCustomisable(ASPECT_CUSTOM_ASPECT);
madeCustomisable.add(ASPECT_CUSTOM_ASPECT);
assertTrue(rmAdminService.isCustomisable(ASPECT_CUSTOM_ASPECT));
// Add a custom property
return rmAdminService.addCustomPropertyDefinition(
QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, "myNewAspectProperty"),
ASPECT_CUSTOM_ASPECT,
"Label",
DataTypeDefinition.TEXT,
"Title",
"Description");
}
@Override
public void test(QName result) throws Exception
{
// Check the property QName is correct
assertNotNull(result);
assertEquals(QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, "myNewAspectProperty"), result);
assertTrue(rmAdminService.existsCustomProperty(result));
// Check that property is available as a custom property
Map<QName, PropertyDefinition> propDefs = rmAdminService.getCustomPropertyDefinitions(ASPECT_CUSTOM_ASPECT);
assertNotNull(propDefs);
assertEquals(1, propDefs.size());
assertTrue(propDefs.containsKey(result));
// Check the property definition
PropertyDefinition propDef = propDefs.get(result);
assertNotNull(propDef);
assertEquals(DataTypeDefinition.TEXT, propDef.getDataType().getName());
assertEquals("Description", propDef.getDescription(dictionaryService));
assertEquals("Label", propDef.getTitle(dictionaryService));
}
});
}
public void testUseCustomProperty() throws Exception
{
// Create custom property on type and aspect
doTestInTransaction(new Test<QName>()
{
@Override
public QName run() throws Exception
{
rmAdminService.makeCustomisable(TYPE_CUSTOM_TYPE);
madeCustomisable.add(TYPE_CUSTOM_TYPE);
rmAdminService.addCustomPropertyDefinition(
QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, "myNewProperty"),
TYPE_CUSTOM_TYPE,
"Label",
DataTypeDefinition.TEXT,
"Title",
"Description");
rmAdminService.makeCustomisable(ASPECT_CUSTOM_ASPECT);
madeCustomisable.add(ASPECT_CUSTOM_ASPECT);
rmAdminService.addCustomPropertyDefinition(
QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, "myNewAspectProperty"),
ASPECT_CUSTOM_ASPECT,
"Label",
DataTypeDefinition.TEXT,
"Title",
"Description");
return null;
}
});
// Create nodes using custom type and aspect
doTestInTransaction(new Test<QName>()
{
@Override
public QName run() throws Exception
{
NodeRef customInstance1 = nodeService.createNode(
folder,
ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "myCustomInstance1"),
TYPE_CUSTOM_TYPE).getChildRef();
NodeRef customInstance2 = nodeService.createNode(
folder,
ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "myCustomInstance2"),
TYPE_CONTENT).getChildRef();
nodeService.addAspect(customInstance2, ASPECT_CUSTOM_ASPECT, null);
// Assert that both instances have the custom aspects applied
assertTrue(nodeService.hasAspect(customInstance1, QName.createQName(RM_CUSTOM_URI, "rmtcustomTypeCustomProperties")));
assertTrue(nodeService.hasAspect(customInstance2, QName.createQName(RM_CUSTOM_URI, "rmtcustomAspectCustomProperties")));
// Remove the custom aspect
nodeService.removeAspect(customInstance2, ASPECT_CUSTOM_ASPECT);
// Assert the custom property aspect is no longer applied applied
assertTrue(nodeService.hasAspect(customInstance1, QName.createQName(RM_CUSTOM_URI, "rmtcustomTypeCustomProperties")));
assertFalse(nodeService.hasAspect(customInstance2, QName.createQName(RM_CUSTOM_URI, "rmtcustomAspectCustomProperties")));
return null;
}
}, AuthenticationUtil.getSystemUserName());
}
public void testCreateAndUseCustomChildReference() throws Exception
{
long now = System.currentTimeMillis();
createAndUseCustomReference(CustomReferenceType.PARENT_CHILD, null, "superseded" + now, "superseding" + now);
}
public void testCreateAndUseCustomNonChildReference() throws Exception
{
long now = System.currentTimeMillis();
createAndUseCustomReference(CustomReferenceType.BIDIRECTIONAL, "supporting" + now, null, null);
}
private void createAndUseCustomReference(final CustomReferenceType refType, final String label, final String source, final String target) throws Exception
{
final NodeRef testRecord1 = retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
NodeRef result = utils.createRecord(rmFolder, "testRecordA" + System.currentTimeMillis());
return result;
}
});
final NodeRef testRecord2 = retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
NodeRef result = utils.createRecord(rmFolder, "testRecordB" + System.currentTimeMillis());
return result;
}
});
final QName generatedQName = retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<QName>()
{
public QName execute() throws Throwable
{
utils.declareRecord(testRecord1);
utils.declareRecord(testRecord2);
Map <String, Serializable> params = new HashMap<String, Serializable>();
params.put("referenceType", refType.toString());
if (label != null) params.put("label", label);
if (source != null) params.put("source", source);
if (target != null) params.put("target", target);
// Create the reference definition.
QName qNameResult;
if (label != null)
{
// A bidirectional reference
qNameResult = rmAdminService.addCustomAssocDefinition(label);
}
else
{
// A parent/child reference
qNameResult = rmAdminService.addCustomChildAssocDefinition(source, target);
}
System.out.println("Creating new " + refType + " reference definition: " + qNameResult);
System.out.println(" params- label: '" + label + "' source: '" + source + "' target: '" + target + "'");
return qNameResult;
}
});
retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
// Confirm the custom reference is included in the list from adminService.
Map<QName, AssociationDefinition> customRefDefinitions = rmAdminService.getCustomReferenceDefinitions();
AssociationDefinition retrievedRefDefn = customRefDefinitions.get(generatedQName);
assertNotNull("Custom reference definition from adminService was null.", retrievedRefDefn);
assertEquals(generatedQName, retrievedRefDefn.getName());
assertEquals(refType.equals(CustomReferenceType.PARENT_CHILD), retrievedRefDefn.isChild());
// Now we need to use the custom reference.
// So we apply the aspect containing it to our test records.
nodeService.addAspect(testRecord1, ASPECT_CUSTOM_ASSOCIATIONS, null);
QName assocsAspectQName = QName.createQName("rmc:customAssocs", namespaceService);
nodeService.addAspect(testRecord1, assocsAspectQName, null);
if (CustomReferenceType.PARENT_CHILD.equals(refType))
{
nodeService.addChild(testRecord1, testRecord2, generatedQName, generatedQName);
}
else
{
nodeService.createAssociation(testRecord1, testRecord2, generatedQName);
}
return null;
}
});
retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
// Read back the reference value to make sure it was correctly applied.
List<ChildAssociationRef> childAssocs = nodeService.getChildAssocs(testRecord1);
List<AssociationRef> retrievedAssocs = nodeService.getTargetAssocs(testRecord1, RegexQNamePattern.MATCH_ALL);
Object newlyAddedRef = null;
if (CustomReferenceType.PARENT_CHILD.equals(refType))
{
for (ChildAssociationRef caRef : childAssocs)
{
QName refInstanceQName = caRef.getQName();
if (generatedQName.equals(refInstanceQName)) newlyAddedRef = caRef;
}
}
else
{
for (AssociationRef aRef : retrievedAssocs)
{
QName refQName = aRef.getTypeQName();
if (generatedQName.equals(refQName)) newlyAddedRef = aRef;
}
}
assertNotNull("newlyAddedRef was null.", newlyAddedRef);
// Check that the reference has appeared in the data dictionary
AspectDefinition customAssocsAspect = dictionaryService.getAspect(ASPECT_CUSTOM_ASSOCIATIONS);
assertNotNull(customAssocsAspect);
if (CustomReferenceType.PARENT_CHILD.equals(refType))
{
assertNotNull("The customReference is not returned from the dictionaryService.",
customAssocsAspect.getChildAssociations().get(generatedQName));
}
else
{
assertNotNull("The customReference is not returned from the dictionaryService.",
customAssocsAspect.getAssociations().get(generatedQName));
}
return null;
}
});
}
public void testGetAllProperties()
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
// Just dump them out for visual inspection
System.out.println("Available custom properties:");
Map<QName, PropertyDefinition> props = rmAdminService.getCustomPropertyDefinitions();
for (QName prop : props.keySet())
{
System.out.println(" - " + prop.toString());
String propId = props.get(prop).getTitle(dictionaryService);
assertNotNull("null client-id for " + prop, propId);
System.out.println(" " + propId);
}
return null;
}
});
}
public void testGetAllReferences()
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
// Just dump them out for visual inspection
System.out.println("Available custom references:");
Map<QName, AssociationDefinition> references = rmAdminService.getCustomReferenceDefinitions();
for (QName reference : references.keySet())
{
System.out.println(" - " + reference.toString());
System.out.println(" " + references.get(reference).getTitle(dictionaryService));
}
return null;
}
});
}
public void testGetAllConstraints()
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
// Just dump them out for visual inspection
System.out.println("Available custom constraints:");
List<ConstraintDefinition> constraints = rmAdminService.getCustomConstraintDefinitions(RecordsManagementCustomModel.RM_CUSTOM_MODEL);
for (ConstraintDefinition constraint : constraints)
{
System.out.println(" - " + constraint.getName());
System.out.println(" " + constraint.getTitle(dictionaryService));
}
return null;
}
});
}
private boolean beforeMarker = false;
private boolean onMarker = false;
@SuppressWarnings("unused")
private boolean inTest = false;
public void testCreateReference() throws Exception
{
inTest = true;
try
{
// Create the necessary test objects in the db: two records.
final Pair<NodeRef, NodeRef> testRecords = retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Pair<NodeRef, NodeRef>>()
{
public Pair<NodeRef, NodeRef> execute() throws Throwable
{
NodeRef rec1 = utils.createRecord(rmFolder, "testRecordA" + System.currentTimeMillis());
NodeRef rec2 = utils.createRecord(rmFolder, "testRecordB" + System.currentTimeMillis());
Pair<NodeRef, NodeRef> result = new Pair<NodeRef, NodeRef>(rec1, rec2);
return result;
}
});
final NodeRef testRecord1 = testRecords.getFirst();
final NodeRef testRecord2 = testRecords.getSecond();
retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
utils.declareRecord(testRecord1);
utils.declareRecord(testRecord2);
policyComponent.bindClassBehaviour(
RecordsManagementPolicies.BEFORE_CREATE_REFERENCE,
this,
new JavaBehaviour(RecordsManagementAdminServiceImplTest.this, "beforeCreateReference", NotificationFrequency.EVERY_EVENT));
policyComponent.bindClassBehaviour(
RecordsManagementPolicies.ON_CREATE_REFERENCE,
this,
new JavaBehaviour(RecordsManagementAdminServiceImplTest.this, "onCreateReference", NotificationFrequency.EVERY_EVENT));
assertFalse(beforeMarker);
assertFalse(onMarker);
rmAdminService.addCustomReference(testRecord1, testRecord2, CUSTOM_REF_VERSIONS);
assertTrue(beforeMarker);
assertTrue(onMarker);
return null;
}
});
}
finally
{
inTest = false;
}
}
public void beforeCreateReference(NodeRef fromNodeRef, NodeRef toNodeRef, QName reference)
{
beforeMarker = true;
}
public void onCreateReference(NodeRef fromNodeRef, NodeRef toNodeRef, QName reference)
{
onMarker = true;
}
public void testCreateCustomConstraints() throws Exception
{
final int beforeCnt =
retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Integer>()
{
public Integer execute() throws Throwable
{
List<ConstraintDefinition> result = rmAdminService.getCustomConstraintDefinitions(RecordsManagementCustomModel.RM_CUSTOM_MODEL);
assertNotNull(result);
return result.size();
}
});
final String conTitle = "test title - "+testRunID;
final List<String> allowedValues = new ArrayList<String>(3);
allowedValues.add("RED");
allowedValues.add("AMBER");
allowedValues.add("GREEN");
final QName testCon = retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<QName>()
{
public QName execute() throws Throwable
{
String conLocalName = "test-"+testRunID;
final QName result = QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, conLocalName);
rmAdminService.addCustomConstraintDefinition(result, conTitle, true, allowedValues, MatchLogic.AND);
return result;
}
});
// Set the current security context as System - to see allowed values (unless caveat config is also updated for admin)
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
List<ConstraintDefinition> customConstraintDefs = rmAdminService.getCustomConstraintDefinitions(RecordsManagementCustomModel.RM_CUSTOM_MODEL);
assertEquals(beforeCnt+1, customConstraintDefs.size());
boolean found = false;
for (ConstraintDefinition conDef : customConstraintDefs)
{
if (conDef.getName().equals(testCon))
{
assertEquals(conTitle, conDef.getTitle(dictionaryService));
Constraint con = conDef.getConstraint();
assertTrue(con instanceof RMListOfValuesConstraint);
assertEquals("LIST", ((RMListOfValuesConstraint)con).getType());
assertEquals(3, ((RMListOfValuesConstraint)con).getAllowedValues().size());
found = true;
break;
}
}
assertTrue(found);
return null;
}
});
// Set the current security context as admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
allowedValues.clear();
allowedValues.add("RED");
allowedValues.add("YELLOW");
rmAdminService.changeCustomConstraintValues(testCon, allowedValues);
return null;
}
});
// Set the current security context as System - to see allowed values (unless caveat config is also updated for admin)
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
List<ConstraintDefinition> customConstraintDefs = rmAdminService.getCustomConstraintDefinitions(RecordsManagementCustomModel.RM_CUSTOM_MODEL);
assertEquals(beforeCnt+1, customConstraintDefs.size());
boolean found = false;
for (ConstraintDefinition conDef : customConstraintDefs)
{
if (conDef.getName().equals(testCon))
{
assertEquals(conTitle, conDef.getTitle(dictionaryService));
Constraint con = conDef.getConstraint();
assertTrue(con instanceof RMListOfValuesConstraint);
assertEquals("LIST", ((RMListOfValuesConstraint)con).getType());
assertEquals(2, ((RMListOfValuesConstraint)con).getAllowedValues().size());
found = true;
break;
}
}
assertTrue(found);
return null;
}
});
// Set the current security context as admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
// Add custom property to record with test constraint
retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
String propLocalName = "myProp-"+testRunID;
QName dataType = DataTypeDefinition.TEXT;
String propTitle = "My property title";
String description = "My property description";
String defaultValue = null;
boolean multiValued = false;
boolean mandatory = false;
boolean isProtected = false;
QName propName = rmAdminService.addCustomPropertyDefinition(null, ASPECT_RECORD, propLocalName, dataType, propTitle, description, defaultValue, multiValued, mandatory, isProtected, testCon);
createdCustomProperties.add(propName);
return null;
}
});
}
}

View File

@@ -0,0 +1,451 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.audit.RecordsManagementAuditEntry;
import org.alfresco.module.org_alfresco_module_rm.audit.RecordsManagementAuditQueryParameters;
import org.alfresco.module.org_alfresco_module_rm.audit.RecordsManagementAuditService;
import org.alfresco.module.org_alfresco_module_rm.audit.event.AuditEvent;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.EqualsHelper;
import org.alfresco.util.Pair;
/**
* @see RecordsManagementAuditService
*
* @author Derek Hulley
* @author Roy Wetherall
*
* @since 3.2
*/
public class RecordsManagementAuditServiceImplTest extends BaseRMTestCase
implements RMPermissionModel
{
/** Test record */
private NodeRef record;
/** Test start time */
private Date testStartTime;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#setUp()
*/
@Override
protected void setUp() throws Exception
{
super.setUp();
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
// test start time recorded
testStartTime = new Date();
// Stop and clear the log
rmAuditService.stopAuditLog(filePlan);
rmAuditService.clearAuditLog(filePlan);
rmAuditService.startAuditLog(filePlan);
// check that audit service is started
assertTrue(rmAuditService.isAuditLogEnabled(filePlan));
return null;
}
});
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#isUserTest()
*/
@Override
protected boolean isUserTest()
{
return true;
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#setupTestDataImpl()
*/
@Override
protected void setupTestDataImpl()
{
super.setupTestDataImpl();
record = utils.createRecord(rmFolder, "AuditTest.txt");
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#setupTestUsersImpl(org.alfresco.service.cmr.repository.NodeRef)
*/
@Override
protected void setupTestUsersImpl(NodeRef filePlan)
{
super.setupTestUsersImpl(filePlan);
// Give all the users file permission objects
for (String user : testUsers)
{
filePlanPermissionService.setPermission(filePlan, user, FILING);
filePlanPermissionService.setPermission(rmContainer, user, FILING);
}
}
public void testGetAuditEvents()
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
List<AuditEvent> events = rmAuditService.getAuditEvents();
System.out.println("Found audit events:");
for (AuditEvent event : events)
{
System.out.println(" - " + event.getName() + " (" + event.getLabel() + ")");
}
return null;
}
}, rmAdminName);
}
/**
* Test getAuditTrail method and parameter filters.
*/
public void testGetAuditTrail()
{
// show the audit is empty
getAuditTrail(1, rmAdminName);
// make a change
final String updatedProperty = updateTitle(filePlan, rmAdminName);
// show the audit has been updated
List<RecordsManagementAuditEntry> entries = getAuditTrail(3, rmAdminName);
final RecordsManagementAuditEntry entry = entries.get(2);
assertNotNull(entry);
// investigate the contents of the audit entry
doTestInTransaction(new Test<Void>()
{
@SuppressWarnings("unchecked")
@Override
public Void run() throws Exception
{
assertEquals(filePlan, entry.getNodeRef());
String id = (String)nodeService.getProperty(filePlan, PROP_IDENTIFIER);
assertEquals(id, entry.getIdentifier());
Map<QName, Serializable> after = entry.getAfterProperties();
Map<QName, Pair<Serializable, Serializable>> changed = entry.getChangedProperties();
assertTrue(after.containsKey(PROP_TITLE));
assertTrue(changed.containsKey(PROP_TITLE));
Serializable value = ((Map<Locale, Serializable>)after.get(PROP_TITLE)).get(Locale.ENGLISH);
assertEquals(updatedProperty, value);
value = ((Map<Locale, Serializable>)changed.get(PROP_TITLE).getSecond()).get(Locale.ENGLISH);
assertEquals(updatedProperty, value);
return null;
}
}, rmAdminName);
// add some more title updates
updateTitle(rmContainer, rmAdminName);
updateTitle(rmFolder, rmAdminName);
updateTitle(record, rmAdminName);
// show the audit has been updated
getAuditTrail(7, rmAdminName);
// snap shot date
Date snapShot = new Date();
// show the audit results can be limited
RecordsManagementAuditQueryParameters params = new RecordsManagementAuditQueryParameters();
params.setMaxEntries(2);
getAuditTrail(params, 2, rmAdminName);
// test filter by user
updateTitle(rmContainer, recordsManagerName);
updateTitle(rmFolder, recordsManagerName);
updateTitle(record, recordsManagerName);
params = new RecordsManagementAuditQueryParameters();
params.setUser(recordsManagerName);
getAuditTrail(params, 3, rmAdminName);
// test filter by date
params = new RecordsManagementAuditQueryParameters();
params.setDateFrom(snapShot);
getAuditTrail(params, 13, rmAdminName);
params = new RecordsManagementAuditQueryParameters();
params.setDateTo(snapShot);
getAuditTrail(params, 14, rmAdminName);
params.setDateFrom(testStartTime);
getAuditTrail(params, 15, rmAdminName);
// test filter by object
updateTitle(record, rmAdminName);
updateTitle(record, rmAdminName);
updateTitle(record, rmAdminName);
params = new RecordsManagementAuditQueryParameters();
params.setNodeRef(record);
getAuditTrail(params, 5, rmAdminName);
// test filter by event
params = new RecordsManagementAuditQueryParameters();
// params.setEvent("cutoff");
// getAuditTrail(params, 0, rmAdminName);
params.setEvent("Update RM Object");
getAuditTrail(params, 10, rmAdminName);
// test filter by property
// params = new RecordsManagementAuditQueryParameters();
//params.setProperty(PROP_ADDRESSEES);
//getAuditTrail(params, 0, rmAdminName);
// params.setProperty(PROP_TITLE);
// getAuditTrail(params, 10, rmAdminName);
}
/**
* Tests the following methods:
* - start()
* - stop()
* - clear()
* - isEnabled()
* - getDateLastStopped()
* - getDateLastStarted()
*
* @throws InterruptedException
*/
public void testAdminMethods() throws InterruptedException
{
// Stop the audit
rmAuditService.stopAuditLog(filePlan);
Thread.sleep(5000);
List<RecordsManagementAuditEntry> result1 = getAuditTrail(rmAdminName);
assertNotNull(result1);
// Update the fileplan
updateTitle(filePlan, rmAdminName);
Thread.sleep(5000);
// There should be no new audit entries
List<RecordsManagementAuditEntry> result2 = getAuditTrail(rmAdminName);
assertNotNull(result2);
assertEquals(
"Audit results should not have changed after auditing was disabled",
result1.size(), result2.size());
// repeat with a start
rmAuditService.startAuditLog(filePlan);
updateTitle(filePlan, rmAdminName);
Thread.sleep(5000);
List<RecordsManagementAuditEntry> result3 = getAuditTrail(rmAdminName);
assertNotNull(result3);
assertTrue(
"Expected more results after enabling audit",
result3.size() > result1.size());
Thread.sleep(5000);
// Stop and delete all entries
rmAuditService.stopAuditLog(filePlan);
rmAuditService.clearAuditLog(filePlan);
// There should be no entries
List<RecordsManagementAuditEntry> result4 = getAuditTrail(rmAdminName);
assertNotNull(result4);
assertEquals(
"Audit entries should have been cleared",
0, result4.size());
}
// TODO testAuditRMAction
// TODO testGetAuditTrailFile
// TODO testFileAuditTrailAsRecord
public void xtestAuditAuthentication()
{
rmAuditService.stopAuditLog(filePlan);
rmAuditService.clearAuditLog(filePlan);
rmAuditService.startAuditLog(filePlan);
//MutableAuthenticationService authenticationService = serviceRegistry.getAuthenticationService();
//PersonService personService = serviceRegistry.getPersonService();
try
{
personService.deletePerson("baboon");
authenticationService.deleteAuthentication("baboon");
}
catch (Throwable e)
{
// Not serious
}
// Failed login attempt ...
try
{
AuthenticationUtil.pushAuthentication();
authenticationService.authenticate("baboon", "lskdfj".toCharArray());
fail("Expected authentication failure");
}
catch (AuthenticationException e)
{
// Good
}
finally
{
AuthenticationUtil.popAuthentication();
}
rmAuditService.stopAuditLog(filePlan);
List<RecordsManagementAuditEntry> result1 = getAuditTrail(rmAdminName);
// Check that the username is reflected correctly in the results
assertFalse("No audit results were generated for the failed login.", result1.isEmpty());
boolean found = false;
for (RecordsManagementAuditEntry entry : result1)
{
String userName = entry.getUserName();
if (userName.equals("baboon"))
{
found = true;
break;
}
}
assertTrue("Expected to hit failed login attempt for user", found);
// Test successful authentication
try
{
personService.deletePerson("cdickons");
authenticationService.deleteAuthentication("cdickons");
}
catch (Throwable e)
{
// Not serious
}
authenticationService.createAuthentication("cdickons", getName().toCharArray());
Map<QName, Serializable> personProperties = new HashMap<QName, Serializable>();
personProperties.put(ContentModel.PROP_USERNAME, "cdickons");
personProperties.put(ContentModel.PROP_FIRSTNAME, "Charles");
personProperties.put(ContentModel.PROP_LASTNAME, "Dickons");
personService.createPerson(personProperties);
rmAuditService.clearAuditLog(filePlan);
rmAuditService.startAuditLog(filePlan);
try
{
AuthenticationUtil.pushAuthentication();
authenticationService.authenticate("cdickons", getName().toCharArray());
}
finally
{
AuthenticationUtil.popAuthentication();
}
rmAuditService.stopAuditLog(filePlan);
List<RecordsManagementAuditEntry> result2 = getAuditTrail(rmAdminName);
found = false;
for (RecordsManagementAuditEntry entry : result2)
{
String userName = entry.getUserName();
String fullName = entry.getFullName();
if (userName.equals("cdickons") && EqualsHelper.nullSafeEquals(fullName, "Charles Dickons"))
{
found = true;
break;
}
}
assertTrue("Expected to hit successful login attempt for Charles Dickons (cdickons)", found);
}
/** === Helper methods === */
private List<RecordsManagementAuditEntry> getAuditTrail(String asUser)
{
return getAuditTrail(-1, asUser);
}
private List<RecordsManagementAuditEntry> getAuditTrail(final int expectedCount, String asUser)
{
return getAuditTrail(new RecordsManagementAuditQueryParameters(), expectedCount, asUser);
}
private List<RecordsManagementAuditEntry> getAuditTrail(final RecordsManagementAuditQueryParameters params, final int expectedCount, final String asUser)
{
return doTestInTransaction(new Test<List<RecordsManagementAuditEntry>>()
{
@Override
public List<RecordsManagementAuditEntry> run() throws Exception
{
return rmAuditService.getAuditTrail(params);
}
@Override
public void test(List<RecordsManagementAuditEntry> result) throws Exception
{
assertNotNull(result);
if (expectedCount != -1)
{
assertEquals(expectedCount, result.size());
}
}
}, asUser);
}
private String updateTitle(final NodeRef nodeRef, final String asUser)
{
return doTestInTransaction(new Test<String>()
{
@Override
public String run() throws Exception
{
String updatedProperty = "Updated - " + System.currentTimeMillis();
nodeService.setProperty(nodeRef, ContentModel.PROP_TITLE, updatedProperty);
return updatedProperty;
}
}, asUser);
}
}

View File

@@ -0,0 +1,127 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.event.RecordsManagementEvent;
import org.alfresco.module.org_alfresco_module_rm.event.RecordsManagementEventType;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.service.cmr.repository.StoreRef;
/**
* Event service implementation unit test
*
* @author Roy Wetherall
*/
public class RecordsManagementEventServiceImplTest extends BaseRMTestCase implements RecordsManagementModel
{
protected static StoreRef SPACES_STORE = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
private RetryingTransactionHelper transactionHelper;
@Override
protected void setUp() throws Exception
{
super.setUp();
// Get the service required in the tests
this.transactionHelper = (RetryingTransactionHelper)this.applicationContext.getBean("retryingTransactionHelper");
// Set the current security context as admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
}
public void testGetEventTypes()
{
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
List<RecordsManagementEventType> eventTypes = rmEventService.getEventTypes();
assertNotNull(eventTypes);
for (RecordsManagementEventType eventType : eventTypes)
{
System.out.println(eventType.getName() + " - " + eventType.getDisplayLabel());
}
return null;
}
});
}
public void testGetEvents()
{
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
List<RecordsManagementEvent> events = rmEventService.getEvents();
assertNotNull(events);
for (RecordsManagementEvent event : events)
{
System.out.println(event.getName());
}
return null;
}
});
}
public void testAddRemoveEvents()
{
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
List<RecordsManagementEvent> events = rmEventService.getEvents();
assertNotNull(events);
assertFalse(containsEvent(events, "myEvent"));
rmEventService.addEvent("rmEventType.simple", "myEvent", "My Event");
events = rmEventService.getEvents();
assertNotNull(events);
assertTrue(containsEvent(events, "myEvent"));
rmEventService.removeEvent("myEvent");
events = rmEventService.getEvents();
assertNotNull(events);
assertFalse(containsEvent(events, "myEvent"));
return null;
}
});
}
private boolean containsEvent(List<RecordsManagementEvent> events, String eventName)
{
boolean result = false;
for (RecordsManagementEvent event : events)
{
if (eventName.equals(event.getName()) == true)
{
result = true;
break;
}
}
return result;
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.query.RecordsManagementQueryDAO;
import org.alfresco.module.org_alfresco_module_rm.record.RecordService;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
/**
* Records Management Query DAO
*
* @author Roy Wetherall
* @since 2.1
*/
public class RecordsManagementQueryDAOImplTest extends BaseRMTestCase implements RecordsManagementModel
{
protected RecordsManagementQueryDAO queryDAO;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#initServices()
*/
@Override
protected void initServices()
{
super.initServices();
queryDAO = (RecordsManagementQueryDAO)applicationContext.getBean("recordsManagementQueryDAO");
}
/**
* This is a record test
*
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#isRecordTest()
*/
@Override
protected boolean isRecordTest()
{
return true;
}
/**
* @see RecordService#getRecordMetaDataAspects()
*/
public void testGetRecordMetaDataAspects() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
int count = queryDAO.getCountRmaIdentifier("abc-123");
assertEquals(0, count);
String existingID = (String)nodeService.getProperty(recordOne, PROP_IDENTIFIER);
count = queryDAO.getCountRmaIdentifier(existingID);
assertEquals(1, count);
return null;
}
});
}
}

View File

@@ -0,0 +1,309 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.search.RecordsManagementSearchParameters;
import org.alfresco.module.org_alfresco_module_rm.search.SavedSearchDetails;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.util.TestWithUserUtils;
/**
* Search service implementation unit test.
*
* @author Roy Wetherall
*/
@SuppressWarnings("unused")
public class RecordsManagementSearchServiceImplTest extends BaseRMTestCase
{
@Override
protected boolean isMultiHierarchyTest()
{
return true;
}
private static final String SEARCH1 = "search1";
private static final String SEARCH2 = "search2";
private static final String SEARCH3 = "search3";
private static final String SEARCH4 = "search4";
private static final String USER1 = "user1";
private static final String USER2 = "user2";
private NodeRef folderLevelRecordFolder;
private NodeRef recordLevelRecordFolder;
private NodeRef recordOne;
private NodeRef recordTwo;
private NodeRef recordThree;
private NodeRef recordFour;
private NodeRef recordFive;
private NodeRef recordSix;
private int numberOfReports;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#setupTestData()
*/
@Override
protected void setupTestData()
{
super.setupTestData();
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// Create test users
TestWithUserUtils.createUser(USER1, USER1, rootNodeRef, nodeService, authenticationService);
TestWithUserUtils.createUser(USER2, USER2, rootNodeRef, nodeService, authenticationService);
// Count the number of pre-defined reports
List<SavedSearchDetails> searches = rmSearchService.getSavedSearches(siteId);
assertNotNull(searches);
numberOfReports = searches.size();
return null;
}
}, AuthenticationUtil.getSystemUserName());
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#setupMultiHierarchyTestData()
*/
@Override
protected void setupMultiHierarchyTestData()
{
super.setupMultiHierarchyTestData();
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
folderLevelRecordFolder = mhRecordFolder42;
recordLevelRecordFolder = mhRecordFolder43;
recordOne = utils.createRecord(folderLevelRecordFolder, "recordOne.txt", null, "record one - folder level - elephant");
recordTwo = utils.createRecord(folderLevelRecordFolder, "recordTwo.txt", null, "record two - folder level - snake");
recordThree = utils.createRecord(folderLevelRecordFolder, "recordThree.txt", null, "record three - folder level - monkey");
recordFour = utils.createRecord(recordLevelRecordFolder, "recordFour.txt", null, "record four - record level - elephant");
recordFive = utils.createRecord(recordLevelRecordFolder, "recordFive.txt", null, "record five - record level - snake");
recordSix = utils.createRecord(recordLevelRecordFolder, "recordSix.txt", null, "record six - record level - monkey");
return null;
}
}, AuthenticationUtil.getSystemUserName());
}
@Override
protected void tearDown() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// Delete test users
TestWithUserUtils.deleteUser(USER1, USER1, rootNodeRef, nodeService, authenticationService);
TestWithUserUtils.deleteUser(USER2, USER2, rootNodeRef, nodeService, authenticationService);
return null;
}
}, AuthenticationUtil.getSystemUserName());
super.tearDown();
}
public void testSearch()
{
// Full text search
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
String query = "keywords:\"elephant\"";
RecordsManagementSearchParameters params = new RecordsManagementSearchParameters();
params.setIncludeUndeclaredRecords(true);
List<NodeRef> results = rmSearchService.search(siteId, query, params);
assertNotNull(results);
assertEquals(2, results.size());
return null;
}
}, AuthenticationUtil.getSystemUserName());
// Property search
//
}
public void testSaveSearch()
{
// Add some saved searches (as admin user)
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
SavedSearchDetails details1 = rmSearchService.saveSearch(siteId, SEARCH1, "description1", "query1", new RecordsManagementSearchParameters(), true);
checkSearchDetails(details1, siteId, "search1", "description1", "query1", new RecordsManagementSearchParameters(), true);
SavedSearchDetails details2 = rmSearchService.saveSearch(siteId, SEARCH2, "description2", "query2", new RecordsManagementSearchParameters(), false);
checkSearchDetails(details2, siteId, "search2", "description2", "query2", new RecordsManagementSearchParameters(), false);
return null;
}
});
// Add some saved searches (as user1)
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
SavedSearchDetails details1 = rmSearchService.saveSearch(siteId, SEARCH3, "description3", "query3", new RecordsManagementSearchParameters(), false);
checkSearchDetails(details1, siteId, SEARCH3, "description3", "query3", new RecordsManagementSearchParameters(), false);
SavedSearchDetails details2 = rmSearchService.saveSearch(siteId, SEARCH4, "description4", "query4", new RecordsManagementSearchParameters(), false);
checkSearchDetails(details2, siteId, SEARCH4, "description4", "query4", new RecordsManagementSearchParameters(), false);
return null;
}
}, USER1);
// Get searches (as admin user)
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
List<SavedSearchDetails> searches = rmSearchService.getSavedSearches(siteId);
assertNotNull(searches);
assertEquals(numberOfReports + 2, searches.size());
SavedSearchDetails search1 = rmSearchService.getSavedSearch(siteId, SEARCH1);
assertNotNull(search1);
checkSearchDetails(search1, siteId, "search1", "description1", "query1", new RecordsManagementSearchParameters(), true);
SavedSearchDetails search2 = rmSearchService.getSavedSearch(siteId, SEARCH2);
assertNotNull(search2);
checkSearchDetails(search2, siteId, "search2", "description2", "query2", new RecordsManagementSearchParameters(), false);
SavedSearchDetails search3 = rmSearchService.getSavedSearch(siteId, SEARCH3);
assertNull(search3);
SavedSearchDetails search4 = rmSearchService.getSavedSearch(siteId, SEARCH4);
assertNull(search4);
return null;
}
});
// Get searches (as user1)
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
List<SavedSearchDetails> searches = rmSearchService.getSavedSearches(siteId);
assertNotNull(searches);
assertEquals(numberOfReports + 3, searches.size());
SavedSearchDetails search1 = rmSearchService.getSavedSearch(siteId, SEARCH1);
assertNotNull(search1);
checkSearchDetails(search1, siteId, "search1", "description1", "query1", new RecordsManagementSearchParameters(), true);
SavedSearchDetails search2 = rmSearchService.getSavedSearch(siteId, SEARCH2);
assertNull(search2);
SavedSearchDetails search3 = rmSearchService.getSavedSearch(siteId, SEARCH3);
assertNotNull(search3);
checkSearchDetails(search3, siteId, SEARCH3, "description3", "query3", new RecordsManagementSearchParameters(), false);
SavedSearchDetails search4 = rmSearchService.getSavedSearch(siteId, SEARCH4);
assertNotNull(search4);
checkSearchDetails(search4, siteId, "search4", "description4", "query4", new RecordsManagementSearchParameters(), false);
return null;
}
}, USER1);
// Update search (as admin user)
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
SavedSearchDetails search1 = rmSearchService.getSavedSearch(siteId, SEARCH1);
assertNotNull(search1);
checkSearchDetails(search1, siteId, SEARCH1, "description1", "query1", new RecordsManagementSearchParameters(), true);
rmSearchService.saveSearch(siteId, SEARCH1, "change", "change", new RecordsManagementSearchParameters(), true);
search1 = rmSearchService.getSavedSearch(siteId, SEARCH1);
assertNotNull(search1);
checkSearchDetails(search1, siteId, SEARCH1, "change", "change", new RecordsManagementSearchParameters(), true);
return null;
}
});
// Delete searches (as admin user)
// TODO
}
/**
* Check the details of the saved search.
*/
private void checkSearchDetails(
SavedSearchDetails details,
String siteid,
String name,
String description,
String query,
RecordsManagementSearchParameters searchParameters,
boolean isPublic)
{
assertNotNull(details);
assertEquals(siteid, details.getSiteId());
assertEquals(name, details.getName());
assertEquals(description, details.getDescription());
assertEquals(query, details.getSearch());
assertEquals(isPublic, details.isPublic());
assertEquals(searchParameters.getMaxItems(), details.getSearchParameters().getMaxItems());
assertEquals(searchParameters.isIncludeRecords(), details.getSearchParameters().isIncludeRecords());
assertEquals(searchParameters.isIncludeUndeclaredRecords(), details.getSearchParameters().isIncludeUndeclaredRecords());
assertEquals(searchParameters.isIncludeVitalRecords(), details.getSearchParameters().isIncludeVitalRecords());
assertEquals(searchParameters.isIncludeRecordFolders(), details.getSearchParameters().isIncludeRecordFolders());
assertEquals(searchParameters.isIncludeFrozen(), details.getSearchParameters().isIncludeFrozen());
assertEquals(searchParameters.isIncludeCutoff(), details.getSearchParameters().isIncludeCutoff());
// Check the other stuff ....
}
}

View File

@@ -0,0 +1,615 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.util.ArrayList;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanComponentKind;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanService;
import org.alfresco.module.org_alfresco_module_rm.recordfolder.RecordFolderService;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.GUID;
/**
* Records management service test.
*
* @author Roy Wetherall
*/
public class RecordsManagementServiceImplTest extends BaseRMTestCase
{
/********** RM Component methods **********/
/**
* @see FilePlanService#isFilePlanComponent(NodeRef)
*/
public void testIsFilePlanComponent() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
assertTrue("The rm root container should be a rm component", filePlanService.isFilePlanComponent(filePlan));
assertTrue("The rm container should be a rm component", filePlanService.isFilePlanComponent(rmContainer));
assertTrue("The rm folder should be a rm component", filePlanService.isFilePlanComponent(rmFolder));
return null;
}
});
}
/**
* @see FilePlanService#getFilePlanComponentKind(NodeRef)
*/
public void testGetFilePlanComponentKind() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run() throws Exception
{
return utils.createRecord(rmFolder, "testRecord.txt");
}
@Override
public void test(NodeRef result) throws Exception
{
assertEquals(FilePlanComponentKind.FILE_PLAN, filePlanService.getFilePlanComponentKind(filePlan));
assertEquals(FilePlanComponentKind.RECORD_CATEGORY, filePlanService.getFilePlanComponentKind(rmContainer));
assertEquals(FilePlanComponentKind.RECORD_FOLDER, filePlanService.getFilePlanComponentKind(rmFolder));
assertEquals(FilePlanComponentKind.RECORD, filePlanService.getFilePlanComponentKind(result));
// TODO HOLD and TRANSFER
assertNull(filePlanService.getFilePlanComponentKind(folder));
}
});
}
/**
* @see FilePlanService#isFilePlan(NodeRef)
*/
public void testIsFilePlan() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
assertTrue("This is a records management root", filePlanService.isFilePlan(filePlan));
assertFalse("This should not be a records management root", filePlanService.isFilePlan(rmContainer));
assertFalse("This should not be a records management root", filePlanService.isFilePlan(rmFolder));
return null;
}
});
}
/**
* @see FilePlanService#isRecordCategory(NodeRef)
*/
public void testIsRecordCategory() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
assertFalse("This should not be a record category.", filePlanService.isRecordCategory(filePlan));
assertTrue("This is a record category.", filePlanService.isRecordCategory(rmContainer));
assertFalse("This should not be a record category.", filePlanService.isRecordCategory(rmFolder));
return null;
}
});
}
/**
* @see RecordFolderService#isRecordFolder(NodeRef)
*/
public void testIsRecordFolder() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
assertFalse("This should not be a record folder", recordFolderService.isRecordFolder(filePlan));
assertFalse("This should not be a record folder", recordFolderService.isRecordFolder(rmContainer));
assertTrue("This should be a record folder", recordFolderService.isRecordFolder(rmFolder));
return null;
}
});
}
public void testGetRecordsManagementRoot() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
assertEquals(filePlan, filePlanService.getFilePlan(filePlan));
assertEquals(filePlan, filePlanService.getFilePlan(rmContainer));
assertEquals(filePlan, filePlanService.getFilePlan(rmFolder));
return null;
}
});
}
/********** Record Management Root methods **********/
/**
* @see FilePlanService#getFilePlans()
*/
public void testGetRecordsManagementRoots() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
List<NodeRef> roots = new ArrayList<NodeRef>(filePlanService.getFilePlans());
assertNotNull(roots);
assertTrue(roots.size() != 0);
assertTrue(roots.contains(filePlan));
return null;
}
});
}
/**
* @see FilePlanService#createFilePlan(NodeRef, String)
* @see FilePlanService#createFilePlan(NodeRef, String, QName)
*/
public void testCreateFilePlan() throws Exception
{
// Create default type of root
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
String id = setString("id", GUID.generate());
return filePlanService.createFilePlan(folder, id);
}
@Override
public void test(NodeRef result)
{
assertNotNull("Unable to create records management root", result);
basicRMContainerCheck(result, getString("id"), TYPE_FILE_PLAN);
}
});
// Create specific type of root
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
String id = setString("id", GUID.generate());
return filePlanService.createFilePlan(folder, id, TYPE_FILE_PLAN);
}
@Override
public void test(NodeRef result)
{
assertNotNull("Unable to create records management root", result);
basicRMContainerCheck(result, getString("id"), TYPE_FILE_PLAN);
}
});
// Failure: creating root in existing hierarchy
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
filePlanService.createFilePlan(rmContainer, GUID.generate());
}
});
// Failure: type no extended from root container
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
filePlanService.createFilePlan(folder, GUID.generate(), TYPE_FOLDER);
}
});
}
/********** Records Management Container methods **********/
/**
* @see FilePlanService#createRecordCategory(NodeRef, String)
* @see FilePlanService#createFilePlan(NodeRef, String, QName)
*/
public void testCreateRecordCategory() throws Exception
{
// Create container (in root)
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
String id = setString("id", GUID.generate());
return filePlanService.createRecordCategory(filePlan, id);
}
@Override
public void test(NodeRef result)
{
assertNotNull("Unable to create records management container", result);
basicRMContainerCheck(result, getString("id"), TYPE_RECORD_CATEGORY);
}
});
// Create container (in container)
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
String id = setString("id", GUID.generate());
return filePlanService.createRecordCategory(rmContainer, id);
}
@Override
public void test(NodeRef result)
{
assertNotNull("Unable to create records management container", result);
basicRMContainerCheck(result, getString("id"), TYPE_RECORD_CATEGORY);
}
});
// TODO need a custom type of container!
// Create container of a given type
// doTestInTransaction(new Test<NodeRef>()
// {
// @Override
// public NodeRef run()
// {
// String id = setString("id", GUID.generate());
// return filePlanService.createRecordCategory(filePlan, id, TYPE_RECORD_SERIES);
// }
//
// @Override
// public void test(NodeRef result)
// {
// assertNotNull("Unable to create records management container", result);
// basicRMContainerCheck(result, getString("id"), TYPE_RECORD_SERIES);
// }
// });
// Fail Test: parent is not a container
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
filePlanService.createRecordCategory(folder, GUID.generate());
}
});
// Fail Test: type is not a sub-type of rm:recordsManagementContainer
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
filePlanService.createRecordCategory(filePlan, GUID.generate(), TYPE_FOLDER);
}
});
}
/**
* @see FilePlanService#getAllContained(NodeRef)
* @see FilePlanService#getAllContained(NodeRef, boolean)
*/
public void testGetAllContained() throws Exception
{
// Get all contained test
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// Add to the test data
NodeRef series = filePlanService.createRecordCategory(rmContainer, "rmSeries");
NodeRef seriesChildFolder = recordFolderService.createRecordFolder(series, "seriesRecordFolder");
NodeRef seriesChildContainer = filePlanService.createRecordCategory(series, "childContainer");
// Put in model
setNodeRef("series", series);
setNodeRef("seriesChildFolder", seriesChildFolder);
setNodeRef("seriesChildContainer", seriesChildContainer);
return null;
}
@Override
public void test(Void result) throws Exception
{
List<NodeRef> nodes = filePlanService.getAllContained(rmContainer);
assertNotNull(nodes);
assertEquals(2, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
assertTrue(nodes.contains(rmFolder));
nodes = filePlanService.getAllContained(rmContainer, false);
assertNotNull(nodes);
assertEquals(2, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
assertTrue(nodes.contains(rmFolder));
nodes = filePlanService.getAllContained(rmContainer, true);
assertNotNull(nodes);
assertEquals(4, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
assertTrue(nodes.contains(rmFolder));
assertTrue(nodes.contains(getNodeRef("seriesChildFolder")));
assertTrue(nodes.contains(getNodeRef("seriesChildContainer")));
}
});
// Failure: call on record folder
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
filePlanService.getAllContained(rmFolder);
}
});
}
/**
* @see FilePlanService#getContainedRecordCategories(NodeRef)
* @see FilePlanService#getContainedRecordCategories(NodeRef, boolean)
*/
public void testGetContainedRecordCategories() throws Exception
{
// Test getting all contained containers
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// Add to the test data
NodeRef series = filePlanService.createRecordCategory(rmContainer, "rmSeries");
NodeRef seriesChildFolder = recordFolderService.createRecordFolder(series, "seriesRecordFolder");
NodeRef seriesChildContainer = filePlanService.createRecordCategory(series, "childContainer");
// Put in model
setNodeRef("series", series);
setNodeRef("seriesChildFolder", seriesChildFolder);
setNodeRef("seriesChildContainer", seriesChildContainer);
return null;
}
@Override
public void test(Void result) throws Exception
{
List<NodeRef> nodes = filePlanService.getContainedRecordCategories(rmContainer);
assertNotNull(nodes);
assertEquals(1, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
nodes = filePlanService.getContainedRecordCategories(rmContainer, false);
assertNotNull(nodes);
assertEquals(1, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
nodes = filePlanService.getContainedRecordCategories(rmContainer, true);
assertNotNull(nodes);
assertEquals(2, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
assertTrue(nodes.contains(getNodeRef("seriesChildContainer")));
}
});
// Failure: call on record folder
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
filePlanService.getContainedRecordCategories(rmFolder);
}
});
}
/**
* @see FilePlanService#getContainedRecordFolders(NodeRef)
* @see FilePlanService#getContainedRecordFolders(NodeRef, boolean)
*/
public void testGetContainedRecordFolders() throws Exception
{
// Test getting all contained record folders
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// Add to the test data
NodeRef series = filePlanService.createRecordCategory(rmContainer, "rmSeries");
NodeRef seriesChildFolder = recordFolderService.createRecordFolder(series, "seriesRecordFolder");
NodeRef seriesChildContainer = filePlanService.createRecordCategory(series, "childContainer");
// Put in model
setNodeRef("series", series);
setNodeRef("seriesChildFolder", seriesChildFolder);
setNodeRef("seriesChildContainer", seriesChildContainer);
return null;
}
@Override
public void test(Void result) throws Exception
{
List<NodeRef> nodes = filePlanService.getContainedRecordFolders(rmContainer);
assertNotNull(nodes);
assertEquals(1, nodes.size());
assertTrue(nodes.contains(rmFolder));
nodes = filePlanService.getContainedRecordFolders(rmContainer, false);
assertNotNull(nodes);
assertEquals(1, nodes.size());
assertTrue(nodes.contains(rmFolder));
nodes = filePlanService.getContainedRecordFolders(rmContainer, true);
assertNotNull(nodes);
assertEquals(2, nodes.size());
assertTrue(nodes.contains(rmFolder));
assertTrue(nodes.contains(getNodeRef("seriesChildFolder")));
}
});
// Failure: call on record folder
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
filePlanService.getContainedRecordFolders(rmFolder);
}
});
}
/********** Record Folder methods **********/
// TODO void testIsRecordFolderDeclared()
// TODO void testIsRecordFolderClosed()
// TODO void testGetRecords()
/**
* @see RecordFolderService#createRecordFolder(NodeRef, String)
* @see RecordFolderService#createRecordFolder(NodeRef, String, QName)
*/
public void testCreateRecordFolder() throws Exception
{
// Create record
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
String id = setString("id", GUID.generate());
return recordFolderService.createRecordFolder(rmContainer, id);
}
@Override
public void test(NodeRef result)
{
assertNotNull("Unable to create record folder", result);
basicRMContainerCheck(result, getString("id"), TYPE_RECORD_FOLDER);
}
});
// TODO Create record of type
// Failure: Create record with invalid type
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
recordFolderService.createRecordFolder(rmContainer, GUID.generate(), TYPE_FOLDER);
}
});
// Failure: Create record folder in root
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
recordFolderService.createRecordFolder(filePlan, GUID.generate());
}
});
}
/********** RM2 - Multi-hierarchy record taxonomy's **********/
/**
* Test to create a simple multi-hierarchy record taxonomy
*/
public void testCreateSimpleHierarchy()
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// Create 3 level hierarchy
NodeRef levelOne = setNodeRef("container1", filePlanService.createRecordCategory(filePlan, "container1"));
assertNotNull("Unable to create container", levelOne);
NodeRef levelTwo = setNodeRef("container2", filePlanService.createRecordCategory(levelOne, "container2"));
assertNotNull("Unable to create container", levelTwo);
NodeRef levelThree = setNodeRef("container3", filePlanService.createRecordCategory(levelTwo, "container3"));
assertNotNull("Unable to create container", levelThree);
NodeRef levelThreeRecordFolder = setNodeRef("recordFolder3", recordFolderService.createRecordFolder(levelThree, "recordFolder3"));
assertNotNull("Unable to create record folder", levelThreeRecordFolder);
return null;
}
@Override
public void test(Void result)
{
// Test that the hierarchy has been created correctly
basicRMContainerCheck(getNodeRef("container1"), "container1", TYPE_RECORD_CATEGORY);
basicRMContainerCheck(getNodeRef("container2"), "container2", TYPE_RECORD_CATEGORY);
basicRMContainerCheck(getNodeRef("container3"), "container3", TYPE_RECORD_CATEGORY);
basicRMContainerCheck(getNodeRef("recordFolder3"), "recordFolder3", TYPE_RECORD_FOLDER);
// TODO need to check that the parents and children can be retrieved correctly
}
});
}
/**
* A basic test of a records management container
*
* @param nodeRef node reference
* @param name name of the container
* @param type the type of container
*/
private void basicRMContainerCheck(NodeRef nodeRef, String name, QName type)
{
// Check the basic details
assertEquals(name, nodeService.getProperty(nodeRef, PROP_NAME));
assertNotNull("RM id has not been set", nodeService.getProperty(nodeRef, PROP_IDENTIFIER));
assertEquals(type, nodeService.getType(nodeRef));
}
}

View File

@@ -0,0 +1,247 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionResult;
import org.alfresco.module.org_alfresco_module_rm.action.impl.CompleteEventAction;
import org.alfresco.module.org_alfresco_module_rm.action.impl.CutOffAction;
import org.alfresco.module.org_alfresco_module_rm.action.impl.DestroyAction;
import org.alfresco.module.org_alfresco_module_rm.action.impl.TransferAction;
import org.alfresco.module.org_alfresco_module_rm.report.Report;
import org.alfresco.module.org_alfresco_module_rm.report.ReportModel;
import org.alfresco.module.org_alfresco_module_rm.report.action.DestructionReportAction;
import org.alfresco.module.org_alfresco_module_rm.report.action.TransferNode;
import org.alfresco.module.org_alfresco_module_rm.report.action.TransferReportAction;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.module.org_alfresco_module_rm.test.util.CommonRMTestUtils;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.GUID;
import org.apache.commons.lang.StringUtils;
/**
* Report service implementation unit test.
*
* @author Roy Wetherall
*/
public class ReportServiceImplTest extends BaseRMTestCase implements ReportModel
{
public void testGetReportTypes() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
Set<QName> reportTypes = reportService.getReportTypes();
assertNotNull(reportTypes);
assertFalse(reportTypes.isEmpty());
for (QName reportType : reportTypes)
{
System.out.println(reportType.toString());
}
return null;
}
});
}
public void testGenerateReport() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
// Destruction Report
Report destructionReport = generateDestructionReport();
System.out.println(destructionReport.getReportName());
System.out.println(destructionReport.getReportContent().getContentString());
// Transfer Report
Report transferReport = generateTransfertReport();
System.out.println(transferReport.getReportName());
System.out.println(transferReport.getReportContent().getContentString());
return null;
}
});
}
public void testFileReport() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
// Destruction Report
NodeRef destructionReportNodeRef = fileDestructionReport();
assertNotNull(destructionReportNodeRef);
assertTrue(recordService.isRecord(destructionReportNodeRef));
assertFalse(recordService.isFiled(destructionReportNodeRef));
assertEquals(TYPE_DESTRUCTION_REPORT, nodeService.getType(destructionReportNodeRef));
// Transfer Report
NodeRef transferReportNodeRef = fileTransferReport();
assertNotNull(transferReportNodeRef);
assertTrue(recordService.isRecord(transferReportNodeRef));
assertFalse(recordService.isFiled(transferReportNodeRef));
assertEquals(TYPE_TRANSFER_REPORT, nodeService.getType(transferReportNodeRef));
return null;
}
});
}
/**
* Helper method to generate a destruction report
*
* @return Destruction report
*/
private Report generateDestructionReport()
{
return reportService.generateReport(TYPE_DESTRUCTION_REPORT, rmFolder);
}
/**
* Helper method to generate a transfer report
*
* @return Transfer report
*/
private Report generateTransfertReport()
{
Map<String, Serializable> properties = new HashMap<String, Serializable>(2);
ArrayList<TransferNode> transferNodes = new ArrayList<TransferNode>(1);
String dispositionAuthority = StringUtils.EMPTY;
properties.put("transferNodes", transferNodes);
properties.put("dispositionAuthority", dispositionAuthority);
return reportService.generateReport(TYPE_TRANSFER_REPORT, getTransferObject(), MimetypeMap.MIMETYPE_HTML, properties);
}
/**
* Helper method to file a destruction report
*
* @return Node reference of the destruction report
*/
private NodeRef fileDestructionReport()
{
Report destructionReport = generateDestructionReport();
return reportService.fileReport(filePlan, destructionReport);
}
/**
* Helper method to file a transfer report
*
* @return Node reference of the transfer report
*/
private NodeRef fileTransferReport()
{
Report transferReport = generateTransfertReport();
return reportService.fileReport(filePlan, transferReport);
}
public void testFileDestructionReportAction() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(CompleteEventAction.PARAM_EVENT_NAME, CommonRMTestUtils.DEFAULT_EVENT_NAME);
rmActionService.executeRecordsManagementAction(rmFolder, CompleteEventAction.NAME, params);
rmActionService.executeRecordsManagementAction(rmFolder, CutOffAction.NAME);
rmActionService.executeRecordsManagementAction(rmFolder, DestroyAction.NAME);
Map<String, Serializable> fileReportParams = new HashMap<String, Serializable>(2);
fileReportParams.put(DestructionReportAction.REPORT_TYPE, "rmr:destructionReport");
fileReportParams.put(DestructionReportAction.DESTINATION, filePlan.toString());
rmActionService.executeRecordsManagementAction(rmFolder, DestructionReportAction.NAME, fileReportParams);
return null;
}
});
}
public void testFileTransferReportAction() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
// Create transfer report for the transfer object
Map<String, Serializable> params = new HashMap<String, Serializable>(2);
params.put(TransferReportAction.REPORT_TYPE, "rmr:transferReport");
params.put(TransferReportAction.DESTINATION, filePlan.toString());
RecordsManagementActionResult transferReportAction = rmActionService.executeRecordsManagementAction(getTransferObject(), TransferReportAction.NAME, params);
// Check transfer report result
String transferReportName = (String) transferReportAction.getValue();
assertFalse(StringUtils.isBlank(transferReportName));
return null;
}
});
}
/**
* Helper method for creating a transfer object
*
* @return Node reference of the transfer object
*/
private NodeRef getTransferObject()
{
NodeRef recordCategory = filePlanService.createRecordCategory(filePlan, GUID.generate());
utils.createDispositionSchedule(
recordCategory,
CommonRMTestUtils.DEFAULT_DISPOSITION_INSTRUCTIONS,
CommonRMTestUtils.DEFAULT_DISPOSITION_AUTHORITY,
false, // record level
true, // set the default actions
true); // extended disposition schedule
NodeRef recordFolder = recordFolderService.createRecordFolder(recordCategory, GUID.generate());
// Set the record folder identifier
String identifier = identifierService.generateIdentifier(TYPE_RECORD_FOLDER, recordCategory);
nodeService.setProperty(recordFolder, PROP_IDENTIFIER, identifier);
// Complete event
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(CompleteEventAction.PARAM_EVENT_NAME, CommonRMTestUtils.DEFAULT_EVENT_NAME);
rmActionService.executeRecordsManagementAction(recordFolder, CompleteEventAction.NAME, params);
// Cut off folder
rmActionService.executeRecordsManagementAction(recordFolder, CutOffAction.NAME);
// Transfer folder
RecordsManagementActionResult transferAction = rmActionService.executeRecordsManagementAction(recordFolder, TransferAction.NAME);
NodeRef transferObject = (NodeRef) transferAction.getValue();
assertTrue(transferObject != null);
return transferObject;
}
}

View File

@@ -0,0 +1,461 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.service;
import java.util.Date;
import org.alfresco.module.org_alfresco_module_rm.model.behaviour.RecordsManagementSearchBehaviour;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.module.org_alfresco_module_rm.vital.VitalRecordDefinition;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.Period;
import org.alfresco.util.GUID;
/**
* Vital record service implementation unit test.
*
* @author Roy Wetherall
*/
public class VitalRecordServiceImplTest extends BaseRMTestCase
{
/** Test periods */
protected static final Period PERIOD_NONE = new Period("none|0");
protected static final Period PERIOD_WEEK = new Period("week|1");
protected static final Period PERIOD_MONTH = new Period("month|1");
/** Test records */
private NodeRef mhRecord51;
private NodeRef mhRecord52;
private NodeRef mhRecord53;
private NodeRef mhRecord54;
private NodeRef mhRecord55;
/**
* Indicate this test uses the collaboration site test data
*/
@Override
protected boolean isCollaborationSiteTest()
{
return true;
}
/** Indicate this is a multi hierarchy test */
@Override
protected boolean isMultiHierarchyTest()
{
return true;
}
/** vital record multi-hierarchy test data
*
* |--rmRootContainer (no vr def)
* |
* |--mhContainer (no vr def)
* |
* |--mhContainer-1-1 (has schedule - folder level) (no vr def)
* | |
* | |--mhContainer-2-1 (vr def)
* | |
* | |--mhContainer-3-1 (no vr def)
* |
* |--mhContainer-1-2 (has schedule - folder level) (no vr def)
* |
* |--mhContainer-2-2 (no vr def)
* | |
* | |--mhContainer-3-2 (vr def disabled)
* | |
* | |--mhContainer-3-3 (has schedule - record level) (vr def)
* |
* |--mhContainer-2-3 (has schedule - folder level) (vr def)
* |
* |--mhContainer-3-4 (no vr def)
* |
* |--mhContainer-3-5 (has schedule- record level) (vr def)
*/
@Override
protected void setupMultiHierarchyTestData()
{
// Load core test data
super.setupMultiHierarchyTestData();
// Setup vital record definitions
setupVitalRecordDefinition(mhContainer21, true, PERIOD_WEEK);
setupVitalRecordDefinition(mhContainer32, false, PERIOD_WEEK);
setupVitalRecordDefinition(mhContainer33, true, PERIOD_WEEK);
setupVitalRecordDefinition(mhContainer23, true, PERIOD_WEEK);
setupVitalRecordDefinition(mhContainer35, true, PERIOD_MONTH);
// Create records
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
mhRecord51 = utils.createRecord(mhRecordFolder41, "record51.txt");
mhRecord52 = utils.createRecord(mhRecordFolder42, "record52.txt");
mhRecord53 = utils.createRecord(mhRecordFolder43, "record53.txt");
mhRecord54 = utils.createRecord(mhRecordFolder44, "record54.txt");
mhRecord55 = utils.createRecord(mhRecordFolder45, "record55.txt");
return null;
}
});
}
/**
* Helper to set up the vital record definition data in a transactional manner.
*
* @param nodeRef
* @param enabled
* @param period
*/
private void setupVitalRecordDefinition(final NodeRef nodeRef, final boolean enabled, final Period period)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
vitalRecordService.setVitalRecordDefintion(nodeRef, enabled, period);
return null;
}
});
}
/**
* Based on the initial data:
* - check category, folder and record raw values.
* - check search aspect values.
*/
public void testInit()
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertHasVitalRecordDefinition(mhContainer, false, null);
assertHasVitalRecordDefinition(mhContainer11, false, null);
assertHasVitalRecordDefinition(mhContainer12, false, null);
assertHasVitalRecordDefinition(mhContainer21, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer22, false, null);
assertHasVitalRecordDefinition(mhContainer23, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer31, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer32, false, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer33, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer34, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer35, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhRecordFolder41, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhRecordFolder42, false, null);
assertHasVitalRecordDefinition(mhRecordFolder43, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhRecordFolder44, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhRecordFolder45, true, PERIOD_MONTH);
assertVitalRecord(mhRecord51, true, PERIOD_WEEK);
assertVitalRecord(mhRecord52, false, null);
assertVitalRecord(mhRecord53, true, PERIOD_WEEK);
assertVitalRecord(mhRecord54, true, PERIOD_WEEK);
assertVitalRecord(mhRecord55, true, PERIOD_MONTH);
return null;
}
});
}
/**
* Test that when new record categories and record folders are created in an existing file plan
* structure that they correctly inherit the correct vital record property values
*/
public void testValueInheritance() throws Exception
{
// Test record category value inheritance
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
return filePlanService.createRecordCategory(mhContainer35, GUID.generate());
}
@Override
public void test(NodeRef result) throws Exception
{
assertHasVitalRecordDefinition(result, true, PERIOD_MONTH);
}
});
// Test record folder value inheritance
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
return recordFolderService.createRecordFolder(mhContainer32, GUID.generate());
}
@Override
public void test(NodeRef result) throws Exception
{
assertHasVitalRecordDefinition(result, false, PERIOD_WEEK);
}
});
}
/** Filling tests */
public void testFileNewContent() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
NodeRef record = fileFolderService.create(mhRecordFolder41, "test101.txt" , TYPE_CONTENT).getNodeRef();
ContentWriter writer = contentService.getWriter(record, PROP_CONTENT, true);
writer.setEncoding("UTF-8");
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
writer.putContent("hello world this is some test content");
return record;
}
@Override
public void test(NodeRef record) throws Exception
{
assertVitalRecord(record, true, PERIOD_WEEK);
}
});
}
// public void testFileUnfiledrecord() throws Exception
// {
// doTestInTransaction(new Test<NodeRef>()
// {
// @Override
// public NodeRef run() throws Exception
// {
// recordService.createRecord(filePlan, dmDocument);
// fileFolderService.move(dmDocument, mhRecordFolder41, "record.txt");
//
// return dmDocument;
// }
//
// @Override
// public void test(NodeRef record) throws Exception
// {
// assertVitalRecord(record, true, PERIOD_WEEK);
// }
// });
// }
//
// public void testFileDirectlyFromCollab() throws Exception
// {
// doTestInTransaction(new Test<NodeRef>()
// {
// @Override
// public NodeRef run() throws Exception
// {
// fileFolderService.move(dmDocument, mhRecordFolder41, "record.txt");
// return dmDocument;
// }
//
// @Override
// public void test(NodeRef record) throws Exception
// {
// assertVitalRecord(record, true, PERIOD_WEEK);
// }
// });
// }
/** Helper Methods */
/**
* Test to ensure that changes made to vital record definitions are reflected down the hierarchy.
*/
public void testChangesToVitalRecordDefinitions() throws Exception
{
// Override vital record definition
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
setupVitalRecordDefinition(mhContainer31, true, PERIOD_MONTH);
return null;
}
@Override
public void test(Void result) throws Exception
{
assertHasVitalRecordDefinition(mhContainer, false, null);
assertHasVitalRecordDefinition(mhContainer11, false, null);
assertHasVitalRecordDefinition(mhContainer12, false, null);
assertHasVitalRecordDefinition(mhContainer21, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer22, false, null);
assertHasVitalRecordDefinition(mhContainer23, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer31, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhContainer32, false, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer33, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer34, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer35, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhRecordFolder41, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhRecordFolder42, false, null);
assertHasVitalRecordDefinition(mhRecordFolder43, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhRecordFolder44, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhRecordFolder45, true, PERIOD_MONTH);
assertVitalRecord(mhRecord51, true, PERIOD_MONTH);
assertVitalRecord(mhRecord52, false, null);
assertVitalRecord(mhRecord53, true, PERIOD_WEEK);
assertVitalRecord(mhRecord54, true, PERIOD_WEEK);
assertVitalRecord(mhRecord55, true, PERIOD_MONTH);
}
});
// 'turn off' vital record def
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
setupVitalRecordDefinition(mhContainer31, false, PERIOD_NONE);
return null;
}
@Override
public void test(Void result) throws Exception
{
assertHasVitalRecordDefinition(mhContainer, false, null);
assertHasVitalRecordDefinition(mhContainer11, false, null);
assertHasVitalRecordDefinition(mhContainer12, false, null);
assertHasVitalRecordDefinition(mhContainer21, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer22, false, null);
assertHasVitalRecordDefinition(mhContainer23, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer31, false, null);
assertHasVitalRecordDefinition(mhContainer32, false, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer33, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer34, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer35, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhRecordFolder41, false, null);
assertHasVitalRecordDefinition(mhRecordFolder42, false, null);
assertHasVitalRecordDefinition(mhRecordFolder43, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhRecordFolder44, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhRecordFolder45, true, PERIOD_MONTH);
assertVitalRecord(mhRecord51, false, null);
assertVitalRecord(mhRecord52, false, null);
assertVitalRecord(mhRecord53, true, PERIOD_WEEK);
assertVitalRecord(mhRecord54, true, PERIOD_WEEK);
assertVitalRecord(mhRecord55, true, PERIOD_MONTH);
}
});
// Test parent change overrites existing
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
setupVitalRecordDefinition(mhContainer12, true, PERIOD_MONTH);
return null;
}
@Override
public void test(Void result) throws Exception
{
assertHasVitalRecordDefinition(mhContainer, false, null);
assertHasVitalRecordDefinition(mhContainer11, false, null);
assertHasVitalRecordDefinition(mhContainer12, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhContainer21, true, PERIOD_WEEK);
assertHasVitalRecordDefinition(mhContainer22, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhContainer23, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhContainer31, false, null);
assertHasVitalRecordDefinition(mhContainer32, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhContainer33, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhContainer34, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhContainer35, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhRecordFolder41, false, null);
assertHasVitalRecordDefinition(mhRecordFolder42, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhRecordFolder43, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhRecordFolder44, true, PERIOD_MONTH);
assertHasVitalRecordDefinition(mhRecordFolder45, true, PERIOD_MONTH);
assertVitalRecord(mhRecord51, false, null);
assertVitalRecord(mhRecord52, true, PERIOD_MONTH);
assertVitalRecord(mhRecord53, true, PERIOD_MONTH);
assertVitalRecord(mhRecord54, true, PERIOD_MONTH);
assertVitalRecord(mhRecord55, true, PERIOD_MONTH);
}
});
}
@SuppressWarnings("deprecation")
private void assertHasVitalRecordDefinition(NodeRef nodeRef, boolean enabled, Period period)
{
assertTrue(nodeService.hasAspect(nodeRef, ASPECT_VITAL_RECORD_DEFINITION));
VitalRecordDefinition def = vitalRecordService.getVitalRecordDefinition(nodeRef);
assertNotNull(def);
Boolean vitalRecordIndicator = (Boolean)nodeService.getProperty(nodeRef, PROP_VITAL_RECORD_INDICATOR);
assertNotNull(vitalRecordIndicator);
assertEquals(enabled, vitalRecordIndicator.booleanValue());
assertEquals(enabled, def.isEnabled());
if (enabled == true)
{
Period reviewPeriod = (Period)nodeService.getProperty(nodeRef, PROP_REVIEW_PERIOD);
assertNotNull(reviewPeriod);
assertEquals(period, reviewPeriod);
assertEquals(period, def.getReviewPeriod());
assertEquals(period.getNextDate(new Date()).getDate(), def.getNextReviewDate().getDate());
}
}
@SuppressWarnings("deprecation")
private void assertVitalRecord(NodeRef nodeRef, boolean enabled, Period period)
{
assertEquals(enabled, nodeService.hasAspect(nodeRef, ASPECT_VITAL_RECORD));
if (enabled == true)
{
Date reviewAsOf = (Date)nodeService.getProperty(nodeRef, PROP_REVIEW_AS_OF);
assertNotNull(reviewAsOf);
assertEquals(period.getNextDate(new Date()).getDate(), reviewAsOf.getDate());
assertEquals(period.getPeriodType(), nodeService.getProperty(nodeRef, RecordsManagementSearchBehaviour.PROP_RS_VITAL_RECORD_REVIEW_PERIOD));
assertEquals(period.getExpression(), nodeService.getProperty(nodeRef, RecordsManagementSearchBehaviour.PROP_RS_VITAL_RECORD_REVIEW_PERIOD_EXPRESSION));
}
else
{
assertNull(nodeService.getProperty(nodeRef, RecordsManagementSearchBehaviour.PROP_RS_VITAL_RECORD_REVIEW_PERIOD));
assertNull(nodeService.getProperty(nodeRef, RecordsManagementSearchBehaviour.PROP_RS_VITAL_RECORD_REVIEW_PERIOD_EXPRESSION));
}
}
}

View File

@@ -0,0 +1,149 @@
/*
* Copyright (C) 2009-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.system;
import java.util.ArrayList;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.notification.RecordsManagementNotificationHelper;
import org.alfresco.module.org_alfresco_module_rm.role.Role;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.util.GUID;
import org.alfresco.util.PropertyMap;
/**
* Notification helper (system) test
*
* @author Roy Wetherall
*/
public class NotificationServiceHelperSystemTest extends BaseRMTestCase
{
private static final String NOTIFICATION_ROLE = "RecordsManager";
private static final String EMAIL_ADDRESS = "roy.wetherall@alfreso.com";
/** Services */
private RecordsManagementNotificationHelper notificationHelper;
/** Test data */
private NodeRef record;
private List<NodeRef> records;
private String userName;
private NodeRef person;
@Override
protected void initServices()
{
super.initServices();
// Get the notification helper
notificationHelper = (RecordsManagementNotificationHelper)applicationContext.getBean("recordsManagementNotificationHelper");
}
@Override
protected void setupTestData()
{
super.setupTestData();
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
// Create a user
userName = GUID.generate();
authenticationService.createAuthentication(userName, "".toCharArray());
PropertyMap props = new PropertyMap();
props.put(PROP_USERNAME, userName);
props.put(PROP_FIRSTNAME, "Test");
props.put(PROP_LASTNAME, "User");
props.put(PROP_EMAIL, EMAIL_ADDRESS);
person = personService.createPerson(props);
// Find the authority for the given role
Role role = filePlanRoleService.getRole(filePlan, NOTIFICATION_ROLE);
assertNotNull("Notification role could not be retrieved", role);
String roleGroup = role.getRoleGroupName();
assertNotNull("Notification role group can not be null.", roleGroup);
// Add user to notification role group
authorityService.addAuthority(roleGroup, userName);
return null;
}
});
}
@Override
protected void setupTestDataImpl()
{
super.setupTestDataImpl();
// Create a few test records
record = utils.createRecord(rmFolder, "recordOne");
NodeRef record2 = utils.createRecord(rmFolder, "recordTwo");
NodeRef record3 = utils.createRecord(rmFolder, "recordThree");
records = new ArrayList<NodeRef>(3);
records.add(record);
records.add(record2);
records.add(record3);
}
@Override
protected void tearDownImpl()
{
super.tearDownImpl();
// Delete the person and user
personService.deletePerson(person);
}
public void testSendDueForReviewNotification()
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
notificationHelper.recordsDueForReviewEmailNotification(records);
return null;
}
});
}
public void testSendSupersededNotification()
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
notificationHelper.recordSupersededEmailNotification(record);
return null;
}
});
}
}

View File

@@ -0,0 +1,250 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.system;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.transaction.UserTransaction;
import junit.framework.TestCase;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionSchedule;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionService;
import org.alfresco.module.org_alfresco_module_rm.dod5015.DOD5015Model;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanService;
import org.alfresco.module.org_alfresco_module_rm.identifier.IdentifierService;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.Period;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.ApplicationContextHelper;
import org.springframework.context.ApplicationContext;
/**
* @author Roy Wetherall
*/
public class PerformanceDataLoadSystemTest extends TestCase implements RecordsManagementModel, DOD5015Model
{
private ApplicationContext appContext;
private AuthenticationComponent authenticationComponent;
private DispositionService dispositionService;
private TransactionService transactionService;
private NodeService nodeService;
private ContentService contentService;
private IdentifierService identifierService;
private FilePlanService filePlanService;
UserTransaction userTransaction;
private int SERIES_COUNT = 1;
private int CATEGORY_COUNT = 1;
private int RECORD_FOLDER_COUNT = 1;
private int RECORD_COUNT = 700;
@Override
protected void setUp() throws Exception
{
appContext = ApplicationContextHelper.getApplicationContext();
authenticationComponent = (AuthenticationComponent)appContext.getBean("authenticationComponent");
transactionService = (TransactionService)appContext.getBean("transactionService");
nodeService = (NodeService)appContext.getBean("nodeService");
contentService = (ContentService)appContext.getBean("contentService");
identifierService = (IdentifierService)appContext.getBean("identifierService");
dispositionService = (DispositionService)appContext.getBean("dispositionService");
filePlanService = (FilePlanService)appContext.getBean("filePlanService");
// Set authentication
authenticationComponent.setCurrentUser("admin");
// Start transaction
userTransaction = transactionService.getUserTransaction();
userTransaction.begin();
}
@Override
protected void tearDown() throws Exception
{
userTransaction.commit();
}
public void testLoadTestData() throws Exception
{
NodeRef filePlan = filePlanService.getFilePlanBySiteId(FilePlanService.DEFAULT_RM_SITE_ID);
if (filePlan == null)
{
fail("The default RM site is not present.");
}
for (int i = 0; i < SERIES_COUNT; i++)
{
// Create the series
createSeries(filePlan, i);
}
}
private void createSeries(NodeRef filePlan, int index) throws Exception
{
String name = genName("series-", index, "-" + System.currentTimeMillis());
Map<QName, Serializable> properties = new HashMap<QName, Serializable>(2);
properties.put(ContentModel.PROP_NAME, name);
properties.put(PROP_IDENTIFIER, identifierService.generateIdentifier(TYPE_RECORD_CATEGORY, filePlan));
NodeRef series = nodeService.createNode(
filePlan,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name),
TYPE_RECORD_CATEGORY,
properties).getChildRef();
System.out.println("Created series '" + name);
// Create the categories
for (int i = 0; i < CATEGORY_COUNT; i++)
{
createCategory(series, i);
}
}
private void createCategory(NodeRef series, int index) throws Exception
{
String name = genName("category-", index);
Map<QName, Serializable> properties = new HashMap<QName, Serializable>(7);
properties.put(ContentModel.PROP_NAME, name);
properties.put(ContentModel.PROP_DESCRIPTION, "Test category");
NodeRef cat = nodeService.createNode(
series,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name),
TYPE_RECORD_CATEGORY,
properties).getChildRef();
// Need to close the transaction and reopen to kick off required initialisation behaviour
userTransaction.commit();
userTransaction = transactionService.getUserTransaction();
userTransaction.begin();
properties = nodeService.getProperties(cat);
//properties.put(PROP_IDENTIFIER, identifierService.generateIdentifier(series));
properties.put(PROP_VITAL_RECORD_INDICATOR, true);
properties.put(PROP_REVIEW_PERIOD, new Period("week|1"));
nodeService.setProperties(cat, properties);
// Get the disposition schedule
DispositionSchedule ds = dispositionService.getDispositionSchedule(cat);
properties = nodeService.getProperties(ds.getNodeRef());
properties.put(PROP_DISPOSITION_AUTHORITY, "Disposition Authority");
properties.put(PROP_DISPOSITION_INSTRUCTIONS, "Test disposition");
nodeService.setProperties(ds.getNodeRef(), properties);
// Add cutoff disposition action
Map<QName, Serializable> actionParams = new HashMap<QName, Serializable>(2);
actionParams.put(PROP_DISPOSITION_ACTION_NAME, "cutoff");
actionParams.put(PROP_DISPOSITION_PERIOD, new Period("day|1"));
dispositionService.addDispositionActionDefinition(ds, actionParams);
// Add delete disposition action
actionParams = new HashMap<QName, Serializable>(3);
actionParams.put(PROP_DISPOSITION_ACTION_NAME, "destroy");
actionParams.put(PROP_DISPOSITION_PERIOD, new Period("immediately|0"));
actionParams.put(PROP_DISPOSITION_PERIOD_PROPERTY, QName.createQName("{http://www.alfresco.org/model/recordsmanagement/1.0}cutOffDate"));
dispositionService.addDispositionActionDefinition(ds, actionParams);
System.out.println("Created category '" + name);
// Create the record folders
for (int i = 0; i < RECORD_FOLDER_COUNT; i++)
{
// Create the series
createRecordFolder(cat, i);
}
}
private void createRecordFolder(NodeRef cat, int index) throws Exception
{
String name = genName("folder-", index);
Map<QName, Serializable> properties = new HashMap<QName, Serializable>(2);
properties.put(ContentModel.PROP_NAME, name);
properties.put(PROP_IDENTIFIER, identifierService.generateIdentifier(TYPE_RECORD_FOLDER, cat));
NodeRef rf = nodeService.createNode(
cat,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name),
TYPE_RECORD_FOLDER,
properties).getChildRef();
// Need to close the transaction and reopen to kick off required initialisation behaviour
userTransaction.commit();
userTransaction = transactionService.getUserTransaction();
userTransaction.begin();
System.out.println("Created record folder '" + name);
// Create the records
for (int i = 0; i < RECORD_COUNT; i++)
{
createRecord(rf, i);
}
userTransaction.commit();
userTransaction = transactionService.getUserTransaction();
userTransaction.begin();
}
private void createRecord(NodeRef recordFolder, int index) throws Exception
{
String name = genName("record-", index, ".txt");
Map<QName, Serializable> properties = new HashMap<QName, Serializable>(2);
properties.put(ContentModel.PROP_NAME, name);
NodeRef r = nodeService.createNode(
recordFolder,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name),
ContentModel.TYPE_CONTENT,
properties).getChildRef();
ContentWriter cw = contentService.getWriter(r, ContentModel.PROP_CONTENT, true);
cw.setEncoding("UTF-8");
cw.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
cw.putContent("This is my records content");
System.out.println("Created record '" + name);
}
private String genName(String prefix, int index)
{
return genName(prefix, index, "");
}
private String genName(String prefix, int index, String postfix)
{
StringBuffer buff = new StringBuffer(120);
buff.append(prefix)
.append(index)
.append(postfix);
return buff.toString();
}
}

View File

@@ -0,0 +1,797 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionService;
import org.alfresco.module.org_alfresco_module_rm.admin.RecordsManagementAdminService;
import org.alfresco.module.org_alfresco_module_rm.audit.RecordsManagementAuditService;
import org.alfresco.module.org_alfresco_module_rm.capability.CapabilityService;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.dataset.DataSetService;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionSchedule;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionService;
import org.alfresco.module.org_alfresco_module_rm.event.RecordsManagementEventService;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanService;
import org.alfresco.module.org_alfresco_module_rm.freeze.FreezeService;
import org.alfresco.module.org_alfresco_module_rm.identifier.IdentifierService;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.model.rma.type.RmSiteType;
import org.alfresco.module.org_alfresco_module_rm.record.RecordService;
import org.alfresco.module.org_alfresco_module_rm.recordfolder.RecordFolderService;
import org.alfresco.module.org_alfresco_module_rm.report.ReportService;
import org.alfresco.module.org_alfresco_module_rm.role.FilePlanRoleService;
import org.alfresco.module.org_alfresco_module_rm.search.RecordsManagementSearchService;
import org.alfresco.module.org_alfresco_module_rm.security.ExtendedSecurityService;
import org.alfresco.module.org_alfresco_module_rm.security.FilePlanAuthenticationService;
import org.alfresco.module.org_alfresco_module_rm.security.FilePlanPermissionService;
import org.alfresco.module.org_alfresco_module_rm.vital.VitalRecordService;
import org.alfresco.repo.policy.BehaviourFilter;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authority.AuthorityDAO;
import org.alfresco.repo.site.SiteModel;
import org.alfresco.repo.site.SiteServiceImpl;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.action.ActionService;
import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.model.FileFolderService;
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.repository.StoreRef;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.cmr.site.SiteInfo;
import org.alfresco.service.cmr.site.SiteService;
import org.alfresco.service.cmr.site.SiteVisibility;
import org.alfresco.service.cmr.tagging.TaggingService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.ApplicationContextHelper;
import org.alfresco.util.GUID;
import org.alfresco.util.RetryingTransactionHelperTestCase;
import org.springframework.context.ApplicationContext;
/**
* Base test case class to use for RM unit tests.
*
* @author Roy Wetherall
*/
public abstract class BaseRMTestCase extends RetryingTransactionHelperTestCase
implements RecordsManagementModel, ContentModel, RMPermissionModel
{
/** Application context */
protected static final String[] CONFIG_LOCATIONS = new String[]
{
"classpath:alfresco/application-context.xml",
"classpath:test-context.xml"
};
protected ApplicationContext applicationContext;
/** test model constants */
protected String URI = "http://www.alfresco.org/model/rmtest/1.0";
protected String PREFIX = "rmt";
protected QName TYPE_CUSTOM_TYPE = QName.createQName(URI, "customType");
protected QName ASPECT_CUSTOM_ASPECT = QName.createQName(URI, "customAspect");
protected QName ASPECT_RECORD_META_DATA = QName.createQName(URI, "recordMetaData");
/** site id's */
protected static final String COLLABORATION_SITE_ID = "collab-site-id";
/** Common test utils */
protected CommonRMTestUtils utils;
/** RM Admin user name */
protected String rmAdminUserName;
/** Services */
protected NodeService nodeService;
protected ContentService contentService;
protected DictionaryService dictionaryService;
protected RetryingTransactionHelper retryingTransactionHelper;
protected PolicyComponent policyComponent;
protected NamespaceService namespaceService;
protected SearchService searchService;
protected SiteService siteService;
protected MutableAuthenticationService authenticationService;
protected AuthorityService authorityService;
protected PersonService personService;
protected TransactionService transactionService;
protected FileFolderService fileFolderService;
protected PermissionService permissionService;
protected TaggingService taggingService;
protected ActionService actionService;
/** RM Services */
protected DispositionService dispositionService;
protected RecordsManagementEventService rmEventService;
protected RecordsManagementAdminService rmAdminService;
protected RecordsManagementActionService rmActionService;
protected RecordsManagementSearchService rmSearchService;
protected FilePlanRoleService filePlanRoleService;
protected FilePlanPermissionService filePlanPermissionService;
protected CapabilityService capabilityService;
protected VitalRecordService vitalRecordService;
protected DataSetService dataSetService;
protected FreezeService freezeService;
protected RecordService recordService;
protected FilePlanService filePlanService;
protected FilePlanAuthenticationService filePlanAuthenticationService;
protected RecordFolderService recordFolderService;
protected ExtendedSecurityService extendedSecurityService;
protected ReportService reportService;
protected RecordsManagementAuditService rmAuditService;
protected IdentifierService identifierService;
/** test data */
protected String siteId;
protected StoreRef storeRef;
protected NodeRef rootNodeRef;
protected SiteInfo siteInfo;
protected NodeRef folder;
protected NodeRef filePlan;
protected NodeRef rmContainer;
protected DispositionSchedule dispositionSchedule;
protected NodeRef rmFolder;
protected NodeRef unfiledContainer;
/** multi-hierarchy test data
*
* |--rmRootContainer
* |
* |--mhContainer
* |
* |--mhContainer-1-1 (has schedule - folder level)
* | |
* | |--mhContainer-2-1
* | |
* | |--mhContainer-3-1
* |
* |--mhContainer-1-2 (has schedule - folder level)
* |
* |--mhContainer-2-2
* | |
* | |--mhContainer-3-2
* | |
* | |--mhContainer-3-3 (has schedule - record level)
* |
* |--mhContainer-2-3 (has schedule - folder level)
* |
* |--mhContainer-3-4
* |
* |--mhContainer-3-5 (has schedule- record level)
*/
protected NodeRef mhContainer;
protected NodeRef mhContainer11;
protected DispositionSchedule mhDispositionSchedule11;
protected NodeRef mhContainer12;
protected DispositionSchedule mhDispositionSchedule12;
protected NodeRef mhContainer21;
protected NodeRef mhContainer22;
protected NodeRef mhContainer23;
protected DispositionSchedule mhDispositionSchedule23;
protected NodeRef mhContainer31;
protected NodeRef mhContainer32;
protected NodeRef mhContainer33;
protected DispositionSchedule mhDispositionSchedule33;
protected NodeRef mhContainer34;
protected NodeRef mhContainer35;
protected DispositionSchedule mhDispositionSchedule35;
protected NodeRef mhRecordFolder41;
protected NodeRef mhRecordFolder42;
protected NodeRef mhRecordFolder43;
protected NodeRef mhRecordFolder44;
protected NodeRef mhRecordFolder45;
/** test user names */
protected String[] testUsers;
protected String userName;
protected String rmUserName;
protected String powerUserName;
protected String securityOfficerName;
protected String recordsManagerName;
protected String rmAdminName;
/** test people */
protected NodeRef userPerson;
protected NodeRef rmUserPerson;
protected NodeRef powerUserPerson;
protected NodeRef securityOfficerPerson;
protected NodeRef recordsManagerPerson;
protected NodeRef rmAdminPerson;
/** test records */
protected NodeRef recordOne;
protected NodeRef recordTwo;
protected NodeRef recordThree;
protected NodeRef recordFour;
protected NodeRef recordFive;
protected NodeRef recordDeclaredOne;
protected NodeRef recordDeclaredTwo;
/** collaboration site artifacts */
protected SiteInfo collaborationSite;
protected NodeRef documentLibrary;
protected NodeRef dmFolder;
protected NodeRef dmDocument;
/** collaboration site users */
protected String dmConsumer;
protected NodeRef dmConsumerNodeRef;
protected String dmCollaborator;
protected NodeRef dmCollaboratorNodeRef;
/**
* Indicates whether this is a multi-hierarchy test or not. If it is then the multi-hierarchy record
* taxonomy test data is loaded.
*/
protected boolean isMultiHierarchyTest()
{
return false;
}
/**
* Indicates whether the test users should be created or not.
*/
protected boolean isUserTest()
{
return false;
}
/**
* Indicates whether the test records should be created or not.
*/
protected boolean isRecordTest()
{
return false;
}
/**
* Indicates whether the test users should have filling on the file plan structure
* by default or not.
*/
protected boolean isFillingForAllUsers()
{
return false;
}
/**
* Indicates whether the test collaboration site should be created
* or not.
*/
protected boolean isCollaborationSiteTest()
{
return false;
}
/**
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception
{
// Get the application context
applicationContext = ApplicationContextHelper.getApplicationContext(CONFIG_LOCATIONS);
utils = new CommonRMTestUtils(applicationContext);
// Initialise the service beans
initServices();
// grab the rmadmin user name
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
// As system user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
rmAdminUserName = filePlanAuthenticationService.getRmAdminUserName();
return null;
}
});
// Setup test data
setupTestData();
// Create multi hierarchy data
if (isMultiHierarchyTest() == true)
{
setupMultiHierarchyTestData();
}
// Create collaboration data
if (isCollaborationSiteTest() == true)
{
setupCollaborationSiteTestData();
}
// Create the users here
if (isUserTest() == true)
{
setupTestUsers(filePlan);
}
}
/**
* Initialise the service beans.
*/
protected void initServices()
{
// Get services
nodeService = (NodeService)applicationContext.getBean("NodeService");
contentService = (ContentService)applicationContext.getBean("ContentService");
retryingTransactionHelper = (RetryingTransactionHelper)applicationContext.getBean("retryingTransactionHelper");
namespaceService = (NamespaceService)this.applicationContext.getBean("NamespaceService");
searchService = (SearchService)this.applicationContext.getBean("SearchService");
policyComponent = (PolicyComponent)this.applicationContext.getBean("policyComponent");
dictionaryService = (DictionaryService)this.applicationContext.getBean("DictionaryService");
siteService = (SiteService)this.applicationContext.getBean("SiteService");
authorityService = (AuthorityService)this.applicationContext.getBean("AuthorityService");
authenticationService = (MutableAuthenticationService)this.applicationContext.getBean("AuthenticationService");
personService = (PersonService)this.applicationContext.getBean("PersonService");
transactionService = (TransactionService)applicationContext.getBean("TransactionService");
fileFolderService = (FileFolderService)applicationContext.getBean("FileFolderService");
permissionService = (PermissionService)applicationContext.getBean("PermissionService");
taggingService = (TaggingService)applicationContext.getBean("TaggingService");
actionService = (ActionService)applicationContext.getBean("ActionService");
// Get RM services
dispositionService = (DispositionService)applicationContext.getBean("DispositionService");
rmEventService = (RecordsManagementEventService)applicationContext.getBean("RecordsManagementEventService");
rmAdminService = (RecordsManagementAdminService)applicationContext.getBean("RecordsManagementAdminService");
rmActionService = (RecordsManagementActionService)this.applicationContext.getBean("RecordsManagementActionService");
rmSearchService = (RecordsManagementSearchService)this.applicationContext.getBean("RecordsManagementSearchService");
filePlanRoleService = (FilePlanRoleService)this.applicationContext.getBean("FilePlanRoleService");
filePlanPermissionService = (FilePlanPermissionService)this.applicationContext.getBean("FilePlanPermissionService");
capabilityService = (CapabilityService)this.applicationContext.getBean("CapabilityService");
vitalRecordService = (VitalRecordService)this.applicationContext.getBean("VitalRecordService");
dataSetService = (DataSetService) applicationContext.getBean("DataSetService");
freezeService = (FreezeService) applicationContext.getBean("FreezeService");
recordService = (RecordService) applicationContext.getBean("RecordService");
filePlanService = (FilePlanService) applicationContext.getBean("FilePlanService");
filePlanAuthenticationService = (FilePlanAuthenticationService) applicationContext.getBean("FilePlanAuthenticationService");
recordFolderService = (RecordFolderService) applicationContext.getBean("RecordFolderService");
extendedSecurityService = (ExtendedSecurityService) applicationContext.getBean("ExtendedSecurityService");
reportService = (ReportService) applicationContext.getBean("ReportService");
rmAuditService = (RecordsManagementAuditService) applicationContext.getBean("RecordsManagementAuditService");
identifierService = (IdentifierService) applicationContext.getBean("recordsManagementIdentifierService");
}
/**
* @see junit.framework.TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
// As system user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
// Do the tear down
tearDownImpl();
return null;
}
});
}
/**
* Tear down implementation
*/
protected void tearDownImpl()
{
BehaviourFilter filter = (BehaviourFilter)applicationContext.getBean("policyBehaviourFilter");
filter.disableBehaviour();
try
{
if (nodeService.exists(filePlan) == true)
{
Set<NodeRef> holds = freezeService.getHolds(filePlan);
for (NodeRef hold : holds)
{
freezeService.relinquish(hold);
}
}
if (nodeService.exists(folder) == true)
{
// Delete the folder
nodeService.deleteNode(folder);
}
if (siteService.getSite(siteId) != null)
{
// Delete the site
siteService.deleteSite(siteId);
}
// delete the collaboration site (if required)
if (isCollaborationSiteTest() == true && siteService.getSite(COLLABORATION_SITE_ID) != null)
{
siteService.deleteSite(COLLABORATION_SITE_ID);
}
}
finally
{
filter.enableBehaviour();
}
}
/**
* @see org.alfresco.util.RetryingTransactionHelperTestCase#getRetryingTransactionHelper()
*/
@Override
public RetryingTransactionHelper getRetryingTransactionHelper()
{
return retryingTransactionHelper;
}
/**
* Setup test data for tests
*/
protected void setupTestData()
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
setupTestDataImpl();
if (isRecordTest() == true)
{
setupTestRecords();
}
return null;
}
@Override
public void test(Void result) throws Exception
{
if (isRecordTest() == true)
{
// declare a record
utils.declareRecord(recordDeclaredOne);
utils.declareRecord(recordDeclaredTwo);
}
// unfiled container
unfiledContainer = filePlanService.getUnfiledContainer(filePlan);
assertNotNull(unfiledContainer);
}
}, AuthenticationUtil.getSystemUserName());
}
/**
* Impl of test data setup
*/
protected void setupTestDataImpl()
{
AuthorityDAO authDao = (AuthorityDAO)applicationContext.getBean("authorityDAO");
if (authDao.authorityExists(AuthenticationUtil.getSystemUserName()) == false)
{
createPerson(AuthenticationUtil.getSystemUserName(), false);
}
assertTrue("No person object for System available.", authDao.authorityExists(AuthenticationUtil.getSystemUserName()));
storeRef = StoreRef.STORE_REF_WORKSPACE_SPACESSTORE;
rootNodeRef = nodeService.getRootNode(storeRef);
// Create folder
String containerName = "RM2_" + System.currentTimeMillis();
Map<QName, Serializable> containerProps = new HashMap<QName, Serializable>(1);
containerProps.put(ContentModel.PROP_NAME, containerName);
folder = nodeService.createNode(
rootNodeRef,
ContentModel.ASSOC_CHILDREN,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, containerName),
ContentModel.TYPE_FOLDER,
containerProps).getChildRef();
assertNotNull("Could not create base folder", folder);
permissionService.setPermission(folder, "rmadmin", PermissionService.WRITE, true);
permissionService.setPermission(folder, "rmadmin", PermissionService.ADD_CHILDREN, true);
siteId = GUID.generate();
siteInfo = siteService.createSite(
"rm-site-dashboard",
siteId,
"title",
"descrition",
SiteVisibility.PUBLIC,
RecordsManagementModel.TYPE_RM_SITE);
filePlan = siteService.getContainer(siteId, RmSiteType.COMPONENT_DOCUMENT_LIBRARY);
assertNotNull("Site document library container was not created successfully.", filePlan);
// Create RM container
rmContainer = filePlanService.createRecordCategory(filePlan, "rmContainer");
assertNotNull("Could not create rm container", rmContainer);
// Create disposition schedule
dispositionSchedule = utils.createBasicDispositionSchedule(rmContainer);
// Create RM folder
rmFolder = recordFolderService.createRecordFolder(rmContainer, "rmFolder");
assertNotNull("Could not create rm folder", rmFolder);
}
protected void setupTestRecords()
{
recordOne = utils.createRecord(rmFolder, "one.txt");
recordTwo = utils.createRecord(rmFolder, "two.txt");
recordThree = utils.createRecord(rmFolder, "three.txt");
recordFour = utils.createRecord(rmFolder, "four.txt");
recordFive = utils.createRecord(rmFolder, "five.txt");
recordDeclaredOne = utils.createRecord(rmFolder, "declaredOne.txt");
recordDeclaredTwo = utils.createRecord(rmFolder, "declaredTwo.txt");
}
protected void setupTestUsers(final NodeRef filePlan)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
setupTestUsersImpl(filePlan);
return null;
}
});
}
/**
*
* @param filePlan
*/
protected void setupTestUsersImpl(NodeRef filePlan)
{
userName = GUID.generate();
userPerson = createPerson(userName);
rmUserName = GUID.generate();
rmUserPerson = createPerson(rmUserName);
filePlanRoleService.assignRoleToAuthority(filePlan, FilePlanRoleService.ROLE_USER, rmUserName);
powerUserName = GUID.generate();
powerUserPerson = createPerson(powerUserName);
filePlanRoleService.assignRoleToAuthority(filePlan, FilePlanRoleService.ROLE_POWER_USER, powerUserName);
securityOfficerName = GUID.generate();
securityOfficerPerson = createPerson(securityOfficerName);
filePlanRoleService.assignRoleToAuthority(filePlan, FilePlanRoleService.ROLE_SECURITY_OFFICER, securityOfficerName);
recordsManagerName = GUID.generate();
recordsManagerPerson = createPerson(recordsManagerName);
filePlanRoleService.assignRoleToAuthority(filePlan, FilePlanRoleService.ROLE_RECORDS_MANAGER, recordsManagerName);
rmAdminName = GUID.generate();
rmAdminPerson = createPerson(rmAdminName);
filePlanRoleService.assignRoleToAuthority(filePlan, FilePlanRoleService.ROLE_ADMIN, rmAdminName);
testUsers = new String[]
{
userName,
rmUserName,
powerUserName,
securityOfficerName,
recordsManagerName,
rmAdminName
};
if (isFillingForAllUsers() == true)
{
// Give all the users file permission objects
for (String user : testUsers)
{
filePlanPermissionService.setPermission(filePlan, user, FILING);
filePlanPermissionService.setPermission(rmContainer, user, FILING);
filePlanPermissionService.setPermission(rmFolder, user, FILING);
filePlanPermissionService.setPermission(unfiledContainer, user, FILING);
}
}
}
/**
* Util method to create a person.
* @param userName user name
* @return NodeRef user node reference
*/
protected NodeRef createPerson(String userName, boolean createAuth)
{
if (createAuth == true)
{
authenticationService.createAuthentication(userName, "password".toCharArray());
}
Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(ContentModel.PROP_USERNAME, userName);
return personService.createPerson(properties);
}
protected NodeRef createPerson(String userName)
{
return createPerson(userName, true);
}
/**
* Setup multi hierarchy test data
*/
protected void setupMultiHierarchyTestData()
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
// As system user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
// Do setup
setupMultiHierarchyTestDataImpl();
return null;
}
});
}
/**
* Impl of multi hierarchy test data
*/
protected void setupMultiHierarchyTestDataImpl()
{
// Create root mh container
mhContainer = filePlanService.createRecordCategory(filePlan, "mhContainer");
// Level 1
mhContainer11 = filePlanService.createRecordCategory(mhContainer, "mhContainer11");
mhDispositionSchedule11 = utils.createBasicDispositionSchedule(mhContainer11, "ds11", CommonRMTestUtils.DEFAULT_DISPOSITION_AUTHORITY, false, true);
mhContainer12 = filePlanService.createRecordCategory(mhContainer, "mhContainer12");
mhDispositionSchedule12 = utils.createBasicDispositionSchedule(mhContainer12, "ds12", CommonRMTestUtils.DEFAULT_DISPOSITION_AUTHORITY, false, true);
// Level 2
mhContainer21 = filePlanService.createRecordCategory(mhContainer11, "mhContainer21");
mhContainer22 = filePlanService.createRecordCategory(mhContainer12, "mhContainer22");
mhContainer23 = filePlanService.createRecordCategory(mhContainer12, "mhContainer23");
mhDispositionSchedule23 = utils.createBasicDispositionSchedule(mhContainer23, "ds23", CommonRMTestUtils.DEFAULT_DISPOSITION_AUTHORITY, false, true);
// Level 3
mhContainer31 = filePlanService.createRecordCategory(mhContainer21, "mhContainer31");
mhContainer32 = filePlanService.createRecordCategory(mhContainer22, "mhContainer32");
mhContainer33 = filePlanService.createRecordCategory(mhContainer22, "mhContainer33");
mhDispositionSchedule33 = utils.createBasicDispositionSchedule(mhContainer33, "ds33", CommonRMTestUtils.DEFAULT_DISPOSITION_AUTHORITY, true, true);
mhContainer34 = filePlanService.createRecordCategory(mhContainer23, "mhContainer34");
mhContainer35 = filePlanService.createRecordCategory(mhContainer23, "mhContainer35");
mhDispositionSchedule35 = utils.createBasicDispositionSchedule(mhContainer35, "ds35", CommonRMTestUtils.DEFAULT_DISPOSITION_AUTHORITY, true, true);
// Record folders
mhRecordFolder41 = recordFolderService.createRecordFolder(mhContainer31, "mhFolder41");
mhRecordFolder42 = recordFolderService.createRecordFolder(mhContainer32, "mhFolder42");
mhRecordFolder43 = recordFolderService.createRecordFolder(mhContainer33, "mhFolder43");
mhRecordFolder44 = recordFolderService.createRecordFolder(mhContainer34, "mhFolder44");
mhRecordFolder45 = recordFolderService.createRecordFolder(mhContainer35, "mhFolder45");
}
protected void setupCollaborationSiteTestData()
{
doTestInTransaction(new Test<Void>()
{
public Void run()
{
setupCollaborationSiteTestDataImpl();
return null;
}
}, AuthenticationUtil.getAdminUserName());
}
protected void setupCollaborationSiteTestDataImpl()
{
// create collaboration site
collaborationSite = siteService.createSite("preset", COLLABORATION_SITE_ID, "title", "description", SiteVisibility.PRIVATE);
documentLibrary = SiteServiceImpl.getSiteContainer(
COLLABORATION_SITE_ID,
SiteService.DOCUMENT_LIBRARY,
true,
siteService,
transactionService,
taggingService);
assertNotNull("Collaboration site document library component was not successfully created.", documentLibrary);
// create a folder and documents
dmFolder = fileFolderService.create(documentLibrary, "collabFolder", ContentModel.TYPE_FOLDER).getNodeRef();
dmDocument = fileFolderService.create(dmFolder, "collabDocument.txt", ContentModel.TYPE_CONTENT).getNodeRef();
dmConsumer = GUID.generate();
dmConsumerNodeRef = createPerson(dmConsumer);
siteService.setMembership(COLLABORATION_SITE_ID, dmConsumer, SiteModel.SITE_CONSUMER);
dmCollaborator = GUID.generate();
dmCollaboratorNodeRef = createPerson(dmCollaborator);
siteService.setMembership(COLLABORATION_SITE_ID, dmCollaborator, SiteModel.SITE_COLLABORATOR);
}
/**
* Override to ensure the tests are run as the 'rmadmin' user by default.
*/
@Override
protected <A> A doTestInTransaction(Test<A> test)
{
return super.doTestInTransaction(test, rmAdminUserName);
}
@Override
protected void doTestInTransaction(FailureTest test)
{
super.doTestInTransaction(test, rmAdminUserName);
}
/**
* Helper class to try and simplify {@link Void} tests.
*
* @author Roy Wetherall
* @since 2.1
*/
protected abstract class VoidTest extends Test<Void>
{
@Override
public Void run() throws Exception
{
runImpl();
return null;
}
public abstract void runImpl() throws Exception;
@Override
public void test(Void result) throws Exception
{
testImpl();
}
public void testImpl() throws Exception
{
// empty implementation
}
}
}

View File

@@ -0,0 +1,384 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionService;
import org.alfresco.module.org_alfresco_module_rm.admin.RecordsManagementAdminService;
import org.alfresco.module.org_alfresco_module_rm.audit.RecordsManagementAuditService;
import org.alfresco.module.org_alfresco_module_rm.capability.CapabilityService;
import org.alfresco.module.org_alfresco_module_rm.caveat.RMCaveatConfigService;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionSchedule;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionService;
import org.alfresco.module.org_alfresco_module_rm.event.RecordsManagementEventService;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanService;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.model.rma.type.RmSiteType;
import org.alfresco.module.org_alfresco_module_rm.recordfolder.RecordFolderService;
import org.alfresco.module.org_alfresco_module_rm.role.FilePlanRoleService;
import org.alfresco.module.org_alfresco_module_rm.search.RecordsManagementSearchService;
import org.alfresco.module.org_alfresco_module_rm.security.FilePlanPermissionService;
import org.alfresco.module.org_alfresco_module_rm.vital.VitalRecordService;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.site.SiteServiceImpl;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.service.cmr.dictionary.DictionaryService;
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.repository.Period;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.AuthorityType;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.cmr.site.SiteInfo;
import org.alfresco.service.cmr.site.SiteService;
import org.alfresco.service.cmr.site.SiteVisibility;
import org.alfresco.service.cmr.tagging.TaggingService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.GUID;
import org.alfresco.util.PropertyMap;
import org.springframework.context.ApplicationContext;
/**
* @author Roy Wetherall
*/
public class BaseRMWebScriptTestCase extends BaseWebScriptTest
{
/** Collab site id */
protected static final String COLLAB_SITE_ID = "myCollabSite";
/** Common test utils */
protected CommonRMTestUtils utils;
/** Application context */
protected ApplicationContext applicationContext;
/** Services */
protected NodeService nodeService;
protected ContentService contentService;
protected DictionaryService dictionaryService;
protected RetryingTransactionHelper retryingTransactionHelper;
protected PolicyComponent policyComponent;
protected NamespaceService namespaceService;
protected SearchService searchService;
protected SiteService siteService;
protected MutableAuthenticationService authenticationService;
protected AuthorityService authorityService;
protected PersonService personService;
protected TransactionService transactionService;
protected TaggingService taggingService;
/** RM Services */
protected DispositionService dispositionService;
protected RecordsManagementEventService eventService;
protected RecordsManagementAdminService adminService;
protected RecordsManagementActionService actionService;
protected RecordsManagementSearchService rmSearchService;
protected FilePlanRoleService filePlanRoleService;
protected FilePlanPermissionService filePlanPermissionService;
protected RecordsManagementAuditService auditService;
protected CapabilityService capabilityService;
protected VitalRecordService vitalRecordService;
protected FilePlanService filePlanService;
protected RecordFolderService recordFolderService;
protected RMCaveatConfigService caveatConfigService;
/** test data */
protected String siteId;
protected StoreRef storeRef;
protected NodeRef rootNodeRef;
protected SiteInfo siteInfo;
protected NodeRef folder;
protected NodeRef filePlan;
protected NodeRef recordSeries; // A category with no disposition schedule
protected NodeRef recordCategory;
protected DispositionSchedule dispositionSchedule;
protected NodeRef recordFolder;
protected NodeRef recordFolder2;
/**
* Indicates whether the test collaboration site should be created
* or not.
*/
protected boolean isCollaborationSiteTest()
{
return false;
}
@Override
protected void setUp() throws Exception
{
super.setUp();
// Initialise the service beans
initServices();
// Setup test data
setupTestData();
}
/**
* Initialise the service beans.
*/
protected void initServices()
{
applicationContext = getServer().getApplicationContext();
// Common test utils
utils = new CommonRMTestUtils(applicationContext);
// Get services
nodeService = (NodeService)applicationContext.getBean("NodeService");
contentService = (ContentService)applicationContext.getBean("ContentService");
retryingTransactionHelper = (RetryingTransactionHelper)applicationContext.getBean("retryingTransactionHelper");
namespaceService = (NamespaceService)applicationContext.getBean("NamespaceService");
searchService = (SearchService)applicationContext.getBean("SearchService");
policyComponent = (PolicyComponent)applicationContext.getBean("policyComponent");
dictionaryService = (DictionaryService)applicationContext.getBean("DictionaryService");
siteService = (SiteService)applicationContext.getBean("SiteService");
authorityService = (AuthorityService)applicationContext.getBean("AuthorityService");
authenticationService = (MutableAuthenticationService)applicationContext.getBean("AuthenticationService");
personService = (PersonService)applicationContext.getBean("PersonService");
transactionService = (TransactionService)applicationContext.getBean("TransactionService");
taggingService = (TaggingService)applicationContext.getBean("TaggingService");
// Get RM services
dispositionService = (DispositionService)applicationContext.getBean("DispositionService");
eventService = (RecordsManagementEventService)applicationContext.getBean("RecordsManagementEventService");
adminService = (RecordsManagementAdminService)applicationContext.getBean("RecordsManagementAdminService");
actionService = (RecordsManagementActionService)applicationContext.getBean("RecordsManagementActionService");
rmSearchService = (RecordsManagementSearchService)applicationContext.getBean("RecordsManagementSearchService");
filePlanRoleService = (FilePlanRoleService)applicationContext.getBean("FilePlanRoleService");
filePlanPermissionService = (FilePlanPermissionService)applicationContext.getBean("FilePlanPermissionService");
auditService = (RecordsManagementAuditService)applicationContext.getBean("RecordsManagementAuditService");
capabilityService = (CapabilityService)applicationContext.getBean("CapabilityService");
vitalRecordService = (VitalRecordService)applicationContext.getBean("VitalRecordService");
filePlanService = (FilePlanService)applicationContext.getBean("FilePlanService");
recordFolderService = (RecordFolderService)applicationContext.getBean("RecordFolderService");
caveatConfigService = (RMCaveatConfigService)applicationContext.getBean("CaveatConfigService");
}
/**
* @see junit.framework.TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
// As system user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
// Do the tear down
tearDownImpl();
return null;
}
});
}
/**
* Tear down implementation
*/
protected void tearDownImpl()
{
// Delete the folder
nodeService.deleteNode(folder);
// Delete the site
siteService.deleteSite(siteId);
// Delete the collaboration site (if required)
if (isCollaborationSiteTest() == true)
{
siteService.deleteSite(COLLAB_SITE_ID);
}
}
/**
* Setup test data for tests
*/
protected void setupTestData()
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
setupTestDataImpl();
return null;
}
});
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
// As system user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
filePlanRoleService.assignRoleToAuthority(filePlan, FilePlanRoleService.ROLE_ADMIN, "rmadmin");
return null;
}
});
}
/**
* Impl of test data setup
*/
protected void setupTestDataImpl()
{
storeRef = StoreRef.STORE_REF_WORKSPACE_SPACESSTORE;
rootNodeRef = nodeService.getRootNode(storeRef);
// Create folder
String containerName = "RM2_" + System.currentTimeMillis();
Map<QName, Serializable> containerProps = new HashMap<QName, Serializable>(1);
containerProps.put(ContentModel.PROP_NAME, containerName);
folder = nodeService.createNode(
rootNodeRef,
ContentModel.ASSOC_CHILDREN,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, containerName),
ContentModel.TYPE_FOLDER,
containerProps).getChildRef();
assertNotNull("Could not create base folder", folder);
// Create the site
siteId = GUID.generate();
siteInfo = siteService.createSite("rm-site-dashboard", siteId, "title", "descrition", SiteVisibility.PUBLIC, RecordsManagementModel.TYPE_RM_SITE);
filePlan = siteService.getContainer(siteId, RmSiteType.COMPONENT_DOCUMENT_LIBRARY);
assertNotNull("Site document library container was not created successfully.", filePlan);
recordSeries = filePlanService.createRecordCategory(filePlan, "recordSeries");
assertNotNull("Could not create record category with no disposition schedule", recordSeries);
recordCategory = filePlanService.createRecordCategory(recordSeries, "rmContainer");
assertNotNull("Could not create record category", recordCategory);
// Make vital record
vitalRecordService.setVitalRecordDefintion(recordCategory, true, new Period("week|1"));
// Create disposition schedule
dispositionSchedule = utils.createBasicDispositionSchedule(recordCategory);
// Create RM folder
recordFolder = recordFolderService.createRecordFolder(recordCategory, "rmFolder");
assertNotNull("Could not create rm folder", recordFolder);
recordFolder2 = recordFolderService.createRecordFolder(recordCategory, "rmFolder2");
assertNotNull("Could not create rm folder 2", recordFolder2);
// Create collaboration data
if (isCollaborationSiteTest() == true)
{
setupCollaborationSiteTestData();
}
}
protected void setupCollaborationSiteTestData()
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
// As system user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
setupCollaborationSiteTestDataImpl();
return null;
}
});
}
protected void setupCollaborationSiteTestDataImpl()
{
// create collaboration site
siteService.createSite("preset", COLLAB_SITE_ID, "title", "description", SiteVisibility.PRIVATE);
NodeRef documentLibrary = SiteServiceImpl.getSiteContainer(
COLLAB_SITE_ID,
SiteService.DOCUMENT_LIBRARY,
true,
siteService,
transactionService,
taggingService);
assertNotNull("Collaboration site document library component was not successfully created.", documentLibrary);
}
protected void createUser(String userName)
{
if (authenticationService.authenticationExists(userName) == false)
{
authenticationService.createAuthentication(userName, "PWD".toCharArray());
PropertyMap ppOne = new PropertyMap(4);
ppOne.put(ContentModel.PROP_USERNAME, userName);
ppOne.put(ContentModel.PROP_AUTHORITY_DISPLAY_NAME, "title" + userName);
ppOne.put(ContentModel.PROP_FIRSTNAME, "firstName");
ppOne.put(ContentModel.PROP_LASTNAME, "lastName");
ppOne.put(ContentModel.PROP_EMAIL, "email@email.com");
ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");
personService.createPerson(ppOne);
}
}
protected void deleteUser(String userName)
{
if (authenticationService.authenticationExists(userName) == true)
{
personService.deletePerson(userName);
}
}
protected void createGroup(String groupName)
{
if (authorityService.authorityExists(groupName) == false)
{
authorityService.createAuthority(AuthorityType.GROUP, groupName);
}
}
protected void deleteGroup(String groupName)
{
if (authorityService.authorityExists(groupName) == true)
{
authorityService.deleteAuthority(groupName, true);
}
}
}

View File

@@ -0,0 +1,300 @@
/**
*
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionService;
import org.alfresco.module.org_alfresco_module_rm.action.impl.CutOffAction;
import org.alfresco.module.org_alfresco_module_rm.action.impl.DestroyAction;
import org.alfresco.module.org_alfresco_module_rm.action.impl.FreezeAction;
import org.alfresco.module.org_alfresco_module_rm.action.impl.TransferAction;
import org.alfresco.module.org_alfresco_module_rm.capability.Capability;
import org.alfresco.module.org_alfresco_module_rm.capability.CapabilityService;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionSchedule;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionService;
import org.alfresco.module.org_alfresco_module_rm.dod5015.DOD5015Model;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.model.security.ModelSecurityService;
import org.alfresco.module.org_alfresco_module_rm.role.FilePlanRoleService;
import org.alfresco.module.org_alfresco_module_rm.role.Role;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;
/**
* @author Roy Wetherall
*/
public class CommonRMTestUtils implements RecordsManagementModel
{
private DispositionService dispositionService;
private NodeService nodeService;
private ContentService contentService;
private RecordsManagementActionService actionService;
private ModelSecurityService modelSecurityService;
private FilePlanRoleService filePlanRoleService;
private CapabilityService capabilityService;
/** test values */
public static final String DEFAULT_DISPOSITION_AUTHORITY = "disposition authority";
public static final String DEFAULT_DISPOSITION_INSTRUCTIONS = "disposition instructions";
public static final String DEFAULT_DISPOSITION_DESCRIPTION = "disposition action description";
public static final String DEFAULT_EVENT_NAME = "case_closed";
public static final String PERIOD_NONE = "none|0";
public static final String PERIOD_IMMEDIATELY = "immediately|0";
public CommonRMTestUtils(ApplicationContext applicationContext)
{
dispositionService = (DispositionService)applicationContext.getBean("DispositionService");
nodeService = (NodeService)applicationContext.getBean("NodeService");
contentService = (ContentService)applicationContext.getBean("ContentService");
actionService = (RecordsManagementActionService)applicationContext.getBean("RecordsManagementActionService");
modelSecurityService = (ModelSecurityService)applicationContext.getBean("ModelSecurityService");
filePlanRoleService = (FilePlanRoleService)applicationContext.getBean("FilePlanRoleService");
capabilityService = (CapabilityService)applicationContext.getBean("CapabilityService");
}
/**
*
* @param container
* @return
*/
public DispositionSchedule createBasicDispositionSchedule(NodeRef container)
{
return createBasicDispositionSchedule(container, DEFAULT_DISPOSITION_INSTRUCTIONS, DEFAULT_DISPOSITION_AUTHORITY, false, true);
}
/**
*
* @param container
* @param dispositionInstructions
* @param dispositionAuthority
* @param isRecordLevel
* @param defaultDispositionActions
* @return
*/
public DispositionSchedule createBasicDispositionSchedule(
NodeRef container,
String dispositionInstructions,
String dispositionAuthority,
boolean isRecordLevel,
boolean defaultDispositionActions)
{
return createDispositionSchedule(container, dispositionInstructions, dispositionAuthority, isRecordLevel, defaultDispositionActions, false);
}
/**
*
* @param container
* @param dispositionInstructions
* @param dispositionAuthority
* @param isRecordLevel
* @param defaultDispositionActions
* @param extendedDispositionSchedule
* @return
*/
public DispositionSchedule createDispositionSchedule(
NodeRef container,
String dispositionInstructions,
String dispositionAuthority,
boolean isRecordLevel,
boolean defaultDispositionActions,
boolean extendedDispositionSchedule)
{
Map<QName, Serializable> dsProps = new HashMap<QName, Serializable>(3);
dsProps.put(PROP_DISPOSITION_AUTHORITY, dispositionAuthority);
dsProps.put(PROP_DISPOSITION_INSTRUCTIONS, dispositionInstructions);
dsProps.put(PROP_RECORD_LEVEL_DISPOSITION, isRecordLevel);
DispositionSchedule dispositionSchedule = dispositionService.createDispositionSchedule(container, dsProps);
if (defaultDispositionActions == true)
{
Map<QName, Serializable> adParams = new HashMap<QName, Serializable>(3);
adParams.put(PROP_DISPOSITION_ACTION_NAME, CutOffAction.NAME);
adParams.put(PROP_DISPOSITION_DESCRIPTION, DEFAULT_DISPOSITION_DESCRIPTION);
List<String> events = new ArrayList<String>(1);
events.add(DEFAULT_EVENT_NAME);
adParams.put(PROP_DISPOSITION_EVENT, (Serializable)events);
dispositionService.addDispositionActionDefinition(dispositionSchedule, adParams);
if (extendedDispositionSchedule == true)
{
adParams = new HashMap<QName, Serializable>(4);
adParams.put(PROP_DISPOSITION_ACTION_NAME, TransferAction.NAME);
adParams.put(PROP_DISPOSITION_DESCRIPTION, DEFAULT_DISPOSITION_DESCRIPTION);
adParams.put(PROP_DISPOSITION_PERIOD, PERIOD_IMMEDIATELY);
adParams.put(PROP_DISPOSITION_LOCATION, StringUtils.EMPTY);
dispositionService.addDispositionActionDefinition(dispositionSchedule, adParams);
}
adParams = new HashMap<QName, Serializable>(3);
adParams.put(PROP_DISPOSITION_ACTION_NAME, DestroyAction.NAME);
adParams.put(PROP_DISPOSITION_DESCRIPTION, DEFAULT_DISPOSITION_DESCRIPTION);
adParams.put(PROP_DISPOSITION_PERIOD, PERIOD_IMMEDIATELY);
dispositionService.addDispositionActionDefinition(dispositionSchedule, adParams);
}
return dispositionSchedule;
}
public NodeRef createRecord(NodeRef recordFolder, String name)
{
return createRecord(recordFolder, name, null, "Some test content");
}
public NodeRef createRecord(NodeRef recordFolder, String name, String title)
{
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
props.put(ContentModel.PROP_TITLE, title);
return createRecord(recordFolder, name, props, "Some test content");
}
public NodeRef createRecord(NodeRef recordFolder, String name, Map<QName, Serializable> properties, String content)
{
// Create the document
if (properties == null)
{
properties = new HashMap<QName, Serializable>(1);
}
if (properties.containsKey(ContentModel.PROP_NAME) == false)
{
properties.put(ContentModel.PROP_NAME, name);
}
NodeRef recordOne = nodeService.createNode(recordFolder,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name),
ContentModel.TYPE_CONTENT,
properties).getChildRef();
// Set the content
ContentWriter writer = contentService.getWriter(recordOne, ContentModel.PROP_CONTENT, true);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
writer.setEncoding("UTF-8");
writer.putContent(content);
return recordOne;
}
public void declareRecord(final NodeRef record)
{
AuthenticationUtil.runAs(new RunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
modelSecurityService.setEnabled(false);
try
{
// Declare record
nodeService.setProperty(record, DOD5015Model.PROP_PUBLICATION_DATE, new Date());
nodeService.setProperty(record, DOD5015Model.PROP_MEDIA_TYPE, "mediaTypeValue");
nodeService.setProperty(record, DOD5015Model.PROP_FORMAT, "formatValue");
nodeService.setProperty(record, DOD5015Model.PROP_DATE_RECEIVED, new Date());
nodeService.setProperty(record, RecordsManagementModel.PROP_DATE_FILED, new Date());
nodeService.setProperty(record, DOD5015Model.PROP_ORIGINATOR, "origValue");
nodeService.setProperty(record, DOD5015Model.PROP_ORIGINATING_ORGANIZATION, "origOrgValue");
nodeService.setProperty(record, ContentModel.PROP_TITLE, "titleValue");
actionService.executeRecordsManagementAction(record, "declareRecord");
}
finally
{
modelSecurityService.setEnabled(true);
}
return null;
}
}, AuthenticationUtil.getAdminUserName());
}
public void closeFolder(final NodeRef recordFolder)
{
AuthenticationUtil.runAs(new RunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
modelSecurityService.setEnabled(false);
try
{
actionService.executeRecordsManagementAction(recordFolder, "closeRecordFolder");
}
finally
{
modelSecurityService.setEnabled(true);
}
return null;
}
}, AuthenticationUtil.getAdminUserName());
}
public void freeze(final NodeRef nodeRef)
{
AuthenticationUtil.runAs(new RunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(FreezeAction.PARAM_REASON, "Freeze reason.");
actionService.executeRecordsManagementAction(nodeRef, "freeze", params);
return null;
}
}, AuthenticationUtil.getSystemUserName());
}
public void unfreeze(final NodeRef nodeRef)
{
AuthenticationUtil.runAs(new RunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
actionService.executeRecordsManagementAction(nodeRef, "unfreeze");
return null;
}
}, AuthenticationUtil.getSystemUserName());
}
public Role createRole(NodeRef filePlan, String roleName, String ... capabilityNames)
{
Set<Capability> capabilities = new HashSet<Capability>(capabilityNames.length);
for (String name : capabilityNames)
{
Capability capability = capabilityService.getCapability(name);
if (capability == null)
{
throw new AlfrescoRuntimeException("capability " + name + " not found.");
}
capabilities.add(capability);
}
return filePlanRoleService.createRole(filePlan, roleName, roleName, capabilities);
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.capability.Capability;
import org.alfresco.module.org_alfresco_module_rm.capability.Group;
/**
* Utility test case to generate a report of the capabilities in the system.
*
* @author Roy Wetherall
* @since 2.1
*/
public class GenerateCapabilityReport extends BaseRMTestCase
{
public void testGetCapability() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
FileWriter writer = new FileWriter("c:\\mywork\\capabilityReport.csv");
BufferedWriter out = new BufferedWriter(writer);
try
{
Set<Capability> capabilities = capabilityService.getCapabilities(true);
for (Capability capability : capabilities)
{
Group group = capability.getGroup();
String groupId = "none";
if (group != null)
{
groupId = group.getId();
}
out.write(groupId);
out.write(",");
out.write(capability.getName());
out.write(",");
out.write(Boolean.toString(capability.isPrivate()));
out.write("\n");
}
}
finally
{
out.close();
}
return null;
}
});
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import org.alfresco.module.org_alfresco_module_rm.action.RMActionExecuterAbstractBase;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.repository.NodeRef;
public class TestAction extends RMActionExecuterAbstractBase
{
public static final String NAME = "testAction";
public static final String PARAM = "testActionParam";
public static final String PARAM_VALUE = "value";
@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef)
{
if (action.getParameterValue(PARAM).equals(PARAM_VALUE) == false)
{
throw new RuntimeException("Unexpected parameter value. Expected " + PARAM_VALUE + " actual " + action.getParameterValue(PARAM));
}
this.nodeService.addAspect(actionedUponNodeRef, ASPECT_RECORD, null);
}
@Override
public boolean isDispositionAction()
{
return true;
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import org.alfresco.module.org_alfresco_module_rm.action.RMActionExecuterAbstractBase;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.repository.NodeRef;
public class TestAction2 extends RMActionExecuterAbstractBase
{
public static final String NAME = "testAction2";
@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef)
{
// Do nothing
}
@Override
public boolean isDispositionAction()
{
return false;
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.module.org_alfresco_module_rm.action.RMActionExecuterAbstractBase;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.repository.NodeRef;
public class TestActionParams extends RMActionExecuterAbstractBase
{
public static final String NAME = "testActionParams";
public static final String PARAM_DATE = "paramDate";
@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef)
{
Object dateValue = action.getParameterValue(PARAM_DATE);
if ((dateValue instanceof java.util.Date) == false)
{
throw new AlfrescoRuntimeException("Param was not a Date as expected.");
}
}
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.action.RMActionExecuterAbstractBase;
import org.alfresco.repo.action.ParameterDefinitionImpl;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ParameterDefinition;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.repository.NodeRef;
import org.springframework.extensions.surf.util.I18NUtil;
public class TestActionPropertySubs extends RMActionExecuterAbstractBase
{
public static final String NAME = "testActionPropertySubs";
@Override
protected void addParameterDefinitions(List<ParameterDefinition> paramList)
{
paramList.add(new ParameterDefinitionImpl("dayShort", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("dayShort2", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("dayLong", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("dayNumber", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("dayYear", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("monthShort", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("monthShort2", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("monthLong", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("monthNumber", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("yearShort", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("yearShort2", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("yearLong", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("yearWeek", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("name", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("company", DataTypeDefinition.TEXT, false, ""));
paramList.add(new ParameterDefinitionImpl("combo", DataTypeDefinition.TEXT, false, ""));
}
@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef)
{
Date date = new Date();
String dayShort = new SimpleDateFormat("EE").format(date);
String dayLong = new SimpleDateFormat("EEEE").format(date);
String dayNumber = new SimpleDateFormat("u").format(date);
String dayYear = new SimpleDateFormat("D").format(date);
String monthShort = new SimpleDateFormat("MMM").format(date);
String monthLong = new SimpleDateFormat("MMMM").format(date);
String monthNumber = new SimpleDateFormat("MM").format(date);
String yearShort = new SimpleDateFormat("yy").format(date);
String yearLong = new SimpleDateFormat("yyyy").format(date);
String yearWeek = new SimpleDateFormat("w").format(date);
String name = (String) nodeService.getProperty(actionedUponNodeRef, ContentModel.PROP_NAME);
String company = I18NUtil.getMessage("test.company");
assertEquals(dayShort, (String) action.getParameterValue("dayShort"));
assertEquals(dayShort, (String) action.getParameterValue("dayShort2"));
assertEquals(dayLong, (String) action.getParameterValue("dayLong"));
assertEquals(dayNumber, (String) action.getParameterValue("dayNumber"));
assertEquals(dayYear, (String) action.getParameterValue("dayYear"));
assertEquals(monthShort, (String) action.getParameterValue("monthShort"));
assertEquals(monthShort, (String) action.getParameterValue("monthShort2"));
assertEquals(monthLong, (String) action.getParameterValue("monthLong"));
assertEquals(monthNumber, (String) action.getParameterValue("monthNumber"));
assertEquals(yearShort, (String) action.getParameterValue("yearShort"));
assertEquals(yearShort, (String) action.getParameterValue("yearShort2"));
assertEquals(yearLong, (String) action.getParameterValue("yearLong"));
assertEquals(yearWeek, (String) action.getParameterValue("yearWeek"));
assertEquals(name, (String)action.getParameterValue("name"));
assertEquals(company, (String)action.getParameterValue("company"));
assertEquals(yearLong + "/" + monthShort + "/" + name + "-" + company +".txt", (String) action.getParameterValue("combo"));
}
private void assertEquals(String expected, String actual)
{
if (expected.equals(actual) == false)
{
throw new AlfrescoRuntimeException("Expected value " + expected + " does not match actual value " + actual);
}
}
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import java.util.List;
import org.alfresco.repo.action.executer.ActionExecuterAbstractBase;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ParameterDefinition;
import org.alfresco.service.cmr.repository.NodeRef;
/**
* @author Roy Wetherall
* @since 2.1
*/
public class TestDmAction extends ActionExecuterAbstractBase
{
@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef)
{
}
@Override
protected void addParameterDefinitions(List<ParameterDefinition> paramDefs)
{
}
}

View File

@@ -0,0 +1,11 @@
package org.alfresco.module.org_alfresco_module_rm.test.util;
import org.alfresco.service.cmr.repository.NodeRef;
public interface TestService
{
void testMethodOne(NodeRef nodeRef);
void testMethodTwo(NodeRef nodeRef);
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import org.alfresco.service.cmr.repository.NodeRef;
/**
* @author Roy Wetherall
* @since 2.1
*/
public class TestServiceImpl implements TestService
{
@Override
public void testMethodOne(NodeRef nodeRef)
{
}
@Override
public void testMethodTwo(NodeRef nodeRef)
{
}
}

View File

@@ -0,0 +1,221 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.util.EqualsHelper;
import org.springframework.extensions.webscripts.TestWebScriptServer;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Stand-alone Web Script Test Server
*
* @author davidc
*/
public class TestWebScriptRepoServer extends TestWebScriptServer
{
/**
* Main entry point.
*/
public static void main(String[] args)
{
try
{
TestWebScriptServer testServer = getTestServer();
AuthenticationUtil.setRunAsUserSystem();
testServer.rep();
}
catch(Throwable e)
{
StringWriter strWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(strWriter);
e.printStackTrace(printWriter);
System.out.println(strWriter.toString());
}
finally
{
System.exit(0);
}
}
private final static String[] CONFIG_LOCATIONS = new String[]
{
"classpath:alfresco/application-context.xml",
"classpath:alfresco/web-scripts-application-context.xml",
"classpath:alfresco/web-scripts-application-context-test.xml"
};
/** A static reference to the application context being used */
private static ClassPathXmlApplicationContext ctx;
private static String appendedTestConfiguration;
private RetryingTransactionHelper retryingTransactionHelper;
private AuthenticationService authenticationService;
/**
* Sets helper that provides transaction callbacks
*/
public void setTransactionHelper(RetryingTransactionHelper retryingTransactionHelper)
{
this.retryingTransactionHelper = retryingTransactionHelper;
}
/**
* @param authenticationService
*/
public void setAuthenticationService(AuthenticationService authenticationService)
{
this.authenticationService = authenticationService;
}
/**
* Get default user name
*/
protected String getDefaultUserName()
{
return AuthenticationUtil.getAdminUserName();
}
/**
* {@inheritDoc #getTestServer(String)}
*/
public static TestWebScriptServer getTestServer()
{
return getTestServer(null);
}
/**
* Start up a context and get the server bean.
* <p>
* This method will close and restart the application context only if the configuration has
* changed.
*
* @param appendTestConfigLocation additional context file to include in the application context
* @return Test Server
*/
public static synchronized TestWebScriptServer getTestServer(String appendTestConfigLocation)
{
if (TestWebScriptRepoServer.ctx != null)
{
boolean configChanged = !EqualsHelper.nullSafeEquals(
appendTestConfigLocation,
TestWebScriptRepoServer.appendedTestConfiguration);
if (configChanged)
{
// The config changed, so close the context (it'll be restarted later)
try
{
ctx.close();
ctx = null;
}
catch (Throwable e)
{
throw new RuntimeException("Failed to shut down existing application context", e);
}
}
else
{
// There is already a context with the required configuration
}
}
// Check if we need to start/restart the context
if (TestWebScriptRepoServer.ctx == null)
{
// Restart it
final String[] configLocations;
if (appendTestConfigLocation == null)
{
configLocations = CONFIG_LOCATIONS;
}
else
{
configLocations = new String[CONFIG_LOCATIONS.length+1];
System.arraycopy(CONFIG_LOCATIONS, 0, configLocations, 0, CONFIG_LOCATIONS.length);
configLocations[CONFIG_LOCATIONS.length] = appendTestConfigLocation;
}
TestWebScriptRepoServer.ctx = new ClassPathXmlApplicationContext(configLocations);
TestWebScriptRepoServer.appendedTestConfiguration = appendTestConfigLocation;
}
// Get the bean
TestWebScriptServer testServer = (org.alfresco.repo.web.scripts.TestWebScriptRepoServer)TestWebScriptRepoServer.ctx.getBean("webscripts.test");
return testServer;
}
/**
* Interpret a single command using the BufferedReader passed in for any data needed.
*
* @param line The unparsed command
* @return The textual output of the command.
*/
@Override
protected String interpretCommand(final String line)
throws IOException
{
try
{
if (username.startsWith("TICKET_"))
{
try
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
public Object execute() throws Exception
{
authenticationService.validate(username);
return null;
}
});
return executeCommand(line);
}
finally
{
authenticationService.clearCurrentSecurityContext();
}
}
}
catch(AuthenticationException e)
{
executeCommand("user " + getDefaultUserName());
}
// execute command in context of currently selected user
return AuthenticationUtil.runAs(new RunAsWork<String>()
{
@SuppressWarnings("synthetic-access")
public String doWork() throws Exception
{
return executeCommand(line);
}
}, username);
}
}

View File

@@ -0,0 +1,111 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.webscript;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* REST API Tests for Action Definitions
*
* @author Tuna Aksoy
* @since 2.1
*/
public class ActionDefinitionsRestApiTest extends BaseRMWebScriptTestCase
{
/** URL for the REST APIs */
private static final String RM_ACTIONDEFINITIONS_URL = "/api/rm/rm-actiondefinitions";
/**
* Test the REST API to retrieve the list of rm action definitions
*
* @throws IOException
* @throws JSONException
*/
public void testRmGetActionDefinitions() throws IOException, JSONException
{
// Send request
Response response = sendRequest(new GetRequest(RM_ACTIONDEFINITIONS_URL), Status.STATUS_OK);
// Check the content from the response
String contentAsString = response.getContentAsString();
assertNotNull(contentAsString);
// Convert the response to json and check the data
JSONObject contentAsJson = new JSONObject(contentAsString);
JSONArray data = contentAsJson.getJSONArray("data");
assertNotNull(data);
// Get a (sub)list of available dm action definitions
List<String> dmActionDefinitions = getDmActionDefinitions();
// Get the list of rm action definitions from the response and check it
List<String> rmActionDefinitions = new ArrayList<String>();
for (int i = 0; i < data.length(); i++)
{
String name = data.getJSONObject(i).getString("name");
assertNotNull(name);
rmActionDefinitions.add(name);
assertFalse(dmActionDefinitions.contains(name));
}
assertTrue(rmActionDefinitions.containsAll(getRmActionDefinitions()));
}
/**
* Returns a (sub)list of rm action definitions
*
* @return A (sub)list of rm action definitions
*/
private List<String> getRmActionDefinitions()
{
return Arrays.asList(new String[]
{
"reject",
"fileTo",
"declareRecord"
});
}
/**
* Returns a (sub)list of dm action definitions
*
* @return A (sub)list of dm action definitions
*/
private List<String> getDmActionDefinitions()
{
return Arrays.asList(new String[]
{
"check-in",
"check-out",
"mail",
"move",
"transform"
});
}
}

View File

@@ -0,0 +1,111 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.webscript;
import java.io.IOException;
import java.text.MessageFormat;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* REST API Test for Capabilities
*
* @author Tuna Aksoy
* @since 2.1
*/
public class CapabilitiesRestApiTest extends BaseRMWebScriptTestCase
{
/** URLs for the REST API */
private static final String GET_CAPABILITIES_URL = "/api/node/{0}/{1}/{2}/capabilities?";
/**
* Tests the REST API to get the list of capabilities
*
* @throws IOException
* @throws JSONException
*/
public void testGetCapabilitiesAction() throws IOException, JSONException
{
String baseURL = MessageFormat.format(GET_CAPABILITIES_URL,
filePlan.getStoreRef().getProtocol(),
filePlan.getStoreRef().getIdentifier(),
filePlan.getId());
// Format url and send request
String getUrl = String.format(baseURL + "includeAll=%s", true);
Response getResponse = sendRequest(new GetRequest(getUrl), Status.STATUS_OK);
// Check the content from the response
String getContentAsString = getResponse.getContentAsString();
assertNotNull(getContentAsString);
System.out.println(getContentAsString);
// Convert the response to json and check the data
JSONObject getContentAsJson = new JSONObject(getContentAsString);
JSONObject getData = getContentAsJson.getJSONObject("data");
assertNotNull(getData);
// Get the capabilities and check them
JSONArray getDataSets = getData.getJSONArray("capabilities");
assertNotNull(getDataSets);
// Format url and send another request with different parameter
getUrl = String.format(baseURL + "grouped=%s", true);
getResponse = sendRequest(new GetRequest(getUrl), Status.STATUS_OK);
// Check the content from the response
getContentAsString = getResponse.getContentAsString();
assertNotNull(getContentAsString);
// If both parameters are specified the result should be the same with only specifying the "grouped" parameter
getUrl = String.format(baseURL + "includeAll=%s&amp;grouped=%s", true, true);
getResponse = sendRequest(new GetRequest(getUrl), Status.STATUS_OK);
getContentAsString.equalsIgnoreCase(getResponse.getContentAsString());
// Convert the response to json and check the data
getContentAsJson = new JSONObject(getContentAsString);
getData = getContentAsJson.getJSONObject("data");
assertNotNull(getData);
// Get the grouped capabilities and check them
getDataSets = getData.getJSONArray("groupedCapabilities");
assertNotNull(getDataSets);
// Check the JSON structure
int length = getDataSets.length();
if (length > 0)
{
for (int i = 0; i < length; i++)
{
JSONObject jsonObject = getDataSets.getJSONObject(i);
String key = (String) jsonObject.keys().next();
JSONObject value = jsonObject.getJSONObject(key);
assertNotNull(value.getString("groupTitle"));
assertNotNull(value.getJSONObject("capabilities"));
}
}
}
}

View File

@@ -0,0 +1,93 @@
package org.alfresco.module.org_alfresco_module_rm.test.webscript;
import java.io.IOException;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
public class DataSetRestApiTest extends BaseRMWebScriptTestCase
{
/** URL for the REST APIs */
private static final String GET_DATASETS_URL = "/api/rma/datasets?site=%s";
//private static final String POST_DATASET_URL = "/api/rma/datasets/%s?site=%s";
/** Constant for the content type */
//private static final String APPLICATION_JSON = "application/json";
/**
* Test the REST API to retrieve details of available RM data sets
* and to import an RM data set into a file plan
*
* @throws IOException
* @throws JSONException
*/
public void testGetPostDataSetAction() throws IOException, JSONException
{
/** Test GET */
// Format url and send request
String getUrl = String.format(GET_DATASETS_URL, siteId);
Response getResponse = sendRequest(new GetRequest(getUrl), Status.STATUS_OK);
// Check the content from the response
String getContentAsString = getResponse.getContentAsString();
assertNotNull(getContentAsString);
// Convert the response to json and check the data
JSONObject getContentAsJson = new JSONObject(getContentAsString);
JSONObject getData = getContentAsJson.getJSONObject("data");
assertNotNull(getData);
// Get the data sets and check them
JSONArray getDataSets = getData.getJSONArray("datasets");
assertNotNull(getDataSets);
// Check the label and the id of the data sets
for (int i = 0; i < getDataSets.length(); i++)
{
JSONObject dataSet = (JSONObject) getDataSets.get(i);
assertTrue(dataSet.length() == 3);
assertNotNull(dataSet.get("label"));
assertNotNull(dataSet.get("id"));
assertNotNull(dataSet.get("isLoaded"));
}
/** Test POST */
// String dataSetId = getDataSets.getJSONObject(0).getString("id");
// if (StringUtils.isNotBlank(dataSetId))
// {
// // Format url and send request
// String url = String.format(POST_DATASET_URL, dataSetId, SITE_ID);
// Response response = sendRequest(new PostRequest(url, new JSONObject().toString(), APPLICATION_JSON), Status.STATUS_OK);
//
// // Check the content from the response
// String contentAsString = response.getContentAsString();
// assertNotNull(contentAsString);
//
// // Convert the response to json and check the result
// JSONObject contentAsJson = new JSONObject(contentAsString);
// String success = contentAsJson.getString("success");
// assertNotNull(success);
// assertTrue(success.equals("true"));
//
// // It is not possible to import the same data set into the same file plan
// response = sendRequest(new PostRequest(url, new JSONObject().toString(), APPLICATION_JSON), Status.STATUS_OK);
//
// // Check the content from the response
// contentAsString = response.getContentAsString();
// assertNotNull(contentAsString);
//
// // Convert the response to json and check the result
// contentAsJson = new JSONObject(contentAsString);
// success = contentAsJson.getString("success");
// assertNotNull(success);
// assertTrue(success.equals("false"));
// assertNotNull(contentAsJson.getString("message"));
// }
}
}

View File

@@ -0,0 +1,438 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.webscript;
import java.text.MessageFormat;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase;
import org.alfresco.module.org_alfresco_module_rm.test.util.CommonRMTestUtils;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.Period;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.util.GUID;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.springframework.extensions.webscripts.TestWebScriptServer.DeleteRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PutRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* This class tests the Rest API for disposition related operations
*
* @author Gavin Cornwell
*/
public class DispositionRestApiTest extends BaseRMWebScriptTestCase implements RecordsManagementModel
{
protected static StoreRef SPACES_STORE = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
protected static final String GET_SCHEDULE_URL_FORMAT = "/api/node/{0}/dispositionschedule";
protected static final String GET_LIFECYCLE_URL_FORMAT = "/api/node/{0}/nextdispositionaction";
protected static final String POST_ACTIONDEF_URL_FORMAT = "/api/node/{0}/dispositionschedule/dispositionactiondefinitions";
protected static final String DELETE_ACTIONDEF_URL_FORMAT = "/api/node/{0}/dispositionschedule/dispositionactiondefinitions/{1}";
protected static final String PUT_ACTIONDEF_URL_FORMAT = "/api/node/{0}/dispositionschedule/dispositionactiondefinitions/{1}";
protected static final String GET_LIST_URL = "/api/rma/admin/listofvalues";
protected static final String SERVICE_URL_PREFIX = "/alfresco/service";
protected static final String APPLICATION_JSON = "application/json";
public void testGetDispositionSchedule() throws Exception
{
// Test 404 status for non existent node
int expectedStatus = 404;
String nonExistentNode = "workspace/SpacesStore/09ca1e02-1c87-4a53-97e7-xxxxxxxxxxxx";
String nonExistentUrl = MessageFormat.format(GET_SCHEDULE_URL_FORMAT, nonExistentNode);
Response rsp = sendRequest(new GetRequest(nonExistentUrl), expectedStatus);
// Test 404 status for node that doesn't have dispostion schedule i.e. a record series
String seriesNodeUrl = recordSeries.toString().replace("://", "/");
String wrongNodeUrl = MessageFormat.format(GET_SCHEDULE_URL_FORMAT, seriesNodeUrl);
rsp = sendRequest(new GetRequest(wrongNodeUrl), expectedStatus);
// Test data structure returned from "AIS Audit Records"
expectedStatus = 200;
String categoryNodeUrl = recordCategory.toString().replace("://", "/");
String requestUrl = MessageFormat.format(GET_SCHEDULE_URL_FORMAT, categoryNodeUrl);
rsp = sendRequest(new GetRequest(requestUrl), expectedStatus);
assertEquals("application/json;charset=UTF-8", rsp.getContentType());
// get response as JSON
JSONObject jsonParsedObject = new JSONObject(new JSONTokener(rsp.getContentAsString()));
assertNotNull(jsonParsedObject);
// check JSON data
JSONObject dataObj = jsonParsedObject.getJSONObject("data");
assertNotNull(dataObj);
JSONObject rootDataObject = (JSONObject)dataObj;
assertEquals(10, rootDataObject.length());
// check individual data items
String serviceUrl = SERVICE_URL_PREFIX + requestUrl;
String url = rootDataObject.getString("url");
assertEquals(serviceUrl, url);
String authority = rootDataObject.getString("authority");
assertEquals(CommonRMTestUtils.DEFAULT_DISPOSITION_AUTHORITY, authority);
String instructions = rootDataObject.getString("instructions");
assertEquals(CommonRMTestUtils.DEFAULT_DISPOSITION_INSTRUCTIONS, instructions);
String actionsUrl = rootDataObject.getString("actionsUrl");
assertEquals(serviceUrl + "/dispositionactiondefinitions", actionsUrl);
boolean recordLevel = rootDataObject.getBoolean("recordLevelDisposition");
assertFalse(recordLevel);
assertFalse(rootDataObject.getBoolean("canStepsBeRemoved"));
JSONArray actions = rootDataObject.getJSONArray("actions");
assertNotNull(actions);
assertEquals(2, actions.length());
JSONObject action1 = (JSONObject)actions.get(0);
assertEquals(9, action1.length());
assertNotNull(action1.get("id"));
assertNotNull(action1.get("url"));
assertEquals(0, action1.getInt("index"));
assertEquals("cutoff", action1.getString("name"));
assertTrue(action1.getBoolean("eligibleOnFirstCompleteEvent"));
JSONObject action2 = (JSONObject)actions.get(1);
assertEquals(8, action2.length());
// make sure the disposition schedule node ref is present and valid
String scheduleNodeRefJSON = rootDataObject.getString("nodeRef");
NodeRef scheduleNodeRef = new NodeRef(scheduleNodeRefJSON);
assertTrue(this.nodeService.exists(scheduleNodeRef));
// create a new recordCategory node in the recordSeries and then get
// the disposition schedule
NodeRef newRecordCategory = filePlanService.createRecordCategory(recordSeries, GUID.generate());
dispositionService.createDispositionSchedule(newRecordCategory, null);
categoryNodeUrl = newRecordCategory.toString().replace("://", "/");
requestUrl = MessageFormat.format(GET_SCHEDULE_URL_FORMAT, categoryNodeUrl);
//System.out.println("GET response: " + rsp.getContentAsString());
rsp = sendRequest(new GetRequest(requestUrl), expectedStatus);
// get response as JSON
jsonParsedObject = new JSONObject(new JSONTokener(rsp.getContentAsString()));
System.out.println(rsp.getContentAsString());
assertNotNull(jsonParsedObject);
// check JSON data
dataObj = jsonParsedObject.getJSONObject("data");
assertNotNull(dataObj);
rootDataObject = (JSONObject)dataObj;
assertEquals(8, rootDataObject.length());
actions = rootDataObject.getJSONArray("actions");
assertNotNull(actions);
assertEquals(0, actions.length());
}
public void testPostDispositionAction() throws Exception
{
// create a new recordCategory node in the recordSeries and then get
// the disposition schedule
NodeRef newRecordCategory = filePlanService.createRecordCategory(recordSeries, GUID.generate());
dispositionService.createDispositionSchedule(newRecordCategory, null);
String categoryNodeUrl = newRecordCategory.toString().replace("://", "/");
String requestUrl = MessageFormat.format(POST_ACTIONDEF_URL_FORMAT, categoryNodeUrl);
// Construct the JSON request.
String name = "destroy";
String desc = "Destroy this record after 5 years";
String period = "year|5";
String periodProperty = "rma:cutOffDate";
boolean eligibleOnFirstCompleteEvent = true;
JSONObject jsonPostData = new JSONObject();
jsonPostData.put("name", name);
jsonPostData.put("description", desc);
jsonPostData.put("period", period);
jsonPostData.put("location", "my location");
jsonPostData.put("periodProperty", periodProperty);
jsonPostData.put("eligibleOnFirstCompleteEvent", eligibleOnFirstCompleteEvent);
JSONArray events = new JSONArray();
events.put("superseded");
events.put("no_longer_needed");
jsonPostData.put("events", events);
// Submit the JSON request.
String jsonPostString = jsonPostData.toString();
Response rsp = sendRequest(new PostRequest(requestUrl, jsonPostString, APPLICATION_JSON), 200);
// check the returned data is what was expected
JSONObject jsonResponse = new JSONObject(new JSONTokener(rsp.getContentAsString()));
JSONObject dataObj = jsonResponse.getJSONObject("data");
JSONObject rootDataObject = (JSONObject)dataObj;
assertNotNull(rootDataObject.getString("id"));
assertNotNull(rootDataObject.getString("url"));
assertEquals(0, rootDataObject.getInt("index"));
assertEquals(name, rootDataObject.getString("name"));
assertEquals("Destroy", rootDataObject.getString("label"));
assertEquals(desc, rootDataObject.getString("description"));
assertEquals(period, rootDataObject.getString("period"));
assertEquals("my location", rootDataObject.getString("location"));
assertEquals(periodProperty, rootDataObject.getString("periodProperty"));
assertTrue(rootDataObject.getBoolean("eligibleOnFirstCompleteEvent"));
events = rootDataObject.getJSONArray("events");
assertNotNull(events);
assertEquals(2, events.length());
assertEquals("superseded", events.get(0));
assertEquals("no_longer_needed", events.get(1));
// test the minimum amount of data required to create an action definition
jsonPostData = new JSONObject();
jsonPostData.put("name", name);
jsonPostString = jsonPostData.toString();
rsp = sendRequest(new PostRequest(requestUrl, jsonPostString, APPLICATION_JSON), 200);
// check the returned data is what was expected
jsonResponse = new JSONObject(new JSONTokener(rsp.getContentAsString()));
dataObj = jsonResponse.getJSONObject("data");
assertNotNull(rootDataObject.getString("id"));
assertNotNull(rootDataObject.getString("url"));
assertEquals(0, rootDataObject.getInt("index"));
assertEquals(name, dataObj.getString("name"));
assertEquals("none|0", dataObj.getString("period"));
assertFalse(dataObj.has("description"));
assertFalse(dataObj.has("periodProperty"));
assertFalse(dataObj.has("events"));
assertTrue(dataObj.getBoolean("eligibleOnFirstCompleteEvent"));
// negative test to ensure not supplying mandatory data results in an error
jsonPostData = new JSONObject();
jsonPostData.put("description", desc);
jsonPostData.put("period", period);
jsonPostString = jsonPostData.toString();
sendRequest(new PostRequest(requestUrl, jsonPostString, APPLICATION_JSON), 400);
}
public void testPutDispositionAction() throws Exception
{
NodeRef newRecordCategory = filePlanService.createRecordCategory(recordSeries, GUID.generate());
dispositionService.createDispositionSchedule(newRecordCategory, null);
// create an action definition to then update
String categoryNodeUrl = newRecordCategory.toString().replace("://", "/");
String postRequestUrl = MessageFormat.format(POST_ACTIONDEF_URL_FORMAT, categoryNodeUrl);
JSONObject jsonPostData = new JSONObject();
jsonPostData.put("name", "cutoff");
String jsonPostString = jsonPostData.toString();
sendRequest(new PostRequest(postRequestUrl, jsonPostString, APPLICATION_JSON), 200);
// verify the action definition is present and retrieve it's id
String getRequestUrl = MessageFormat.format(GET_SCHEDULE_URL_FORMAT, categoryNodeUrl);
Response rsp = sendRequest(new GetRequest(getRequestUrl), 200);
JSONObject json = new JSONObject(new JSONTokener(rsp.getContentAsString()));
JSONObject actionDef = json.getJSONObject("data").getJSONArray("actions").getJSONObject(0);
String actionDefId = actionDef.getString("id");
assertEquals("cutoff", actionDef.getString("name"));
assertEquals("none|0", actionDef.getString("period"));
assertFalse(actionDef.has("description"));
assertFalse(actionDef.has("events"));
// define body for PUT request
String name = "destroy";
String desc = "Destroy this record after 5 years";
String period = "year|5";
String location = "my location";
String periodProperty = "rma:cutOffDate";
boolean eligibleOnFirstCompleteEvent = false;
jsonPostData = new JSONObject();
jsonPostData.put("name", name);
jsonPostData.put("description", desc);
jsonPostData.put("period", period);
jsonPostData.put("location", location);
jsonPostData.put("periodProperty", periodProperty);
jsonPostData.put("eligibleOnFirstCompleteEvent", eligibleOnFirstCompleteEvent);
JSONArray events = new JSONArray();
events.put("superseded");
events.put("no_longer_needed");
jsonPostData.put("events", events);
jsonPostString = jsonPostData.toString();
// try and update a non existent action definition to check for 404
String putRequestUrl = MessageFormat.format(PUT_ACTIONDEF_URL_FORMAT, categoryNodeUrl, "xyz");
rsp = sendRequest(new PutRequest(putRequestUrl, jsonPostString, APPLICATION_JSON), 404);
// update the action definition
putRequestUrl = MessageFormat.format(PUT_ACTIONDEF_URL_FORMAT, categoryNodeUrl, actionDefId);
rsp = sendRequest(new PutRequest(putRequestUrl, jsonPostString, APPLICATION_JSON), 200);
// check the update happened correctly
json = new JSONObject(new JSONTokener(rsp.getContentAsString()));
actionDef = json.getJSONObject("data");
assertEquals(name, actionDef.getString("name"));
assertEquals("Destroy", actionDef.getString("label"));
assertEquals(desc, actionDef.getString("description"));
assertEquals(period, actionDef.getString("period"));
assertEquals(location, actionDef.getString("location"));
assertEquals(periodProperty, actionDef.getString("periodProperty"));
assertFalse(actionDef.getBoolean("eligibleOnFirstCompleteEvent"));
assertEquals(2, actionDef.getJSONArray("events").length());
assertEquals("superseded", actionDef.getJSONArray("events").getString(0));
assertEquals("no_longer_needed", actionDef.getJSONArray("events").getString(1));
}
public void testDeleteDispositionAction() throws Exception
{
NodeRef newRecordCategory = filePlanService.createRecordCategory(recordSeries, GUID.generate());
dispositionService.createDispositionSchedule(newRecordCategory, null);
// create an action definition to then delete
String categoryNodeUrl = newRecordCategory.toString().replace("://", "/");
String postRequestUrl = MessageFormat.format(POST_ACTIONDEF_URL_FORMAT, categoryNodeUrl);
JSONObject jsonPostData = new JSONObject();
jsonPostData.put("name", "cutoff");
String jsonPostString = jsonPostData.toString();
sendRequest(new PostRequest(postRequestUrl, jsonPostString, APPLICATION_JSON), 200);
// verify the action definition is present and retrieve it's id
String getRequestUrl = MessageFormat.format(GET_SCHEDULE_URL_FORMAT, categoryNodeUrl);
Response rsp = sendRequest(new GetRequest(getRequestUrl), 200);
JSONObject json = new JSONObject(new JSONTokener(rsp.getContentAsString()));
String actionDefId = json.getJSONObject("data").getJSONArray("actions").getJSONObject(0).getString("id");
// try and delete a non existent action definition to check for 404
String deleteRequestUrl = MessageFormat.format(DELETE_ACTIONDEF_URL_FORMAT, categoryNodeUrl, "xyz");
rsp = sendRequest(new DeleteRequest(deleteRequestUrl), 404);
// now delete the action defintion created above
deleteRequestUrl = MessageFormat.format(DELETE_ACTIONDEF_URL_FORMAT, categoryNodeUrl, actionDefId);
rsp = sendRequest(new DeleteRequest(deleteRequestUrl), 200);
// verify it got deleted
getRequestUrl = MessageFormat.format(GET_SCHEDULE_URL_FORMAT, categoryNodeUrl);
rsp = sendRequest(new GetRequest(getRequestUrl), 200);
json = new JSONObject(new JSONTokener(rsp.getContentAsString()));
JSONArray actions = json.getJSONObject("data").getJSONArray("actions");
assertEquals(0, actions.length());
}
public void testGetDispositionLifecycle() throws Exception
{
// Test 404 for disposition lifecycle request on incorrect node
String categoryUrl = recordCategory.toString().replace("://", "/");
String requestUrl = MessageFormat.format(GET_LIFECYCLE_URL_FORMAT, categoryUrl);
Response rsp = sendRequest(new GetRequest(requestUrl), 200);
JSONObject notFound = new JSONObject(new JSONTokener(rsp.getContentAsString()));
assertEquals(true, notFound.getJSONObject("data").getBoolean("notFound"));
NodeRef newRecordFolder = recordFolderService.createRecordFolder(recordCategory, "recordFolder");
// there should now be a disposition lifecycle for the record
requestUrl = MessageFormat.format(GET_LIFECYCLE_URL_FORMAT, newRecordFolder.toString().replace("://", "/"));
rsp = sendRequest(new GetRequest(requestUrl), 200);
System.out.println("GET : " + rsp.getContentAsString());
assertEquals("application/json;charset=UTF-8", rsp.getContentType());
// get response as JSON
JSONObject jsonParsedObject = new JSONObject(new JSONTokener(rsp.getContentAsString()));
assertNotNull(jsonParsedObject);
// check mandatory stuff is present
JSONObject dataObj = jsonParsedObject.getJSONObject("data");
assertEquals(SERVICE_URL_PREFIX + requestUrl, dataObj.getString("url"));
assertEquals("cutoff", dataObj.getString("name"));
assertFalse(dataObj.getBoolean("eventsEligible"));
assertTrue(dataObj.has("events"));
JSONArray events = dataObj.getJSONArray("events");
assertEquals(1, events.length());
JSONObject event1 = events.getJSONObject(0);
assertEquals("case_closed", event1.get("name"));
assertEquals("Case Closed", event1.get("label"));
assertFalse(event1.getBoolean("complete"));
assertFalse(event1.getBoolean("automatic"));
// check stuff expected to be missing is missing
assertFalse(dataObj.has("asOf"));
assertFalse(dataObj.has("startedAt"));
assertFalse(dataObj.has("startedBy"));
assertFalse(dataObj.has("completedAt"));
assertFalse(dataObj.has("completedBy"));
assertFalse(event1.has("completedAt"));
assertFalse(event1.has("completedBy"));
}
public void testGetListOfValues() throws Exception
{
// call the list service
Response rsp = sendRequest(new GetRequest(GET_LIST_URL), 200);
assertEquals("application/json;charset=UTF-8", rsp.getContentType());
// get response as JSON
JSONObject jsonParsedObject = new JSONObject(new JSONTokener(rsp.getContentAsString()));
assertNotNull(jsonParsedObject);
JSONObject data = jsonParsedObject.getJSONObject("data");
// check dispostion actions
JSONObject actions = data.getJSONObject("dispositionActions");
assertEquals(SERVICE_URL_PREFIX + GET_LIST_URL + "/dispositionactions", actions.getString("url"));
JSONArray items = actions.getJSONArray("items");
assertEquals(actionService.getDispositionActions().size(), items.length());
assertTrue(items.length() > 0);
JSONObject item = items.getJSONObject(0);
assertTrue(item.length() == 2);
assertTrue(item.has("label"));
assertTrue(item.has("value"));
// check events
JSONObject events = data.getJSONObject("events");
assertEquals(SERVICE_URL_PREFIX + GET_LIST_URL + "/events", events.getString("url"));
items = events.getJSONArray("items");
assertEquals(eventService.getEvents().size(), items.length());
assertTrue(items.length() > 0);
item = items.getJSONObject(0);
assertTrue(item.length() == 3);
assertTrue(item.has("label"));
assertTrue(item.has("value"));
assertTrue(item.has("automatic"));
// check period types
JSONObject periodTypes = data.getJSONObject("periodTypes");
assertEquals(SERVICE_URL_PREFIX + GET_LIST_URL + "/periodtypes", periodTypes.getString("url"));
items = periodTypes.getJSONArray("items");
assertEquals(Period.getProviderNames().size()-1, items.length());
assertTrue(items.length() > 0);
item = items.getJSONObject(0);
assertTrue(item.length() == 2);
assertTrue(item.has("label"));
assertTrue(item.has("value"));
// check period properties
JSONObject periodProperties = data.getJSONObject("periodProperties");
assertEquals(SERVICE_URL_PREFIX + GET_LIST_URL + "/periodproperties", periodProperties.getString("url"));
items = periodProperties.getJSONArray("items");
assertEquals(5, items.length());
assertTrue(items.length() > 0);
item = items.getJSONObject(0);
assertTrue(item.length() == 2);
assertTrue(item.has("label"));
assertTrue(item.has("value"));
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.webscript;
import java.io.IOException;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* REST API Test for Email mapping keys
*
* @author Tuna Aksoy
* @since 2.1
*/
public class EmailMapKeysRestApiTest extends BaseRMWebScriptTestCase
{
/** URLs for the REST API */
private static final String GET_EMAIL_MAP_KEYS_URL = "/api/rma/admin/emailmapkeys";
/**
* Tests the REST API to get the list of email mapping keys
*
* @throws IOException
* @throws JSONException
*/
public void testGetCapabilitiesAction() throws IOException, JSONException
{
// Send request
Response response = sendRequest(new GetRequest(GET_EMAIL_MAP_KEYS_URL), Status.STATUS_OK);
// Check the content from the response
String contentAsString = response.getContentAsString();
assertNotNull(contentAsString);
// Convert the response to json and check the data
JSONObject contentAsJson = new JSONObject(contentAsString);
JSONObject data = contentAsJson.getJSONObject("data");
assertNotNull(data);
// Get the email mapping keys and check them
JSONArray dataSets = data.getJSONArray("emailmapkeys");
assertNotNull(dataSets);
// Check the number of email mapping keys
assertTrue(dataSets.length() == 6);
}
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.webscript;
import java.io.IOException;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.DeleteRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
public class EmailMapScriptTest extends BaseRMWebScriptTestCase
{
/** URLs for the REST APIs */
public final static String URL_RM_EMAILMAP = "/api/rma/admin/emailmap";
public final static String URL_RM_EMAILMAP_DELETE = "/api/rma/admin/emailmap/%s/%s";
/** Constant for the content type */
private static final String APPLICATION_JSON = "application/json";
/**
* Tests the REST APIs for a custom mapping
*
* @throws IOException
* @throws JSONException
*/
public void testEmailMap() throws IOException, JSONException
{
/** Test GET */
Response getResponse = sendRequest(new GetRequest(URL_RM_EMAILMAP), Status.STATUS_OK);
JSONObject getResponseContent = new JSONObject(getResponse.getContentAsString());
JSONObject getData = getResponseContent.getJSONObject("data");
JSONArray getMappings = getData.getJSONArray("mappings");
assertTrue(getMappings.length() == 20);
/** Test POST */
JSONObject newMapping = new JSONObject();
newMapping.put("from", "messageTo");
newMapping.put("to", "rmc:Wibble");
Response postResponse = sendRequest(new PostRequest(URL_RM_EMAILMAP, newMapping.toString(), APPLICATION_JSON), Status.STATUS_OK);
JSONObject postResponseContent = new JSONObject(postResponse.getContentAsString());
JSONObject postData = postResponseContent.getJSONObject("data");
JSONArray postMappings = postData.getJSONArray("mappings");
assertTrue(postMappings.length() == 21);
assertTrue(existsMapping(postMappings));
/** Test DELETE */
Response deleteResponse = sendRequest(new DeleteRequest(String.format(URL_RM_EMAILMAP_DELETE, "messageTo", "rmc:Wibble")), Status.STATUS_OK);
JSONObject deleteResponseContent = new JSONObject(deleteResponse.getContentAsString());
JSONObject deleteData = deleteResponseContent.getJSONObject("data");
JSONArray deleteMappings = deleteData.getJSONArray("mappings");
assertTrue(deleteMappings.length() == 20);
assertFalse(existsMapping(deleteMappings));
}
/**
* Helper method for checking if a custom mapping exists
*
* @param mappings The list of available mappings
* @return true if the custom mapping exists in the list of available mappings, false otherwise
* @throws JSONException
*/
private boolean existsMapping(JSONArray mappings) throws JSONException
{
boolean result = false;
for (int i = 0; i < mappings.length(); i++)
{
String from = mappings.getJSONObject(i).getString("from");
String to = mappings.getJSONObject(i).getString("to");
if (from.equalsIgnoreCase("messageTo") && to.equalsIgnoreCase("rmc:Wibble"))
{
result = true;
break;
}
}
return result;
}
}

View File

@@ -0,0 +1,242 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.webscript;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase;
import org.alfresco.util.GUID;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.TestWebScriptServer.DeleteRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PutRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* RM event REST API test
*
* @author Roy Wetherall
*/
public class EventRestApiTest extends BaseRMWebScriptTestCase implements RecordsManagementModel
{
protected static final String GET_EVENTS_URL = "/api/rma/admin/rmevents";
protected static final String GET_EVENTTYPES_URL = "/api/rma/admin/rmeventtypes";
protected static final String SERVICE_URL_PREFIX = "/alfresco/service";
protected static final String APPLICATION_JSON = "application/json";
protected static final String DISPLAY_LABEL = "display label";
protected static final String EVENT_TYPE = "rmEventType.simple";
protected static final String KEY_EVENT_NAME = "eventName";
protected static final String KEY_EVENT_TYPE = "eventType";
protected static final String KEY_EVENT_DISPLAY_LABEL = "eventDisplayLabel";
public void testGetEventTypes() throws Exception
{
Response rsp = sendRequest(new GetRequest(GET_EVENTTYPES_URL),200);
String rspContent = rsp.getContentAsString();
JSONObject obj = new JSONObject(rspContent);
JSONObject types = obj.getJSONObject("data");
assertNotNull(types);
JSONObject type = types.getJSONObject("rmEventType.simple");
assertNotNull(type);
assertEquals("rmEventType.simple", type.getString("eventTypeName"));
assertNotNull(type.getString("eventTypeDisplayLabel"));
System.out.println(rspContent);
}
public void testGetEvents() throws Exception
{
String event1 = GUID.generate();
String event2 = GUID.generate();
// Create a couple or events by hand
eventService.addEvent(EVENT_TYPE, event1, DISPLAY_LABEL);
eventService.addEvent(EVENT_TYPE, event2, DISPLAY_LABEL);
try
{
// Get the events
Response rsp = sendRequest(new GetRequest(GET_EVENTS_URL),200);
String rspContent = rsp.getContentAsString();
JSONObject obj = new JSONObject(rspContent);
JSONObject roles = obj.getJSONObject("data");
assertNotNull(roles);
JSONObject eventObj = roles.getJSONObject(event1);
assertNotNull(eventObj);
assertEquals(event1, eventObj.get(KEY_EVENT_NAME));
assertEquals(DISPLAY_LABEL, eventObj.get(KEY_EVENT_DISPLAY_LABEL));
assertEquals(EVENT_TYPE, eventObj.get(KEY_EVENT_TYPE));
eventObj = roles.getJSONObject(event2);
assertNotNull(eventObj);
assertEquals(event2, eventObj.get(KEY_EVENT_NAME));
assertEquals(DISPLAY_LABEL, eventObj.get(KEY_EVENT_DISPLAY_LABEL));
assertEquals(EVENT_TYPE, eventObj.get(KEY_EVENT_TYPE));
}
finally
{
// Clean up
eventService.removeEvent(event1);
eventService.removeEvent(event2);
}
}
public void testPostEvents() throws Exception
{
String eventName= GUID.generate();
JSONObject obj = new JSONObject();
obj.put(KEY_EVENT_NAME, eventName);
obj.put(KEY_EVENT_DISPLAY_LABEL, DISPLAY_LABEL);
obj.put(KEY_EVENT_TYPE, EVENT_TYPE);
Response rsp = sendRequest(new PostRequest(GET_EVENTS_URL, obj.toString(), APPLICATION_JSON),200);
try
{
String rspContent = rsp.getContentAsString();
JSONObject resultObj = new JSONObject(rspContent);
JSONObject eventObj = resultObj.getJSONObject("data");
assertNotNull(eventObj);
assertEquals(eventName, eventObj.get(KEY_EVENT_NAME));
assertEquals(DISPLAY_LABEL, eventObj.get(KEY_EVENT_DISPLAY_LABEL));
assertEquals(EVENT_TYPE, eventObj.get(KEY_EVENT_TYPE));
}
finally
{
eventService.removeEvent(eventName);
}
// Test with no event name set
obj = new JSONObject();
obj.put(KEY_EVENT_DISPLAY_LABEL, DISPLAY_LABEL);
obj.put(KEY_EVENT_TYPE, EVENT_TYPE);
rsp = sendRequest(new PostRequest(GET_EVENTS_URL, obj.toString(), APPLICATION_JSON),200);
try
{
String rspContent = rsp.getContentAsString();
JSONObject resultObj = new JSONObject(rspContent);
JSONObject eventObj = resultObj.getJSONObject("data");
assertNotNull(eventObj);
assertNotNull(eventObj.get(KEY_EVENT_NAME));
assertEquals(DISPLAY_LABEL, eventObj.get(KEY_EVENT_DISPLAY_LABEL));
assertEquals(EVENT_TYPE, eventObj.get(KEY_EVENT_TYPE));
eventName = eventObj.getString(KEY_EVENT_NAME);
}
finally
{
eventService.removeEvent(eventName);
}
}
public void testPutRole() throws Exception
{
String eventName = GUID.generate();
eventService.addEvent(EVENT_TYPE, eventName, DISPLAY_LABEL);
try
{
JSONObject obj = new JSONObject();
obj.put(KEY_EVENT_NAME, eventName);
obj.put(KEY_EVENT_DISPLAY_LABEL, "changed");
obj.put(KEY_EVENT_TYPE, EVENT_TYPE);
// Get the roles
Response rsp = sendRequest(new PutRequest(GET_EVENTS_URL + "/" + eventName, obj.toString(), APPLICATION_JSON),200);
String rspContent = rsp.getContentAsString();
JSONObject result = new JSONObject(rspContent);
JSONObject eventObj = result.getJSONObject("data");
assertNotNull(eventObj);
assertEquals(eventName, eventObj.get(KEY_EVENT_NAME));
assertEquals("changed", eventObj.get(KEY_EVENT_DISPLAY_LABEL));
assertEquals(EVENT_TYPE, eventObj.get(KEY_EVENT_TYPE));
// Bad requests
obj = new JSONObject();
obj.put(KEY_EVENT_NAME, "cheese");
obj.put(KEY_EVENT_DISPLAY_LABEL, "whatever");
obj.put(KEY_EVENT_TYPE, EVENT_TYPE);
sendRequest(new PutRequest(GET_EVENTS_URL + "/cheese", obj.toString(), APPLICATION_JSON), 404);
}
finally
{
// Clean up
eventService.removeEvent(eventName);
}
}
public void testGetRole() throws Exception
{
String eventName = GUID.generate();
eventService.addEvent(EVENT_TYPE, eventName, DISPLAY_LABEL);
try
{
// Get the roles
Response rsp = sendRequest(new GetRequest(GET_EVENTS_URL + "/" + eventName),200);
String rspContent = rsp.getContentAsString();
JSONObject obj = new JSONObject(rspContent);
JSONObject eventObj = obj.getJSONObject("data");
assertNotNull(eventObj);
assertEquals(eventName, eventObj.get(KEY_EVENT_NAME));
assertEquals(DISPLAY_LABEL, eventObj.get(KEY_EVENT_DISPLAY_LABEL));
assertEquals(EVENT_TYPE, eventObj.get(KEY_EVENT_TYPE));
// Bad requests
sendRequest(new GetRequest(GET_EVENTS_URL + "/cheese"), 404);
}
finally
{
// Clean up
eventService.removeEvent(eventName);
}
}
public void testDeleteRole() throws Exception
{
String eventName = GUID.generate();
assertFalse(eventService.existsEvent(eventName));
eventService.addEvent(EVENT_TYPE, eventName, DISPLAY_LABEL);
assertTrue(eventService.existsEvent(eventName));
sendRequest(new DeleteRequest(GET_EVENTS_URL + "/" + eventName),200);
assertFalse(eventService.existsEvent(eventName));
// Bad request
sendRequest(new DeleteRequest(GET_EVENTS_URL + "/cheese"), 404);
}
}

View File

@@ -0,0 +1,925 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.webscript;
import java.util.ArrayList;
import java.util.List;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.caveat.RMCaveatConfigService;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.util.GUID;
import org.alfresco.util.PropertyMap;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.DeleteRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PutRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
*
*
* @author Mark Rogers
*/
@SuppressWarnings("unused")
public class RMCaveatConfigScriptTest extends BaseRMWebScriptTestCase
{
protected final static String RM_LIST = "rmc:smListTest";
protected final static String RM_LIST_URI_ELEM = "rmc_smListTest";
private static final String URL_RM_CONSTRAINTS = "/api/rma/admin/rmconstraints";
public void testGetRMConstraints() throws Exception
{
{
Response response = sendRequest(new GetRequest(URL_RM_CONSTRAINTS), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
System.out.println(response.getContentAsString());
assertNotNull(top.getJSONArray("data"));
}
/**
* Add a list, then get it back via the list rest script
*/
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
{
Response response = sendRequest(new GetRequest(URL_RM_CONSTRAINTS), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
System.out.println(response.getContentAsString());
JSONArray data = top.getJSONArray("data");
boolean found = false;
assertTrue("no data returned", data.length() > 0);
for(int i = 0; i < data.length(); i++)
{
JSONObject obj = data.getJSONObject(i);
String name = (String)obj.getString("constraintName");
assertNotNull("constraintName is null", name);
String url = (String)obj.getString("url");
assertNotNull("detail url is null", name);
if(name.equalsIgnoreCase(RM_LIST))
{
found = true;
}
/**
* vallidate the detail URL returned
*/
sendRequest(new GetRequest(url), Status.STATUS_OK);
}
}
}
/**
*
* @throws Exception
*/
public void testGetRMConstraint() throws Exception
{
/**
* Delete the list to remove any junk then recreate it.
*/
if (caveatConfigService.getRMConstraint(RM_LIST) != null)
{
caveatConfigService.deleteRMConstraint(RM_LIST);
}
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
createUser("fbloggs");
createUser("jrogers");
createUser("jdoe");
List<String> values = new ArrayList<String>();
values.add("NOFORN");
values.add("FGI");
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "fbloggs", values);
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "jrogers", values);
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "jdoe", values);
/**
* Positive test Get the constraint
*/
{
String url = URL_RM_CONSTRAINTS + "/" + RM_LIST_URI_ELEM;
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
String constraintName = data.getString("constraintName");
assertNotNull("constraintName is null", constraintName);
// JSONArray allowedValues = data.getJSONArray("allowedValues");
// assertTrue("values not correct", compare(array, allowedValues));
// JSONArray constraintDetails = data.getJSONArray("constraintDetails");
//
// assertTrue("details array does not contain 3 elements", constraintDetails.length() == 3);
// for(int i =0; i < constraintDetails.length(); i++)
// {
// JSONObject detail = constraintDetails.getJSONObject(i);
// }
}
/**
*
* @throws Exception
*/
/**
* Negative test - Attempt to get a constraint that does exist
*/
{
String url = URL_RM_CONSTRAINTS + "/" + "rmc_wibble";
sendRequest(new GetRequest(url), Status.STATUS_NOT_FOUND);
}
deleteUser("fbloggs");
deleteUser("jrogers");
deleteUser("jdoe");
}
/**
* Create an RM Constraint
* @throws Exception
*/
public void testUpdateRMConstraint() throws Exception
{
String constraintName = null;
/*
* Create a new list
*/
{
String title = "test Update RM Constraint title";
JSONArray array = new JSONArray();
array.put("LEMON");
array.put("BANANA");
array.put("PEACH");
JSONObject obj = new JSONObject();
obj.put("allowedValues", array);
obj.put("constraintTitle", title);
/**
* Now do a post to create a new list
*/
Response response = sendRequest(new PostRequest(URL_RM_CONSTRAINTS, obj.toString(), "application/json"), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
constraintName = data.getString("constraintName");
JSONArray allowedValues = data.getJSONArray("allowedValues");
assertTrue("values not correct", compare(array, allowedValues));
}
/**
* Now update both values and title - remove BANANA, PEACH, Add APPLE.
*/
{
String newTitle = "this is the new title";
JSONArray array = new JSONArray();
array.put("LEMON");
array.put("APPLE");
JSONObject obj = new JSONObject();
obj.put("allowedValues", array);
obj.put("constraintName", constraintName);
obj.put("constraintTitle", newTitle);
System.out.println(obj.toString());
/**
* Now do a post to update list
*/
Response response = sendRequest(new PutRequest(URL_RM_CONSTRAINTS + "/" + constraintName, obj.toString(), "application/json"), Status.STATUS_OK);
// Check the response
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
String url = data.getString("url");
String constraintName2 = data.getString("constraintName");
String constraintTitle = data.getString("constraintTitle");
JSONArray allowedValues = data.getJSONArray("allowedValues");
assertTrue(allowedValues.length() == 2);
assertTrue("values not correct", compare(array, allowedValues));
assertNotNull(url);
assertEquals(constraintName2, constraintName);
assertNotNull(constraintTitle);
assertEquals("title not as expected", constraintTitle, newTitle);
// Check that data has been persisted.
Response resp2 = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject top2 = new JSONObject(resp2.getContentAsString());
System.out.println("Problem here");
System.out.println(resp2.getContentAsString());
JSONObject data2 = top2.getJSONObject("data");
String constraintTitle2 = data2.getString("constraintTitle");
JSONArray allowedValues2 = data2.getJSONArray("allowedValues");
assertTrue("values not correct", compare(array, allowedValues2));
assertTrue("allowedValues is not 2", allowedValues2.length() == 2);
assertEquals(constraintName2, constraintName);
assertNotNull(constraintTitle2);
assertEquals("title not as expected", constraintTitle2, newTitle);
}
/**
* Now put without allowed values
*/
{
String newTitle = "update with no values";
JSONObject obj = new JSONObject();
obj.put("constraintName", RM_LIST);
obj.put("constraintTitle", newTitle);
/**
* Now do a put to update a new list
*/
Response response = sendRequest(new PutRequest(URL_RM_CONSTRAINTS + "/" + constraintName, obj.toString(), "application/json"), Status.STATUS_OK);
// Check the response
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
String url = data.getString("url");
String constraintName2 = data.getString("constraintName");
String constraintTitle = data.getString("constraintTitle");
JSONArray allowedValues = data.getJSONArray("allowedValues");
assertTrue(allowedValues.length() == 2);
assertNotNull(url);
assertEquals(constraintName2, constraintName);
assertNotNull(constraintTitle);
assertEquals("title not as expected", constraintTitle, newTitle);
}
/**
* Now post without constraint Title
*/
{
JSONArray array = new JSONArray();
array.put("LEMON");
array.put("APPLE");
JSONObject obj = new JSONObject();
obj.put("allowedValues", array);
System.out.println(obj.toString());
/**
* Now do a Put to update the list - title should remain
*/
Response response = sendRequest(new PutRequest(URL_RM_CONSTRAINTS + "/" + constraintName, obj.toString(), "application/json"), Status.STATUS_OK);
// Check the response
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
}
/**
* Add a new value (PEAR) to the list
*/
{
JSONArray array = new JSONArray();
array.put("PEAR");
array.put("LEMON");
array.put("APPLE");
JSONObject obj = new JSONObject();
obj.put("allowedValues", array);
System.out.println(obj.toString());
Response response = sendRequest(new PutRequest(URL_RM_CONSTRAINTS + "/" + constraintName, obj.toString(), "application/json"), Status.STATUS_OK);
// Check the response
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
}
/**
* Remove a value (PEAR) from the list
*/
{
JSONArray array = new JSONArray();
array.put("APPLE");
array.put("LEMON");
JSONObject obj = new JSONObject();
obj.put("allowedValues", array);
System.out.println(obj.toString());
Response response = sendRequest(new PutRequest(URL_RM_CONSTRAINTS + "/" + constraintName, obj.toString(), "application/json"), Status.STATUS_OK);
// Check the response
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
}
}
/**
* Create an RM Constraint
* @throws Exception
*/
public void testCreateRMConstraint() throws Exception
{
/**
* Delete the list to remove any junk then recreate it.
*/
//caveatConfigService.deleteRMConstraint(RM_LIST);
/**
* create a new list
*/
{
JSONArray array = new JSONArray();
array.put("NOFORN");
array.put("FGI");
JSONObject obj = new JSONObject();
obj.put("allowedValues", array);
obj.put("constraintName", RM_LIST);
obj.put("constraintTitle", GUID.generate());
System.out.println(obj.toString());
/**
* Now do a post to create a new list
*/
Response response = sendRequest(new PostRequest(URL_RM_CONSTRAINTS, obj.toString(), "application/json"), Status.STATUS_OK);
// Check the response
}
/**
* Now go and get the constraint
*/
{
String url = URL_RM_CONSTRAINTS + "/" + RM_LIST_URI_ELEM;
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
String constraintName = data.getString("constraintName");
assertNotNull("constraintName is null", constraintName);
// JSONArray constraintDetails = data.getJSONArray("constraintDetails");
//
// assertTrue("details array does not contain 3 elements", constraintDetails.length() == 3);
// for(int i =0; i < constraintDetails.length(); i++)
// {
// JSONObject detail = constraintDetails.getJSONObject(i);
// }
}
/**
* Now a constraint with a generated name
*/
{
String title = GUID.generate();
JSONArray array = new JSONArray();
array.put("Red");
array.put("Blue");
array.put("Green");
JSONObject obj = new JSONObject();
obj.put("allowedValues", array);
obj.put("constraintTitle", title);
System.out.println(obj.toString());
/**
* Now do a post to create a new list
*/
Response response = sendRequest(new PostRequest(URL_RM_CONSTRAINTS, obj.toString(), "application/json"), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
// Check the response
String url = data.getString("url");
String constraintName = data.getString("constraintName");
String constraintTitle = data.getString("constraintTitle");
JSONArray allowedValues = data.getJSONArray("allowedValues");
assertTrue(allowedValues.length() == 3);
assertNotNull(url);
assertNotNull(constraintName);
assertNotNull(constraintTitle);
assertEquals("title not as expected", constraintTitle, title);
sendRequest(new GetRequest(url), Status.STATUS_OK);
}
/**
* Now a constraint with an empty list of values.
*/
{
JSONArray array = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("allowedValues", array);
obj.put("constraintName", "rmc_whazoo");
obj.put("constraintTitle", GUID.generate());
System.out.println(obj.toString());
/**
* Now do a post to create a new list
*/
Response response = sendRequest(new PostRequest(URL_RM_CONSTRAINTS, obj.toString(), "application/json"), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
// Check the response
}
// /**
// * Negative tests - duplicate list
// */
// {
// JSONArray array = new JSONArray();
// array.put("NOFORN");
// array.put("FGI");
//
// JSONObject obj = new JSONObject();
// obj.put("allowedValues", array);
// obj.put("constraintName", RM_LIST);
// obj.put("constraintTitle", "this is the title");
//
// System.out.println(obj.toString());
//
// /**
// * Now do a post to create a new list
// */
// Response response = sendRequest(new PostRequest(URL_RM_CONSTRAINTS, obj.toString(), "application/json"), Status.STATUS_CREATED);
// JSONObject top = new JSONObject(response.getContentAsString());
//
// JSONObject data = top.getJSONObject("data");
// System.out.println(response.getContentAsString());
//
// // Check the response
// }
}
public void testGetRMConstraintValues() throws Exception
{
createUser("fbloggs");
createUser("jrogers");
createUser("jdoe");
/**
* Delete the list to remove any junk then recreate it.
*/
{
if (caveatConfigService.getRMConstraint(RM_LIST) != null)
{
caveatConfigService.deleteRMConstraint(RM_LIST);
}
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
List<String> values = new ArrayList<String>();
values.add("NOFORN");
values.add("FGI");
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "fbloggs", values);
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "jrogers", values);
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "jdoe", values);
}
/**
* Positive test Get the constraint
*/
{
String url = URL_RM_CONSTRAINTS + "/" + RM_LIST_URI_ELEM + "/values";
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
String constraintName = data.getString("constraintName");
assertNotNull("constraintName is null", constraintName);
String constraintTitle = data.getString("constraintTitle");
assertNotNull("constraintTitle is null", constraintTitle);
JSONArray values = data.getJSONArray("values");
assertTrue("details array does not contain 2 elements", values.length() == 2);
boolean fgiFound = false;
boolean nofornFound = false;
for(int i =0; i < values.length(); i++)
{
JSONObject value = values.getJSONObject(i);
if(value.getString("valueName").equalsIgnoreCase("FGI"))
{
fgiFound = true;
}
if(value.getString("valueName").equalsIgnoreCase("NOFORN"))
{
nofornFound = true;
}
}
assertTrue("fgi not found", fgiFound);
assertTrue("noforn not found", nofornFound);
}
deleteUser("fbloggs");
deleteUser("jrogers");
deleteUser("jdoe");
}
/**
* Update a value in a constraint
* @throws Exception
*/
public void testUpdateRMConstraintValue() throws Exception
{
if (caveatConfigService.getRMConstraint(RM_LIST) != null)
{
caveatConfigService.deleteRMConstraint(RM_LIST);
}
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
/**
* Add some data to an empty list
*/
{
JSONArray values = new JSONArray();
JSONArray authorities = new JSONArray();
authorities.put("fbloggs");
authorities.put("jdoe");
JSONObject valueA = new JSONObject();
valueA.put("value", "NOFORN");
valueA.put("authorities", authorities);
values.put(valueA);
JSONObject valueB = new JSONObject();
valueB.put("value", "FGI");
valueB.put("authorities", authorities);
values.put(valueB);
JSONObject obj = new JSONObject();
obj.put("values", values);
/**
* Do the first update - should get back
* NOFORN - fbloggs, jdoe
* FGI - fbloggs, jdoe
*/
Response response = sendRequest(new PostRequest(URL_RM_CONSTRAINTS + "/" + RM_LIST + "/values" , obj.toString(), "application/json"), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
assertNotNull("data is null", data);
JSONArray myValues = data.getJSONArray("values");
assertTrue("two values not found", myValues.length() == 2);
for(int i = 0; i < myValues.length(); i++)
{
JSONObject myObj = myValues.getJSONObject(i);
}
}
/**
* Add to a new value, NOCON, fbloggs, jrogers
*/
{
JSONArray values = new JSONArray();
JSONArray authorities = new JSONArray();
authorities.put("fbloggs");
authorities.put("jrogers");
JSONObject valueA = new JSONObject();
valueA.put("value", "NOCON");
valueA.put("authorities", authorities);
values.put(valueA);
JSONObject obj = new JSONObject();
obj.put("values", values);
/**
* Add a new value - should get back
* NOFORN - fbloggs, jdoe
* FGI - fbloggs, jdoe
* NOCON - fbloggs, jrogers
*/
System.out.println(obj.toString());
Response response = sendRequest(new PostRequest(URL_RM_CONSTRAINTS + "/" + RM_LIST + "/values" , obj.toString(), "application/json"), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
assertNotNull("data is null", data);
JSONArray myValues = data.getJSONArray("values");
assertTrue("three values not found", myValues.length() == 3);
for(int i = 0; i < myValues.length(); i++)
{
JSONObject myObj = myValues.getJSONObject(i);
}
}
/**
* Add to an existing value (NOFORN, jrogers)
* should get back
* NOFORN - fbloggs, jdoe, jrogers
* FGI - fbloggs, jdoe
* NOCON - fbloggs, jrogers
*/
{
JSONArray values = new JSONArray();
JSONArray authorities = new JSONArray();
authorities.put("fbloggs");
authorities.put("jrogers");
authorities.put("jdoe");
JSONObject valueA = new JSONObject();
valueA.put("value", "NOFORN");
valueA.put("authorities", authorities);
values.put(valueA);
JSONObject obj = new JSONObject();
obj.put("values", values);
Response response = sendRequest(new PostRequest(URL_RM_CONSTRAINTS + "/" + RM_LIST + "/values" , obj.toString(), "application/json"), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
assertNotNull("data is null", data);
JSONArray myValues = data.getJSONArray("values");
assertTrue("three values not found", myValues.length() == 3);
for(int i = 0; i < myValues.length(); i++)
{
JSONObject myObj = myValues.getJSONObject(i);
}
}
/**
* Remove from existing value (NOCON, fbloggs)
*/
{
JSONArray values = new JSONArray();
JSONArray authorities = new JSONArray();
authorities.put("jrogers");
JSONObject valueA = new JSONObject();
valueA.put("value", "NOCON");
valueA.put("authorities", authorities);
values.put(valueA);
JSONObject obj = new JSONObject();
obj.put("values", values);
/**
* should get back
* NOFORN - fbloggs, jdoe
* FGI - fbloggs, jdoe
* NOCON - jrogers
*/
Response response = sendRequest(new PostRequest(URL_RM_CONSTRAINTS + "/" + RM_LIST + "/values" , obj.toString(), "application/json"), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
assertNotNull("data is null", data);
JSONArray myValues = data.getJSONArray("values");
assertTrue("three values not found", myValues.length() == 3);
boolean foundNOCON = false;
boolean foundNOFORN = false;
boolean foundFGI = false;
for(int i = 0; i < myValues.length(); i++)
{
JSONObject myObj = myValues.getJSONObject(i);
if(myObj.getString("valueName").equalsIgnoreCase("NOCON"))
{
foundNOCON = true;
}
if(myObj.getString("valueName").equalsIgnoreCase("NOFORN"))
{
foundNOFORN = true;
}
if(myObj.getString("valueName").equalsIgnoreCase("FGI"))
{
foundFGI = true;
}
}
assertTrue("not found NOCON", foundNOCON);
assertTrue("not found NOFORN", foundNOFORN);
assertTrue("not found FGI", foundFGI);
}
}
/**
* Delete the entire constraint
*
* @throws Exception
*/
public void testDeleteRMConstraint() throws Exception
{
/**
* Delete the list to remove any junk then recreate it.
*/
if (caveatConfigService.getRMConstraint(RM_LIST) != null)
{
caveatConfigService.deleteRMConstraint(RM_LIST);
}
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
/**
* Now do a delete
*/
Response response = sendRequest(new DeleteRequest(URL_RM_CONSTRAINTS + "/" + RM_LIST), Status.STATUS_OK);
/**
* Now delete the list that should have been deleted
*/
// TODO NEED TO THINK ABOUT THIS BEHAVIOUR
//{
// sendRequest(new DeleteRequest(URL_RM_CONSTRAINTS + "/" + RM_LIST), Status.STATUS_NOT_FOUND);
//}
/**
* Negative test - delete list that does not exist
*/
{
sendRequest(new DeleteRequest(URL_RM_CONSTRAINTS + "/" + "rmc_wibble"), Status.STATUS_NOT_FOUND);
}
}
private boolean compare(JSONArray from, JSONArray to) throws Exception
{
List<String> ret = new ArrayList<String>();
if(from.length() != to.length())
{
fail("arrays are different lengths" + from.length() +", " + to.length());
return false;
}
for(int i = 0 ; i < to.length(); i++)
{
ret.add(to.getString(i));
}
for(int i = 0 ; i < from.length(); i++)
{
String val = from.getString(i);
if(ret.contains(val))
{
}
else
{
fail("Value not contained in list:" + val);
return false;
}
}
return true;
}
/**
* Create an RM Constraint value
* @throws Exception
*/
public void testGetRMConstraintValue() throws Exception
{
String constraintName = null;
/*
* Create a new list
*/
{
String title = "Get Constraint Value";
JSONArray array = new JSONArray();
array.put("POTATO");
array.put("CARROT");
array.put("TURNIP");
JSONObject obj = new JSONObject();
obj.put("allowedValues", array);
obj.put("constraintTitle", title);
/**
* Now do a post to create a new list
*/
Response response = sendRequest(new PostRequest(URL_RM_CONSTRAINTS, obj.toString(), "application/json"), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
constraintName = data.getString("constraintName");
JSONArray allowedValues = data.getJSONArray("allowedValues");
assertTrue("values not correct", compare(array, allowedValues));
}
/**
* Get the CARROT value
*/
{
String url = URL_RM_CONSTRAINTS + "/" + constraintName + "/values/" + "CARROT";
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
}
{
String url = URL_RM_CONSTRAINTS + "/" + constraintName + "/values/" + "ONION";
sendRequest(new GetRequest(url), Status.STATUS_NOT_FOUND);
}
}
}

View File

@@ -0,0 +1,100 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.webscript;
import java.util.ArrayList;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* Test of GET RM Constraint (User facing scripts)
*
* @author Mark Rogers
*/
public class RMConstraintScriptTest extends BaseRMWebScriptTestCase
{
protected final static String RM_LIST = "rmc:smListTest";
protected final static String RM_LIST_URI_ELEM = "rmc_smListTest";
private static final String URL_RM_CONSTRAINTS = "/api/rma/rmconstraints";
/**
*
* @throws Exception
*/
public void testGetRMConstraint() throws Exception
{
// Set the current security context as admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
/**
* Delete the list to remove any junk then recreate it.
*/
if (caveatConfigService.getRMConstraint(RM_LIST) != null)
{
caveatConfigService.deleteRMConstraint(RM_LIST);
}
caveatConfigService.addRMConstraint(RM_LIST, "my title", new String[0]);
createUser("fbloggs");
createUser("jrogers");
createUser("jdoe");
List<String> values = new ArrayList<String>();
values.add("NOFORN");
values.add("FGI");
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "fbloggs", values);
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "jrogers", values);
caveatConfigService.updateRMConstraintListAuthority(RM_LIST, "jdoe", values);
AuthenticationUtil.setFullyAuthenticatedUser("jdoe");
/**
* Positive test Get the constraint
*/
{
String url = URL_RM_CONSTRAINTS + "/" + RM_LIST_URI_ELEM;
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
System.out.println(response.getContentAsString());
data.getJSONArray("allowedValuesForCurrentUser");
}
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
deleteUser("fbloggs");
deleteUser("jrogers");
deleteUser("jdoe");
}
}

View File

@@ -0,0 +1,341 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.webscript;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.capability.Capability;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.role.FilePlanRoleService;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.security.AuthorityType;
import org.alfresco.util.GUID;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.DeleteRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* REST API Tests for adding/removing users/groups to/from a role
*
* @author Tuna Aksoy
* @since 2.1
*/
public class RmAuthoritiesRestApiTest extends BaseRMWebScriptTestCase
{
/** URL for the REST APIs */
private static final String RM_CHILDREN_URL = "/api/rm/%s/roles/%s/authorities/%s";
/** Constant for the content type */
private static final String APPLICATION_JSON = "application/json";
/** Constant for users and groups */
private static final String USER_WITH_CAPABILITY = GUID.generate();
private static final String USER_WITHOUT_CAPABILITY = GUID.generate();
private static final String ROLE_INCLUDING_CAPABILITY = GUID.generate();
private static final String ROLE_NOT_INCLUDING_CAPABILITY = GUID.generate();
private static final String USER_TO_ADD_TO_ROLE = GUID.generate();
private static final String GROUP_TO_ADD_TO_ROLE = GUID.generate();
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase#setupTestData()
*/
@Override
protected void setupTestData()
{
super.setupTestData();
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
// Create test user WITH required capability
createUser(USER_WITH_CAPABILITY);
// Create test role
Set<Capability> capabilities = new HashSet<Capability>(2);
capabilities.add(capabilityService.getCapability(RMPermissionModel.VIEW_RECORDS));
capabilities.add(capabilityService.getCapability(RMPermissionModel.CREATE_MODIFY_DESTROY_USERS_AND_GROUPS));
filePlanRoleService.createRole(filePlan, ROLE_INCLUDING_CAPABILITY, ROLE_INCLUDING_CAPABILITY, capabilities);
// Add user to the role
filePlanRoleService.assignRoleToAuthority(filePlan, ROLE_INCLUDING_CAPABILITY, USER_WITH_CAPABILITY);
// Create test user WITHOUT required capability
createUser(USER_WITHOUT_CAPABILITY);
// Create test role
filePlanRoleService.createRole(filePlan, ROLE_NOT_INCLUDING_CAPABILITY, ROLE_NOT_INCLUDING_CAPABILITY, new HashSet<Capability>(1));
// Add user to the role
filePlanRoleService.assignRoleToAuthority(filePlan, ROLE_NOT_INCLUDING_CAPABILITY, USER_WITHOUT_CAPABILITY);
// Create a test user to add to role
createUser(USER_TO_ADD_TO_ROLE);
// Create a group to add to role
createGroup(GROUP_TO_ADD_TO_ROLE);
return null;
}
});
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase#tearDownImpl()
*/
@Override
protected void tearDownImpl()
{
super.tearDownImpl();
// Delete test user WITH required capability
deleteUser(USER_WITH_CAPABILITY);
// Delete test role
filePlanRoleService.deleteRole(filePlan, ROLE_INCLUDING_CAPABILITY);
// Delete test user WITHOUT required capability
deleteUser(USER_WITHOUT_CAPABILITY);
// Add user to the role
filePlanRoleService.deleteRole(filePlan, ROLE_NOT_INCLUDING_CAPABILITY);
// Delete the user which was added to the role
deleteUser(getTestUserName());
// Delete the group which was added to the role
deleteGroup(getTestGroupName());
}
/**
* Test the REST API to add/remove a user to/from a role
*
* @throws IOException
* @throws JSONException
*/
public void testRmAddRemoveUser() throws IOException, JSONException
{
// Do the positive test with a user with the needed capabilities
AuthenticationUtil.setFullyAuthenticatedUser(USER_WITH_CAPABILITY);
// Get the user name
String userName = getTestUserName();
// Check if the user is already assigned to the role
assertFalse(getUsersAssignedToRole().contains(userName));
// Format url, send the request and check the content
String url = getFormattedUrlString(userName);
checkContent(postRequestSuccess(url));
// The user should be added to the role
assertTrue(getUsersAssignedToRole().contains(userName));
// Remove the user from the role and check the content
checkContent(deleteRequestSuccess(url));
// The user should be removed from the role
assertFalse(getUsersAssignedToRole().contains(userName));
// Do the negative test with a user without any capabilities
AuthenticationUtil.setFullyAuthenticatedUser(USER_WITHOUT_CAPABILITY);
// Send a request. The expectation is an internal server error
postRequestFailure(url);
}
/**
* Test the REST API to add/remove a group to/from a role
*
* @throws IOException
* @throws JSONException
*/
public void testRmAddRemoveGroup() throws IOException, JSONException
{
// Do the positive test with a user with the needed capabilities
AuthenticationUtil.setFullyAuthenticatedUser(USER_WITH_CAPABILITY);
// Get the group name
String groupName = getTestGroupName();
// Check if the group is already assigned to the role
assertFalse(getGroupsAssignedToRole().contains(groupName));
// Format url, send the request and check the content
String url = getFormattedUrlString(groupName);
checkContent(postRequestSuccess(url));
// The group should be added to the role
assertTrue(getGroupsAssignedToRole().contains(groupName));
// Remove the group from the role and check the content
checkContent(deleteRequestSuccess(url));
// The user should be removed from the role
assertFalse(getGroupsAssignedToRole().contains(groupName));
// Do the negative test with a user without any capabilities
AuthenticationUtil.setFullyAuthenticatedUser(USER_WITHOUT_CAPABILITY);
// Send a request. The expectation is an internal server error
deleteRequestFailure(url);
}
/**
* Util method to get the user name which will be added/removed to/from the role
*
* @return Returns the user name which will be added/removed to/from the role
*/
private String getTestUserName()
{
return authorityService.getName(AuthorityType.USER, USER_TO_ADD_TO_ROLE);
}
/**
* Util method to get the group name which will be added/removed to/from the role
*
* @return Returns the user group which will be added/removed to/from the role
*/
private String getTestGroupName()
{
return authorityService.getName(AuthorityType.GROUP, GROUP_TO_ADD_TO_ROLE);
}
/**
* Util method to get a set of groups assigned to a role
*
* @return Returns a set of groups assigned to a role
*/
private Set<String> getGroupsAssignedToRole()
{
return filePlanRoleService.getGroupsAssignedToRole(filePlan, FilePlanRoleService.ROLE_SECURITY_OFFICER);
}
/**
* Util method to get a set of users assigned to a role
*
* @return Returns a set of users assigned to a role
*/
private Set<String> getUsersAssignedToRole()
{
return filePlanRoleService.getUsersAssignedToRole(filePlan, FilePlanRoleService.ROLE_SECURITY_OFFICER);
}
/**
* Util method to get a formatted nodeRef string
*
* @return Returns a formatted nodeRef string
*/
private String getFormattedFilePlanString()
{
StoreRef storeRef = filePlan.getStoreRef();
String storeType = storeRef.getProtocol();
String storeId = storeRef.getIdentifier();
String id = filePlan.getId();
StringBuffer sb = new StringBuffer(32);
sb.append(storeType);
sb.append("/");
sb.append(storeId);
sb.append("/");
sb.append(id);
return sb.toString();
}
/**
* Util method to get a formatted url string
*
* @param authorityName The name of the authority which should be added/removed to/from a role
* @return Returns a formatted url string
*/
private String getFormattedUrlString(String authorityName)
{
return String.format(RM_CHILDREN_URL, getFormattedFilePlanString(), FilePlanRoleService.ROLE_SECURITY_OFFICER, authorityName);
}
/**
* Util method to send a post request. The expected status is success.
*
* @param url The url which should be used to make the post request
* @return Returns the response from the server
* @throws UnsupportedEncodingException
* @throws IOException
*/
private Response postRequestSuccess(String url) throws UnsupportedEncodingException, IOException
{
return sendRequest(new PostRequest(url, new JSONObject().toString(), APPLICATION_JSON), Status.STATUS_OK);
}
/**
* Util method to send a post request. The expected status is an internal server error.
*
* @param url The url which should be used to make the post request
* @return Returns the response from the server
* @throws UnsupportedEncodingException
* @throws IOException
*/
private Response postRequestFailure(String url) throws UnsupportedEncodingException, IOException
{
return sendRequest(new PostRequest(url, new JSONObject().toString(), APPLICATION_JSON), Status.STATUS_INTERNAL_SERVER_ERROR);
}
/**
* Util method to send a delete request. The expected status is success.
*
* @param url The url which should be used to make the delete request
* @return Returns the response from the server
* @throws IOException
*/
private Response deleteRequestSuccess(String url) throws IOException
{
return sendRequest(new DeleteRequest(url), Status.STATUS_OK);
}
/**
* Util method to send a delete request. The expected status is an internal server error.
*
* @param url The url which should be used to make the delete request
* @return Returns the response from the server
* @throws IOException
*/
private Response deleteRequestFailure(String url) throws IOException
{
return sendRequest(new DeleteRequest(url), Status.STATUS_INTERNAL_SERVER_ERROR);
}
/**
* Util method to check the server response
*
* @param response The server response
* @throws UnsupportedEncodingException
*/
private void checkContent(Response response) throws UnsupportedEncodingException
{
String contentAsString = response.getContentAsString();
assertNotNull(contentAsString);
assertTrue(contentAsString.equals("{}"));
}
}

View File

@@ -0,0 +1,146 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.webscript;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase;
import org.json.JSONArray;
import org.json.JSONException;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* REST API Tests for Class Definitions
*
* @author Tuna Aksoy
* @since 2.1
*/
public class RmClassesRestApiTest extends BaseRMWebScriptTestCase
{
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase#isCollaborationSiteTest()
*/
@Override
protected boolean isCollaborationSiteTest()
{
return true;
}
/** URL for the REST APIs */
private static final String RM_ASPECTS_URL = "/api/rm/classes?cf=%s&siteId=%s";
/**
* Test the REST API to retrieve the list of rm aspects
*
* @throws IOException
* @throws JSONException
*/
public void testRmGetAspectDefinitions() throws IOException, JSONException
{
// Format url and send request
String url = String.format(RM_ASPECTS_URL, "aspect", siteId);
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
// Check the content from the response
String contentAsString = response.getContentAsString();
assertNotNull(contentAsString);
// Convert the response to json array
JSONArray contentAsJson = new JSONArray(contentAsString);
assertNotNull(contentAsJson);
// Get a (sub)list of available dm/rm aspects
List<String> dmAspects = getDmAspects();
List<String> rmAspects = getRmAspects();
// Get the list of rm aspects from the response and check it
List<String> rmAspectList = new ArrayList<String>();
for (int i = 0; i < contentAsJson.length(); i++)
{
String name = contentAsJson.getJSONObject(i).getString("name");
assertNotNull(name);
rmAspectList.add(name);
assertFalse(dmAspects.contains(name));
}
assertTrue(rmAspectList.containsAll(rmAspects));
// Get the list of dm aspects and check them. It also contains rm related aspects.
// Format url and send request
url = String.format(RM_ASPECTS_URL, "aspect", COLLAB_SITE_ID);
response = sendRequest(new GetRequest(url), Status.STATUS_OK);
// Check the content from the response
contentAsString = response.getContentAsString();
assertNotNull(contentAsString);
// Convert the response to json array
contentAsJson = new JSONArray(contentAsString);
assertNotNull(contentAsJson);
// Get the list of dm aspects from the response and check it
List<String> dmAspectList = new ArrayList<String>();
for (int i = 0; i < contentAsJson.length(); i++)
{
String name = contentAsJson.getJSONObject(i).getString("name");
assertNotNull(name);
dmAspectList.add(name);
}
assertTrue(dmAspectList.containsAll(dmAspects));
// the list of dm aspescts contains also rm aspects
assertTrue(dmAspectList.containsAll(rmAspects));
}
/**
* Returns a (sub)list of rm aspects
*
* @return A (sub)list of rm aspects
*/
private List<String> getRmAspects()
{
return Arrays.asList(new String[]
{
"rma:ascended",
"rma:recordMetaData",
"rma:vitalRecordDefinition"
});
}
/**
* Returns a (sub)list of dm aspects
*
* @return A (sub)list of dm aspects
*/
private List<String> getDmAspects()
{
return Arrays.asList(new String[]
{
"emailserver:attached",
"bpm:assignees",
"cm:likesRatingSchemeRollups",
"wcmwf:submission",
"sys:localized"
});
}
}

View File

@@ -0,0 +1,146 @@
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.webscript;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase;
import org.json.JSONArray;
import org.json.JSONException;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* REST API Tests for Properties Definitions
*
* @author Tuna Aksoy
* @since 2.1
*/
public class RmPropertiesRestApiTest extends BaseRMWebScriptTestCase
{
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase#isCollaborationSiteTest()
*/
@Override
protected boolean isCollaborationSiteTest()
{
return true;
}
/** URL for the REST APIs */
private static final String RM_TYPES_URL = "/api/rm/classes?cf=%s&siteId=%s";
/**
* Test the REST API to retrieve the list of rm types
*
* @throws IOException
* @throws JSONException
*/
public void testRmGetTypeDefinitions() throws IOException, JSONException
{
// Format url and send request
String url = String.format(RM_TYPES_URL, "type", siteId);
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
// Check the content from the response
String contentAsString = response.getContentAsString();
assertNotNull(contentAsString);
// Convert the response to json array
JSONArray contentAsJson = new JSONArray(contentAsString);
assertNotNull(contentAsJson);
// Get a (sub)list of available dm/rm types
List<String> dmTypes = getDmTypes();
List<String> rmTypes = getRmTypes();
// Get the list of rm types from the response and check it
List<String> rmTypeList = new ArrayList<String>();
for (int i = 0; i < contentAsJson.length(); i++)
{
String name = contentAsJson.getJSONObject(i).getString("name");
assertNotNull(name);
rmTypeList.add(name);
assertFalse(dmTypes.contains(name));
}
assertTrue(rmTypeList.containsAll(rmTypes));
// Get the list of dm types and check them. It also contains rm related types.
// Format url and send request
url = String.format(RM_TYPES_URL, "type", COLLAB_SITE_ID);
response = sendRequest(new GetRequest(url), Status.STATUS_OK);
// Check the content from the response
contentAsString = response.getContentAsString();
assertNotNull(contentAsString);
// Convert the response to json array
contentAsJson = new JSONArray(contentAsString);
assertNotNull(contentAsJson);
// Get the list of dm types from the response and check it
List<String> dmTypeList = new ArrayList<String>();
for (int i = 0; i < contentAsJson.length(); i++)
{
String name = contentAsJson.getJSONObject(i).getString("name");
assertNotNull(name);
dmTypeList.add(name);
}
assertTrue(dmTypeList.containsAll(dmTypes));
// the list of dm type contains also rm types
assertTrue(dmTypeList.containsAll(rmTypes));
}
/**
* Returns a (sub)list of rm types
*
* @return A (sub)list of rm types
*/
private List<String> getRmTypes()
{
return Arrays.asList(new String[]
{
"rma:eventExecution",
"rma:nonElectronicDocument",
"rma:transfer"
});
}
/**
* Returns a (sub)list of dm types
*
* @return A (sub)list of dm types
*/
private List<String> getDmTypes()
{
return Arrays.asList(new String[]
{
"cm:authority",
"sys:descriptor",
"app:folderlink",
"wcmwf:parallelReviewTask",
"wca:deploymentserver"
});
}
}

View File

@@ -0,0 +1,367 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.webscript;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.capability.Capability;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMWebScriptTestCase;
import org.alfresco.service.cmr.security.AuthorityType;
import org.alfresco.util.GUID;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.TestWebScriptServer.DeleteRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PutRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* This class tests the Rest API for disposition related operations
*
* @author Roy Wetherall
*/
public class RoleRestApiTest extends BaseRMWebScriptTestCase
implements RecordsManagementModel
{
protected static final String GET_ROLES_URL_BY_SITE = "/api/rma/admin/{0}/rmroles";
protected static final String GET_ROLES_URL_BY_FILEPLAN = "/api/rma/admin/{0}/{1}/{2}/rmroles";
protected static final String SERVICE_URL_PREFIX = "/alfresco/service";
protected static final String APPLICATION_JSON = "application/json";
private String getRolesUrlBySite()
{
return MessageFormat.format(GET_ROLES_URL_BY_SITE, siteId);
}
private String getRoleUrlByFilePlan()
{
return MessageFormat.format(GET_ROLES_URL_BY_FILEPLAN, filePlan.getStoreRef().getProtocol(), filePlan.getStoreRef().getIdentifier(), filePlan.getId());
}
public void testGetRoles() throws Exception
{
String role1 = GUID.generate();
String role2 = GUID.generate();
String role3 = GUID.generate();
// Create a couple or roles by hand
filePlanRoleService.createRole(filePlan, role1, "My Test Role", getListOfCapabilities(5));
filePlanRoleService.createRole(filePlan, role2, "My Test Role Too", getListOfCapabilities(5));
//The user can either enter a plain text label or a key to look up in a property file.
filePlanRoleService.createRole(filePlan, role3, "bootstrap.rmadmin.lastName", getListOfCapabilities(5));
// create test group
String groupName = GUID.generate();
String group = authorityService.createAuthority(AuthorityType.GROUP, groupName, "monkey", null);
// Add the admin user to one of the roles
filePlanRoleService.assignRoleToAuthority(filePlan, role1, "admin");
filePlanRoleService.assignRoleToAuthority(filePlan, role1, group);
try
{
// Get the roles (for the default file plan)
Response rsp = sendRequest(new GetRequest(getRolesUrlBySite()),200);
String rspContent = rsp.getContentAsString();
JSONObject obj = new JSONObject(rspContent);
JSONObject roles = obj.getJSONObject("data");
assertNotNull(roles);
JSONObject roleObj = roles.getJSONObject(role1);
assertNotNull(roleObj);
assertEquals(role1, roleObj.get("name"));
assertEquals("My Test Role", roleObj.get("displayLabel"));
checkCapabilities(roleObj, 5);
roleObj = roles.getJSONObject(role2);
assertNotNull(roleObj);
assertEquals(role2, roleObj.get("name"));
assertEquals("My Test Role Too", roleObj.get("displayLabel"));
checkCapabilities(roleObj, 5);
//Custom role with a user entered message key
roleObj = roles.getJSONObject(role3);
assertNotNull(roleObj);
assertEquals(role3, roleObj.get("name"));
assertEquals("System Administrator", roleObj.get("displayLabel"));
// Get the roles, specifying the file plan
rsp = sendRequest(new GetRequest(getRoleUrlByFilePlan()),200);
rspContent = rsp.getContentAsString();
obj = new JSONObject(rspContent);
roles = obj.getJSONObject("data");
assertNotNull(roles);
roleObj = roles.getJSONObject(role1);
assertNotNull(roleObj);
assertEquals(role1, roleObj.get("name"));
assertEquals("My Test Role", roleObj.get("displayLabel"));
checkCapabilities(roleObj, 5);
roleObj = roles.getJSONObject(role2);
assertNotNull(roleObj);
assertEquals(role2, roleObj.get("name"));
assertEquals("My Test Role Too", roleObj.get("displayLabel"));
checkCapabilities(roleObj, 5);
// Get the roles for "admin"
rsp = sendRequest(new GetRequest(getRolesUrlBySite() + "?user=admin"),200);
rspContent = rsp.getContentAsString();
obj = new JSONObject(rspContent);
roles = obj.getJSONObject("data");
assertNotNull(roles);
roleObj = roles.getJSONObject(role1);
assertNotNull(roleObj);
assertEquals(role1, roleObj.get("name"));
assertEquals("My Test Role", roleObj.get("displayLabel"));
checkCapabilities(roleObj, 5);
assertFalse(roles.has(role2));
// Get the roles including assigned authorities
rsp = sendRequest(new GetRequest(getRoleUrlByFilePlan() + "?auths=true"),200);
rspContent = rsp.getContentAsString();
System.out.println(rspContent);
obj = new JSONObject(rspContent);
roles = obj.getJSONObject("data");
assertNotNull(roles);
roleObj = roles.getJSONObject(role1);
assertNotNull(roleObj);
assertEquals(role1, roleObj.get("name"));
assertEquals("My Test Role", roleObj.get("displayLabel"));
checkCapabilities(roleObj, 5);
JSONArray users = roleObj.getJSONArray("assignedUsers");
assertNotNull(users);
assertEquals(1, users.length());
JSONArray groups = roleObj.getJSONArray("assignedGroups");
assertNotNull(groups);
assertEquals(1, groups.length());
roleObj = roles.getJSONObject(role2);
assertNotNull(roleObj);
assertEquals(role2, roleObj.get("name"));
assertEquals("My Test Role Too", roleObj.get("displayLabel"));
checkCapabilities(roleObj, 5);
users = roleObj.getJSONArray("assignedUsers");
assertNotNull(users);
assertEquals(0, users.length());
groups = roleObj.getJSONArray("assignedGroups");
assertNotNull(groups);
assertEquals(0, groups.length());
}
finally
{
// Clean up
filePlanRoleService.deleteRole(filePlan, role1);
filePlanRoleService.deleteRole(filePlan, role2);
}
}
@SuppressWarnings("unchecked")
private void checkCapabilities(JSONObject role, int expectedCount) throws JSONException
{
JSONObject capabilities = role.getJSONObject("capabilities");
assertNotNull(capabilities);
int count = 0;
Iterator<String> it = capabilities.keys();
while (it.hasNext())
{
String key = it.next();
assertNotNull(key);
assertNotNull(capabilities.getString(key));
count ++;
}
assertEquals(expectedCount, count);
}
public void testPostRoles() throws Exception
{
Set<Capability> caps = getListOfCapabilities(5);
JSONArray arrCaps = new JSONArray();
for (Capability cap : caps)
{
arrCaps.put(cap.getName());
}
String roleName = GUID.generate();
JSONObject obj = new JSONObject();
obj.put("name", roleName);
obj.put("displayLabel", "Display Label");
obj.put("capabilities", arrCaps);
Response rsp = sendRequest(new PostRequest(getRolesUrlBySite(), obj.toString(), APPLICATION_JSON),200);
try
{
String rspContent = rsp.getContentAsString();
JSONObject resultObj = new JSONObject(rspContent);
JSONObject roleObj = resultObj.getJSONObject("data");
assertNotNull(roleObj);
assertNotNull(roleObj);
assertEquals(roleName, roleObj.get("name"));
assertEquals("Display Label", roleObj.get("displayLabel"));
checkCapabilities(roleObj, 5);
}
finally
{
filePlanRoleService.deleteRole(filePlan, roleName);
}
}
public void testPutRole() throws Exception
{
String role1 = GUID.generate();
filePlanRoleService.createRole(filePlan, role1, "My Test Role", getListOfCapabilities(5));
try
{
Set<Capability> caps = getListOfCapabilities(4,8);
JSONArray arrCaps = new JSONArray();
for (Capability cap : caps)
{
System.out.println(cap.getName());
arrCaps.put(cap.getName());
}
JSONObject obj = new JSONObject();
obj.put("name", role1);
obj.put("displayLabel", "Changed");
obj.put("capabilities", arrCaps);
// Get the roles
Response rsp = sendRequest(new PutRequest(getRolesUrlBySite() + "/" + role1, obj.toString(), APPLICATION_JSON),200);
String rspContent = rsp.getContentAsString();
JSONObject result = new JSONObject(rspContent);
JSONObject roleObj = result.getJSONObject("data");
assertNotNull(roleObj);
assertNotNull(roleObj);
assertEquals(role1, roleObj.get("name"));
assertEquals("Changed", roleObj.get("displayLabel"));
checkCapabilities(roleObj, 4);
// Bad requests
sendRequest(new PutRequest(getRolesUrlBySite() + "/cheese", obj.toString(), APPLICATION_JSON), 404);
}
finally
{
// Clean up
filePlanRoleService.deleteRole(filePlan, role1);
}
}
public void testGetRole() throws Exception
{
String role1 = GUID.generate();
filePlanRoleService.createRole(filePlan, role1, "My Test Role", getListOfCapabilities(5));
try
{
// Get the roles
Response rsp = sendRequest(new GetRequest(getRolesUrlBySite() + "/" + role1),200);
String rspContent = rsp.getContentAsString();
JSONObject obj = new JSONObject(rspContent);
JSONObject roleObj = obj.getJSONObject("data");
assertNotNull(roleObj);
assertNotNull(roleObj);
assertEquals(role1, roleObj.get("name"));
assertEquals("My Test Role", roleObj.get("displayLabel"));
checkCapabilities(roleObj, 5);
// Bad requests
sendRequest(new GetRequest(getRolesUrlBySite() + "/cheese"), 404);
}
finally
{
// Clean up
filePlanRoleService.deleteRole(filePlan, role1);
}
}
public void testDeleteRole() throws Exception
{
String role1 = GUID.generate();
assertFalse(filePlanRoleService.existsRole(filePlan, role1));
filePlanRoleService.createRole(filePlan, role1, "My Test Role", getListOfCapabilities(5));
assertTrue(filePlanRoleService.existsRole(filePlan, role1));
sendRequest(new DeleteRequest(getRolesUrlBySite() + "/" + role1),200);
assertFalse(filePlanRoleService.existsRole(filePlan, role1));
// Bad request
sendRequest(new DeleteRequest(getRolesUrlBySite() + "/cheese"), 404);
}
private Set<Capability> getListOfCapabilities(int size)
{
return getListOfCapabilities(size, 0);
}
private Set<Capability> getListOfCapabilities(int size, int offset)
{
Set<Capability> result = new HashSet<Capability>(size);
Set<Capability> caps = capabilityService.getCapabilities(false);
int count = 0;
for (Capability cap : caps)
{
if (count < size+offset)
{
if (count >= offset)
{
result.add(cap);
}
}
else
{
break;
}
count ++;
}
return result;
}
}