RM Build Scripts and Tests:

* moved RM tests into separate folder structure
 * updated Gradle scripts with test source locations and dependancies .. 'gradlew test' will now attempt to execute the unit tests (even if they fail!)
 * eclipse project dependancies updated so unit tests execute within the RM eclipse project
 * TODO get the unit tests working reliabily! (still lots of refactoring of old tests to do)



git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/modules/recordsmanagement/HEAD@35093 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Roy Wetherall
2012-04-05 03:01:22 +00:00
parent b0180e599a
commit f70eb812bc
51 changed files with 51 additions and 6 deletions

View File

@@ -0,0 +1,47 @@
/*
* 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 junit.framework.Test;
import junit.framework.TestSuite;
import org.alfresco.module.org_alfresco_module_rm.test.capabilities.CapabilitiesTest;
import org.alfresco.module.org_alfresco_module_rm.test.capabilities.DeclarativeCapabilityTest;
/**
* RM test suite
*
* @author Roy Wetherall
*/
public class CapabilitiesTestSuite extends TestSuite
{
/**
* Creates the test suite
*
* @return the test suite
*/
public static Test suite()
{
TestSuite suite = new TestSuite();
suite.addTestSuite(CapabilitiesTest.class);
suite.addTestSuite(DeclarativeCapabilityTest.class);
return suite;
}
}

View File

@@ -0,0 +1,45 @@
/*
* 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 junit.framework.Test;
import junit.framework.TestSuite;
import org.alfresco.module.org_alfresco_module_rm.test.jscript.RMJScriptTest;
/**
* RM JScript test suite
*
* @author Roy Wetherall
*/
public class JScriptTestSuite extends TestSuite
{
/**
* Creates the test suite
*
* @return the test suite
*/
public static Test suite()
{
TestSuite suite = new TestSuite();
suite.addTestSuite(RMJScriptTest.class);
return suite;
}
}

View File

@@ -0,0 +1,57 @@
/*
* 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.DispositionServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.RecordsManagementAdminServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.RecordsManagementSearchServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.RecordsManagementServiceImplTest;
import org.alfresco.module.org_alfresco_module_rm.test.service.VitalRecordServiceImplTest;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* RM test suite
*
* @author Roy Wetherall
*/
public class ServicesTestSuite extends TestSuite
{
/**
* Creates the test suite
*
* @return the test suite
*/
public static Test suite()
{
TestSuite suite = new TestSuite();
suite.addTestSuite(RecordsManagementServiceImplTest.class);
suite.addTestSuite(DispositionServiceImplTest.class);
//suite.addTestSuite(RecordsManagementActionServiceImplTest.class);
suite.addTestSuite(RecordsManagementAdminServiceImplTest.class);
//suite.addTestSuite(RecordsManagementAuditServiceImplTest.class);
//suite.addTestSuite(RecordsManagementEventServiceImplTest.class);
//suite.addTestSuite(RecordsManagementSecurityServiceImplTest.class);
suite.addTestSuite(RecordsManagementSearchServiceImplTest.class);
suite.addTestSuite(VitalRecordServiceImplTest.class);
return suite;
}
}

View File

@@ -0,0 +1,57 @@
/*
* 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 junit.framework.Test;
import junit.framework.TestSuite;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.BootstraptestDataRestApiTest;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.DispositionRestApiTest;
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.RmRestApiTest;
import org.alfresco.module.org_alfresco_module_rm.test.webscript.RoleRestApiTest;
/**
* RM WebScript test suite
*
* @author Roy Wetherall
*/
public class WebScriptTestSuite extends TestSuite
{
/**
* Creates the test suite
*
* @return the test suite
*/
public static Test suite()
{
TestSuite suite = new TestSuite();
suite.addTestSuite(BootstraptestDataRestApiTest.class);
suite.addTestSuite(DispositionRestApiTest.class);
suite.addTestSuite(EventRestApiTest.class);
suite.addTestSuite(RMCaveatConfigScriptTest.class);
suite.addTestSuite(RMConstraintScriptTest.class);
suite.addTestSuite(RmRestApiTest.class);
suite.addTestSuite(RoleRestApiTest.class);
return suite;
}
}

View File

@@ -0,0 +1,282 @@
/*
* 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.capabilities;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.action.impl.CompleteEventAction;
import org.alfresco.module.org_alfresco_module_rm.action.impl.FreezeAction;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.security.AccessStatus;
/**
* @author Roy Wetherall
*/
public class AddModifyEventDatesCapabilityTest extends BaseTestCapabilities
{
/**
*
* @throws Exception
*/
public void testAddModifyEventDatesCapability() throws Exception
{
// Check file plan permissions
checkPermissions(
filePlan,
ADD_MODIFY_EVENT_DATES,
stdUsers,
new AccessStatus[]
{
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.DENIED
});
checkCapabilities(
recordFolder_1,
ADD_MODIFY_EVENT_DATES,
stdUsers,
new AccessStatus[]
{
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.DENIED
});
checkCapabilities(
record_1,
ADD_MODIFY_EVENT_DATES,
stdUsers,
new AccessStatus[]
{
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED
});
checkCapabilities(
recordFolder_2,
ADD_MODIFY_EVENT_DATES,
stdUsers,
new AccessStatus[]
{
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED
});
checkCapabilities(
record_2,
ADD_MODIFY_EVENT_DATES,
stdUsers,
new AccessStatus[]
{
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.DENIED
});
/** Test user has no capabilities */
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.DENIED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.DENIED); // record_2
/** Add filing to both record folders */
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
permissionService.setPermission(filePlan, testers, VIEW_RECORDS, true);
permissionService.setInheritParentPermissions(recordCategory_1, false);
permissionService.setInheritParentPermissions(recordCategory_2, false);
permissionService.setPermission(recordCategory_1, testers, READ_RECORDS, true);
permissionService.setPermission(recordCategory_2, testers, READ_RECORDS, true);
permissionService.setPermission(recordFolder_1, testers, FILING, true);
permissionService.setPermission(recordFolder_2, testers, FILING, true);
return null;
}
}, false, true);
/** Check capabilities */
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.DENIED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.DENIED); // record_2
/** Add declare record capability */
addCapability(DECLARE_RECORDS, testers, filePlan);
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.DENIED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.DENIED); // record_2
/** Add modify event date capability */
addCapability(ADD_MODIFY_EVENT_DATES, testers, filePlan);
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
/** Remove declare capability */
removeCapability(DECLARE_RECORDS, testers, filePlan);
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
/** Add declare capability */
addCapability(DECLARE_RECORDS, testers, filePlan);
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
/** Remove view records capability */
removeCapability(VIEW_RECORDS, testers, filePlan);
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.DENIED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.DENIED); // record_2
/** Add view records capability */
addCapability(VIEW_RECORDS, testers, filePlan);
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
/** Remove filing from record folders */
removeCapability(FILING, testers, recordFolder_1, recordFolder_2);
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.DENIED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.DENIED); // record_2
/** Set filing permission on records folders */
addCapability(FILING, testers, recordFolder_1, recordFolder_2);
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
/** Freeze folder 1 */
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(FreezeAction.PARAM_REASON, "one");
executeAction("freeze", params, recordFolder_1);
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.DENIED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
/** Freeze record_2 */
params = new HashMap<String, Serializable>(1);
params.put(FreezeAction.PARAM_REASON, "Two");
executeAction("freeze", params, record_2);
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.DENIED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.DENIED); // record_2
/** Unfreeze */
executeAction("unfreeze", recordFolder_1, record_2);
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
/** Close record folders */
executeAction("closeRecordFolder", recordFolder_1, recordFolder_2);
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
/** Open record folders */
executeAction("openRecordFolder", recordFolder_1, recordFolder_2);
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
/** Try and complete events*/
Map<String, Serializable> eventDetails = new HashMap<String, Serializable>(3);
eventDetails.put(CompleteEventAction.PARAM_EVENT_NAME, "event");
eventDetails.put(CompleteEventAction.PARAM_EVENT_COMPLETED_AT, new Date());
eventDetails.put(CompleteEventAction.PARAM_EVENT_COMPLETED_BY, test_user);
executeAction("completeEvent", eventDetails, test_user, recordFolder_1);
checkExecuteActionFail("completeEvent", eventDetails, test_user, recordFolder_2);
checkExecuteActionFail("completeEvent", eventDetails, test_user, record_1);
executeAction("completeEvent", eventDetails, test_user, record_2);
/** Check properties can not be set */
checkSetPropertyFail(record_1, RecordsManagementModel.PROP_EVENT_EXECUTION_COMPLETE, test_user, true);
checkSetPropertyFail(record_1, RecordsManagementModel.PROP_EVENT_EXECUTION_COMPLETED_AT, test_user, new Date());
checkSetPropertyFail(record_1, RecordsManagementModel.PROP_EVENT_EXECUTION_COMPLETED_AT, test_user, "me");
/** Declare and cutoff */
declare(record_1, record_2);
cutoff(recordFolder_1, record_2);
checkTestUserCapabilities(ADD_MODIFY_EVENT_DATES,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
}
}

View File

@@ -0,0 +1,307 @@
/*
* 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.capabilities;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.action.impl.FreezeAction;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.security.AccessStatus;
/**
* @author Roy Wetherall
*/
public class ApproveRecordsScheduledForCutoffCapability extends BaseTestCapabilities
{
public void testApproveRecordsScheduledForCutoffCapability()
{
// File plan permissions
checkPermissions(filePlan, APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF, stdUsers,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED);
// Not yet eligible
checkCapabilities(recordFolder_1, APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF, stdUsers,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED);
checkCapabilities(record_1, APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF, stdUsers,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED);
checkCapabilities(recordFolder_2, APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF, stdUsers,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED);
checkCapabilities(record_2, APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF, stdUsers,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED);
// Set appropriate state - declare records and make eligible
declare(record_1, record_2);
makeEligible(recordFolder_1, record_2);
checkCapabilities(recordFolder_1, APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF, stdUsers,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED);
checkCapabilities(record_1, APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF, stdUsers,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED);
checkCapabilities(recordFolder_2, APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF, stdUsers,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED);
checkCapabilities(record_2, APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF, stdUsers,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.ALLOWED,
AccessStatus.DENIED,
AccessStatus.DENIED,
AccessStatus.DENIED);
checkTestUserCapabilities(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
AccessStatus.DENIED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.DENIED); // record_2
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
permissionService.setPermission(filePlan, testers, VIEW_RECORDS, true);
permissionService.setInheritParentPermissions(recordCategory_1, false);
permissionService.setInheritParentPermissions(recordCategory_2, false);
permissionService.setPermission(recordCategory_1, testers, READ_RECORDS, true);
permissionService.setPermission(recordCategory_2, testers, READ_RECORDS, true);
permissionService.setPermission(recordFolder_1, testers, FILING, true);
permissionService.setPermission(recordFolder_2, testers, FILING, true);
return null;
}
}, false, true);
checkTestUserCapabilities(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
AccessStatus.DENIED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.DENIED); // record_2
addCapability(DECLARE_RECORDS, testers, filePlan);
checkTestUserCapabilities(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
AccessStatus.DENIED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.DENIED); // record_2
addCapability(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF, testers, filePlan);
checkTestUserCapabilities(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
removeCapability(DECLARE_RECORDS, testers, filePlan);
checkTestUserCapabilities(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
addCapability(DECLARE_RECORDS, testers, filePlan);
checkTestUserCapabilities(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
removeCapability(VIEW_RECORDS, testers, filePlan);
checkTestUserCapabilities(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
AccessStatus.DENIED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.DENIED); // record_2
addCapability(VIEW_RECORDS, testers, filePlan);
checkTestUserCapabilities(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
removeCapability(FILING, testers, recordFolder_1, recordFolder_2);
checkTestUserCapabilities(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
AccessStatus.DENIED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.DENIED); // record_2
addCapability(FILING, testers, recordFolder_1, recordFolder_2);
checkTestUserCapabilities(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
// Freeze record folder
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(FreezeAction.PARAM_REASON, "one");
executeAction("freeze", params, recordFolder_1);
checkTestUserCapabilities(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
AccessStatus.DENIED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
// Freeze record
executeAction("freeze", params, record_2);
checkTestUserCapabilities(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
AccessStatus.DENIED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.DENIED); // record_2
// Unfreeze
executeAction("unfreeze", recordFolder_1, record_2);
checkTestUserCapabilities(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
// Close folders
executeAction("closeRecordFolder", recordFolder_1, recordFolder_2);
checkTestUserCapabilities(APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
AccessStatus.ALLOWED, // recordFolder_1
AccessStatus.DENIED, // record_1
AccessStatus.DENIED, // recordFolder_2
AccessStatus.ALLOWED); // record_2
//
// AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
// recordsManagementActionService.executeRecordsManagementAction(recordFolder_1, "openRecordFolder");
// recordsManagementActionService.executeRecordsManagementAction(recordFolder_2, "openRecordFolder");
//
// checkCapability(test_user, recordFolder_1, RMPermissionModel.APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF, AccessStatus.ALLOWED);
// checkCapability(test_user, record_1, RMPermissionModel.APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF, AccessStatus.DENIED);
// checkCapability(test_user, recordFolder_2, RMPermissionModel.APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF, AccessStatus.DENIED);
// checkCapability(test_user, record_2, RMPermissionModel.APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF, AccessStatus.ALLOWED);
//
// // try and cut off
//
// AuthenticationUtil.setFullyAuthenticatedUser(test_user);
// recordsManagementActionService.executeRecordsManagementAction(recordFolder_1, "cutoff", null);
// try
// {
// recordsManagementActionService.executeRecordsManagementAction(recordFolder_2, "cutoff", null);
// fail();
// }
// catch (AccessDeniedException ade)
// {
//
// }
// try
// {
// recordsManagementActionService.executeRecordsManagementAction(record_1, "cutoff", null);
// fail();
// }
// catch (AccessDeniedException ade)
// {
//
// }
// recordsManagementActionService.executeRecordsManagementAction(record_2, "cutoff", null);
//
// // check protected properties
//
// try
// {
// publicNodeService.setProperty(record_1, RecordsManagementModel.PROP_CUT_OFF_DATE, new Date());
// fail();
// }
// catch (AccessDeniedException ade)
// {
//
// }
// check cutoff again (it is already cut off)
// try
// {
// recordsManagementActionService.executeRecordsManagementAction(recordFolder_1, "cutoff", null);
// fail();
// }
// catch (AccessDeniedException ade)
// {
//
// }
// try
// {
// recordsManagementActionService.executeRecordsManagementAction(record_2, "cutoff", null);
// fail();
// }
// catch (AccessDeniedException ade)
// {
//
// }
// checkCapability(test_user, recordFolder_1, RMPermissionModel.APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
// AccessStatus.DENIED);
// checkCapability(test_user, record_1, RMPermissionModel.APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
// AccessStatus.DENIED);
// checkCapability(test_user, recordFolder_2, RMPermissionModel.APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
// AccessStatus.DENIED);
// checkCapability(test_user, record_2, RMPermissionModel.APPROVE_RECORDS_SCHEDULED_FOR_CUTOFF,
// AccessStatus.DENIED);
}
}

View File

@@ -0,0 +1,922 @@
/*
* 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.capabilities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
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.RecordsManagementService;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionService;
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.RMEntryVoter;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.event.RecordsManagementEventService;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.security.RecordsManagementSecurityService;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.security.permissions.AccessDeniedException;
import org.alfresco.repo.security.permissions.PermissionReference;
import org.alfresco.repo.security.permissions.impl.model.PermissionModel;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
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.StoreRef;
import org.alfresco.service.cmr.security.AccessStatus;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.AuthorityType;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.ApplicationContextHelper;
import org.springframework.context.ApplicationContext;
/**
* @author Roy Wetherall
*/
public abstract class BaseCapabilitiesTest extends TestCase
implements RMPermissionModel, RecordsManagementModel
{
/* Application context */
protected ApplicationContext ctx;
/* Root node reference */
protected StoreRef storeRef;
protected NodeRef rootNodeRef;
/* Services */
protected NodeService nodeService;
protected NodeService publicNodeService;
protected TransactionService transactionService;
protected PermissionService permissionService;
protected RecordsManagementService recordsManagementService;
protected RecordsManagementSecurityService recordsManagementSecurityService;
protected RecordsManagementActionService recordsManagementActionService;
protected RecordsManagementEventService recordsManagementEventService;
protected PermissionModel permissionModel;
protected ContentService contentService;
protected AuthorityService authorityService;
protected PersonService personService;
protected ContentService publicContentService;
protected RetryingTransactionHelper retryingTransactionHelper;
protected CapabilityService capabilityService;
protected RMEntryVoter rmEntryVoter;
protected UserTransaction testTX;
protected NodeRef filePlan;
protected NodeRef recordSeries;
protected NodeRef recordCategory_1;
protected NodeRef recordCategory_2;
protected NodeRef recordFolder_1;
protected NodeRef recordFolder_2;
protected NodeRef record_1;
protected NodeRef record_2;
protected NodeRef recordCategory_3;
protected NodeRef recordFolder_3;
protected NodeRef record_3;
protected String rmUsers;
protected String rmPowerUsers;
protected String rmSecurityOfficers;
protected String rmRecordsManagers;
protected String rmAdministrators;
protected String rm_user;
protected String rm_power_user;
protected String rm_security_officer;
protected String rm_records_manager;
protected String rm_administrator;
protected String test_user;
protected String testers;
protected String[] stdUsers;
protected NodeRef[] stdNodeRefs;;
/**
* Test setup
* @throws Exception
*/
protected void setUp() throws Exception
{
// Get the application context
ctx = ApplicationContextHelper.getApplicationContext();
// Get beans
nodeService = (NodeService) ctx.getBean("dbNodeService");
publicNodeService = (NodeService) ctx.getBean("NodeService");
transactionService = (TransactionService) ctx.getBean("transactionComponent");
permissionService = (PermissionService) ctx.getBean("permissionService");
permissionModel = (PermissionModel) ctx.getBean("permissionsModelDAO");
contentService = (ContentService) ctx.getBean("contentService");
publicContentService = (ContentService) ctx.getBean("ContentService");
authorityService = (AuthorityService) ctx.getBean("authorityService");
personService = (PersonService) ctx.getBean("personService");
recordsManagementService = (RecordsManagementService) ctx.getBean("RecordsManagementService");
recordsManagementSecurityService = (RecordsManagementSecurityService) ctx.getBean("RecordsManagementSecurityService");
recordsManagementActionService = (RecordsManagementActionService) ctx.getBean("RecordsManagementActionService");
recordsManagementEventService = (RecordsManagementEventService) ctx.getBean("RecordsManagementEventService");
rmEntryVoter = (RMEntryVoter) ctx.getBean("rmEntryVoter");
retryingTransactionHelper = (RetryingTransactionHelper)ctx.getBean("retryingTransactionHelper");
capabilityService = (CapabilityService)ctx.getBean("capabilityService");
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
// As system user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
// Create store and get the root node reference
storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
rootNodeRef = nodeService.getRootNode(storeRef);
// As admin user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
// Create test events
recordsManagementEventService.getEvents();
recordsManagementEventService.addEvent("rmEventType.simple", "event", "My Event");
// Create file plan node
filePlan = nodeService.createNode(
rootNodeRef,
ContentModel.ASSOC_CHILDREN,
TYPE_FILE_PLAN,
TYPE_FILE_PLAN).getChildRef();
return null;
}
}, false, true);
// Load in the plan data required for the test
loadFilePlanData();
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
// As system user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
// create people ...
rm_user = "rm_user_" + storeRef.getIdentifier();
rm_power_user = "rm_power_user_" + storeRef.getIdentifier();
rm_security_officer = "rm_security_officer_" + storeRef.getIdentifier();
rm_records_manager = "rm_records_manager_" + storeRef.getIdentifier();
rm_administrator = "rm_administrator_" + storeRef.getIdentifier();
test_user = "test_user_" + storeRef.getIdentifier();
personService.createPerson(createDefaultProperties(rm_user));
personService.createPerson(createDefaultProperties(rm_power_user));
personService.createPerson(createDefaultProperties(rm_security_officer));
personService.createPerson(createDefaultProperties(rm_records_manager));
personService.createPerson(createDefaultProperties(rm_administrator));
personService.createPerson(createDefaultProperties(test_user));
// create roles as groups
rmUsers = authorityService.createAuthority(AuthorityType.GROUP, "RM_USER_" + storeRef.getIdentifier());
rmPowerUsers = authorityService.createAuthority(AuthorityType.GROUP, "RM_POWER_USER_" + storeRef.getIdentifier());
rmSecurityOfficers = authorityService.createAuthority(AuthorityType.GROUP, "RM_SECURITY_OFFICER_" + storeRef.getIdentifier());
rmRecordsManagers = authorityService.createAuthority(AuthorityType.GROUP, "RM_RECORDS_MANAGER_" + storeRef.getIdentifier());
rmAdministrators = authorityService.createAuthority(AuthorityType.GROUP, "RM_ADMINISTRATOR_" + storeRef.getIdentifier());
testers = authorityService.createAuthority(AuthorityType.GROUP, "RM_TESTOR_" + storeRef.getIdentifier());
authorityService.addAuthority(testers, test_user);
setPermissions(rmUsers, rm_user, ROLE_USER);
setPermissions(rmPowerUsers, rm_power_user, ROLE_POWER_USER);
setPermissions(rmSecurityOfficers, rm_security_officer, ROLE_SECURITY_OFFICER);
setPermissions(rmRecordsManagers, rm_records_manager, ROLE_RECORDS_MANAGER);
setPermissions(rmAdministrators, rm_administrator, ROLE_ADMINISTRATOR);
stdUsers = new String[]
{
AuthenticationUtil.getSystemUserName(),
rm_administrator,
rm_records_manager,
rm_security_officer,
rm_power_user,
rm_user
};
stdNodeRefs = new NodeRef[]
{
recordFolder_1,
record_1,
recordFolder_2,
record_2
};
return null;
}
}, false, true);
}
/**
* Test tear down
* @throws Exception
*/
@Override
protected void tearDown() throws Exception
{
// TODO we should clean up as much as we can ....
}
/**
* Set the permissions for a group, user and role
* @param group
* @param user
* @param role
*/
private void setPermissions(String group, String user, String role)
{
for (PermissionReference pr : permissionModel.getImmediateGranteePermissions(permissionModel.getPermissionReference(null, role)))
{
setPermission(filePlan, group, pr.getName(), true);
}
authorityService.addAuthority(group, user);
setPermission(filePlan, user, FILING, true);
}
/**
* Loads the file plan date required for the tests
*/
protected void loadFilePlanData()
{
recordSeries = createRecordSeries(filePlan, "RS", "RS-1", "Record Series", "My record series");
recordCategory_1 = createRecordCategory(recordSeries, "Docs", "101-1", "Docs", "Docs", "week|1", true, false);
recordCategory_2 = createRecordCategory(recordSeries, "More Docs", "101-2", "More Docs", "More Docs", "week|1", true, true);
recordCategory_3 = createRecordCategory(recordSeries, "No disp schedule", "101-3", "No disp schedule", "No disp schedule", "week|1", true, null);
recordFolder_1 = createRecordFolder(recordCategory_1, "F1", "101-3", "title", "description", "week|1", true);
recordFolder_2 = createRecordFolder(recordCategory_2, "F2", "102-3", "title", "description", "week|1", true);
recordFolder_3 = createRecordFolder(recordCategory_3, "F3", "103-3", "title", "description", "week|1", true);
record_1 = createRecord(recordFolder_1);
record_2 = createRecord(recordFolder_2);
record_3 = createRecord(recordFolder_3);
}
/**
* Set permission for authority on node reference.
* @param nodeRef
* @param authority
* @param permission
* @param allow
*/
private void setPermission(NodeRef nodeRef, String authority, String permission, boolean allow)
{
permissionService.setPermission(nodeRef, authority, permission, allow);
if (permission.equals(FILING))
{
if (recordsManagementService.isRecordCategory(nodeRef) == true)
{
List<ChildAssociationRef> assocs = nodeService.getChildAssocs(nodeRef, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
for (ChildAssociationRef assoc : assocs)
{
NodeRef child = assoc.getChildRef();
if (recordsManagementService.isRecordFolder(child) == true ||
recordsManagementService.isRecordCategory(child) == true)
{
setPermission(child, authority, permission, allow);
}
}
}
}
}
/**
* Create the default person properties
* @param userName
* @return
*/
private Map<QName, Serializable> createDefaultProperties(String userName)
{
HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(ContentModel.PROP_USERNAME, userName);
properties.put(ContentModel.PROP_HOMEFOLDER, null);
properties.put(ContentModel.PROP_FIRSTNAME, userName);
properties.put(ContentModel.PROP_LASTNAME, userName);
properties.put(ContentModel.PROP_EMAIL, userName);
properties.put(ContentModel.PROP_ORGID, "");
return properties;
}
/**
* Create a new record. Executed in a new transaction.
*/
private NodeRef createRecord(final NodeRef recordFolder)
{
return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
{
@Override
public NodeRef execute() throws Throwable
{
// As admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
// Create the record
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
props.put(ContentModel.PROP_NAME, "MyRecord.txt");
NodeRef recordOne = nodeService.createNode(recordFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "MyRecord.txt"),
ContentModel.TYPE_CONTENT, props).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("There is some content in this record");
return recordOne;
}
}, false, true);
}
/**
* Create a test record series. Executed in a new transaction.
*/
private NodeRef createRecordSeries(final NodeRef filePlan, final String name, final String identifier, final String title, final String description)
{
return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
{
@Override
public NodeRef execute() throws Throwable
{
// As admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(ContentModel.PROP_NAME, name);
properties.put(PROP_IDENTIFIER, identifier);
properties.put(ContentModel.PROP_TITLE, title);
properties.put(ContentModel.PROP_DESCRIPTION, description);
NodeRef recordSeried = nodeService.createNode(filePlan, ContentModel.ASSOC_CONTAINS, TYPE_RECORD_CATEGORY, TYPE_RECORD_CATEGORY, properties).getChildRef();
permissionService.setInheritParentPermissions(recordSeried, false);
return recordSeried;
}
}, false, true);
}
/**
* Create a test record category in a new transaction.
*/
private NodeRef createRecordCategory(
final NodeRef recordSeries,
final String name,
final String identifier,
final String title,
final String description,
final String review,
final boolean vital,
final Boolean recordLevelDisposition)
{
return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
{
@Override
public NodeRef execute() throws Throwable
{
// As admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(ContentModel.PROP_NAME, name);
properties.put(PROP_IDENTIFIER, identifier);
properties.put(ContentModel.PROP_TITLE, title);
properties.put(ContentModel.PROP_DESCRIPTION, description);
properties.put(PROP_REVIEW_PERIOD, review);
properties.put(PROP_VITAL_RECORD_INDICATOR, vital);
NodeRef answer = nodeService.createNode(recordSeries, ContentModel.ASSOC_CONTAINS, TYPE_RECORD_CATEGORY, TYPE_RECORD_CATEGORY, properties)
.getChildRef();
if (recordLevelDisposition != null)
{
properties = new HashMap<QName, Serializable>();
properties.put(PROP_DISPOSITION_AUTHORITY, "N1-218-00-4 item 023");
properties.put(PROP_DISPOSITION_INSTRUCTIONS, "Cut off monthly, hold 1 month, then destroy.");
properties.put(PROP_RECORD_LEVEL_DISPOSITION, recordLevelDisposition);
NodeRef ds = nodeService.createNode(answer, ASSOC_DISPOSITION_SCHEDULE, TYPE_DISPOSITION_SCHEDULE, TYPE_DISPOSITION_SCHEDULE,
properties).getChildRef();
createDispoistionAction(ds, "cutoff", "monthend|1", null, "event");
createDispoistionAction(ds, "transfer", "month|1", null, null);
createDispoistionAction(ds, "accession", "month|1", null, null);
createDispoistionAction(ds, "destroy", "month|1", "{http://www.alfresco.org/model/recordsmanagement/1.0}cutOffDate", null);
}
permissionService.setInheritParentPermissions(answer, false);
return answer;
}
}, false, true);
}
/**
* Create disposition action.
* @param disposition
* @param actionName
* @param period
* @param periodProperty
* @param event
* @return
*/
private NodeRef createDispoistionAction(NodeRef disposition, String actionName, String period, String periodProperty, String event)
{
HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(PROP_DISPOSITION_ACTION_NAME, actionName);
properties.put(PROP_DISPOSITION_PERIOD, period);
if (periodProperty != null)
{
properties.put(PROP_DISPOSITION_PERIOD_PROPERTY, periodProperty);
}
if (event != null)
{
properties.put(PROP_DISPOSITION_EVENT, event);
}
NodeRef answer = nodeService.createNode(disposition, ASSOC_DISPOSITION_ACTION_DEFINITIONS, TYPE_DISPOSITION_ACTION_DEFINITION,
TYPE_DISPOSITION_ACTION_DEFINITION, properties).getChildRef();
return answer;
}
/**
* Create record folder. Executed in a new transaction.
* @param recordCategory
* @param name
* @param identifier
* @param title
* @param description
* @param review
* @param vital
* @return
*/
private NodeRef createRecordFolder(
final NodeRef recordCategory,
final String name,
final String identifier,
final String title,
final String description,
final String review,
final boolean vital)
{
return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
{
@Override
public NodeRef execute() throws Throwable
{
// As admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(ContentModel.PROP_NAME, name);
properties.put(PROP_IDENTIFIER, identifier);
properties.put(ContentModel.PROP_TITLE, title);
properties.put(ContentModel.PROP_DESCRIPTION, description);
properties.put(PROP_REVIEW_PERIOD, review);
properties.put(PROP_VITAL_RECORD_INDICATOR, vital);
NodeRef answer = nodeService.createNode(recordCategory, ContentModel.ASSOC_CONTAINS, TYPE_RECORD_FOLDER, TYPE_RECORD_FOLDER, properties)
.getChildRef();
permissionService.setInheritParentPermissions(answer, false);
return answer;
}
}, false, true);
}
/**
*
* @param user
* @param nodeRef
* @param capabilityName
* @param accessStstus
*/
protected void checkCapability(final String user, final NodeRef nodeRef, final String capabilityName, final AccessStatus expected)
{
AuthenticationUtil.runAs(new RunAsWork<Object>()
{
@Override
public Object doWork() throws Exception
{
Capability capability = recordsManagementSecurityService.getCapability(capabilityName);
assertNotNull(capability);
List<String> capabilities = new ArrayList<String>(1);
capabilities.add(capabilityName);
Map<Capability, AccessStatus> access = capabilityService.getCapabilitiesAccessState(nodeRef, capabilities);
AccessStatus actual = access.get(capability);
assertEquals(
"for user: " + user,
expected,
actual);
return null;
}
}, user);
}
/**
*
* @param access
* @param name
* @param accessStatus
*/
protected void check(Map<Capability, AccessStatus> access, String name, AccessStatus accessStatus)
{
Capability capability = recordsManagementSecurityService.getCapability(name);
assertNotNull(capability);
assertEquals(accessStatus, access.get(capability));
}
/**
*
* @param user
* @param nodeRef
* @param permission
* @param accessStstus
*/
protected void checkPermission(final String user, final NodeRef nodeRef, final String permission, final AccessStatus accessStstus)
{
AuthenticationUtil.runAs(new RunAsWork<Object>()
{
@Override
public Object doWork() throws Exception
{
AccessStatus actualAccessStatus = permissionService.hasPermission(nodeRef, permission);
assertTrue(actualAccessStatus == accessStstus);
return null;
}
}, user);
}
/**
*
* @param nodeRef
* @param permission
* @param users
* @param expectedAccessStatus
*/
protected void checkPermissions(
final NodeRef nodeRef,
final String permission,
final String[] users,
final AccessStatus ... expectedAccessStatus)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
assertEquals(
"The number of users should match the number of expected access status",
users.length,
expectedAccessStatus.length);
for (int i = 0; i < users.length; i++)
{
checkPermission(users[i], nodeRef, permission, expectedAccessStatus[i]);
}
return null;
}
}, true, true);
}
/**
*
* @param nodeRef
* @param capability
* @param users
* @param expectedAccessStatus
*/
protected void checkCapabilities(
final NodeRef nodeRef,
final String capability,
final String[] users,
final AccessStatus ... expectedAccessStatus)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
assertEquals(
"The number of users should match the number of expected access status",
users.length,
expectedAccessStatus.length);
for (int i = 0; i < users.length; i++)
{
checkCapability(users[i], nodeRef, capability, expectedAccessStatus[i]);
}
return null;
}
}, true, true);
}
/**
*
* @param user
* @param capability
* @param nodeRefs
* @param expectedAccessStatus
*/
protected void checkCapabilities(
final String user,
final String capability,
final NodeRef[] nodeRefs,
final AccessStatus ... expectedAccessStatus)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
assertEquals(
"The number of node references should match the number of expected access status",
nodeRefs.length,
expectedAccessStatus.length);
for (int i = 0; i < nodeRefs.length; i++)
{
checkCapability(user, nodeRefs[i], capability, expectedAccessStatus[i]);
}
return null;
}
}, true, true);
}
/**
*
* @param capability
* @param accessStatus
*/
protected void checkTestUserCapabilities(String capability, AccessStatus ... accessStatus)
{
checkCapabilities(
test_user,
capability,
stdNodeRefs,
accessStatus);
}
/**
* Execute RM action
* @param action
* @param params
* @param nodeRefs
*/
protected void executeAction(final String action, final Map<String, Serializable> params, final String user, final NodeRef ... nodeRefs)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(user);
for (NodeRef nodeRef : nodeRefs)
{
recordsManagementActionService.executeRecordsManagementAction(nodeRef, action, params);
}
return null;
}
}, false, true);
}
/**
*
* @param action
* @param nodeRefs
*/
protected void executeAction(final String action, final NodeRef ... nodeRefs)
{
executeAction(action, null, AuthenticationUtil.SYSTEM_USER_NAME, nodeRefs);
}
/**
*
* @param action
* @param params
* @param nodeRefs
*/
protected void executeAction(final String action, final Map<String, Serializable> params, final NodeRef ... nodeRefs)
{
executeAction(action, params, AuthenticationUtil.SYSTEM_USER_NAME, nodeRefs);
}
/**
*
* @param action
* @param params
* @param user
* @param nodeRefs
*/
protected void checkExecuteActionFail(final String action, final Map<String, Serializable> params, final String user, final NodeRef ... nodeRefs)
{
try
{
executeAction(action, params, user, nodeRefs);
fail("Action " + action + " has succeded and was expected to fail");
}
catch (AccessDeniedException ade)
{}
}
/**
*
* @param nodeRef
* @param property
* @param user
*/
protected void checkSetPropertyFail(final NodeRef nodeRef, final QName property, final String user, final Serializable value)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(user);
try
{
publicNodeService.setProperty(nodeRef, property, value);
fail("Expected failure when setting property");
}
catch (AccessDeniedException ade)
{}
return null;
}
}, false, true);
}
/**
* Add a capability
* @param capability
* @param authority
* @param nodeRefs
*/
protected void addCapability(final String capability, final String authority, final NodeRef ... nodeRefs)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
for (NodeRef nodeRef : nodeRefs)
{
permissionService.setPermission(nodeRef, authority, capability, true);
}
return null;
}
}, false, true);
}
/**
* Remove capability
* @param capability
* @param authority
* @param nodeRef
*/
protected void removeCapability(final String capability, final String authority, final NodeRef ... nodeRefs)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
for (NodeRef nodeRef : nodeRefs)
{
permissionService.deletePermission(nodeRef, authority, capability);
}
return null;
}
}, false, true);
}
/**
*
* @param nodeRefs
*/
protected void declare(final NodeRef ... nodeRefs)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
for (NodeRef nodeRef : nodeRefs)
{
nodeService.setProperty(nodeRef, RecordsManagementModel.PROP_ORIGINATOR, "origValue");
nodeService.setProperty(nodeRef, RecordsManagementModel.PROP_ORIGINATING_ORGANIZATION, "origOrgValue");
nodeService.setProperty(nodeRef, RecordsManagementModel.PROP_PUBLICATION_DATE, new Date());
nodeService.setProperty(nodeRef, ContentModel.PROP_TITLE, "titleValue");
recordsManagementActionService.executeRecordsManagementAction(nodeRef, "declareRecord");
}
return null;
}
}, false, true);
}
protected void cutoff(final NodeRef ... nodeRefs)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
for (NodeRef nodeRef : nodeRefs)
{
NodeRef ndNodeRef = nodeService.getChildAssocs(nodeRef, RecordsManagementModel.ASSOC_NEXT_DISPOSITION_ACTION, RegexQNamePattern.MATCH_ALL).get(0).getChildRef();
nodeService.setProperty(ndNodeRef, RecordsManagementModel.PROP_DISPOSITION_AS_OF, calendar.getTime());
recordsManagementActionService.executeRecordsManagementAction(nodeRef, "cutoff", null);
}
return null;
}
}, false, true);
}
protected void makeEligible(final NodeRef ... nodeRefs)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
for (NodeRef nodeRef : nodeRefs)
{
NodeRef ndNodeRef = nodeService.getChildAssocs(nodeRef, RecordsManagementModel.ASSOC_NEXT_DISPOSITION_ACTION, RegexQNamePattern.MATCH_ALL).get(0).getChildRef();
nodeService.setProperty(ndNodeRef, RecordsManagementModel.PROP_DISPOSITION_AS_OF, calendar.getTime());
}
return null;
}
}, false, true);
}
}

View File

@@ -0,0 +1,903 @@
/*
* 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.capabilities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
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.RecordsManagementService;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionService;
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.RMEntryVoter;
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.disposition.DispositionService;
import org.alfresco.module.org_alfresco_module_rm.event.RecordsManagementEventService;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.security.RecordsManagementSecurityService;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.security.permissions.AccessDeniedException;
import org.alfresco.repo.security.permissions.impl.model.PermissionModel;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
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.StoreRef;
import org.alfresco.service.cmr.security.AccessStatus;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.AuthorityType;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.ApplicationContextHelper;
import org.springframework.context.ApplicationContext;
/**
* @author Roy Wetherall
*/
public abstract class BaseTestCapabilities extends TestCase
implements RMPermissionModel, RecordsManagementModel
{
/* Application context */
protected ApplicationContext ctx;
/* Root node reference */
protected StoreRef storeRef;
protected NodeRef rootNodeRef;
/* Services */
protected NodeService nodeService;
protected NodeService publicNodeService;
protected TransactionService transactionService;
protected PermissionService permissionService;
protected RecordsManagementService recordsManagementService;
protected RecordsManagementSecurityService recordsManagementSecurityService;
protected RecordsManagementActionService recordsManagementActionService;
protected RecordsManagementEventService recordsManagementEventService;
protected DispositionService dispositionService;
protected CapabilityService capabilityService;
protected PermissionModel permissionModel;
protected ContentService contentService;
protected AuthorityService authorityService;
protected PersonService personService;
protected ContentService publicContentService;
protected RetryingTransactionHelper retryingTransactionHelper;
protected RMEntryVoter rmEntryVoter;
protected UserTransaction testTX;
protected NodeRef filePlan;
protected NodeRef recordSeries;
protected NodeRef recordCategory_1;
protected NodeRef recordCategory_2;
protected NodeRef recordFolder_1;
protected NodeRef recordFolder_2;
protected NodeRef record_1;
protected NodeRef record_2;
protected NodeRef recordCategory_3;
protected NodeRef recordFolder_3;
protected NodeRef record_3;
// protected String rmUsers;
// protected String rmPowerUsers;
// protected String rmSecurityOfficers;
// protected String rmRecordsManagers;
// protected String rmAdministrators;
protected String rm_user;
protected String rm_power_user;
protected String rm_security_officer;
protected String rm_records_manager;
protected String rm_administrator;
protected String test_user;
protected String testers;
protected String[] stdUsers;
protected NodeRef[] stdNodeRefs;;
/**
* Test setup
* @throws Exception
*/
protected void setUp() throws Exception
{
// Get the application context
ctx = ApplicationContextHelper.getApplicationContext();
// Get beans
nodeService = (NodeService) ctx.getBean("dbNodeService");
publicNodeService = (NodeService) ctx.getBean("NodeService");
transactionService = (TransactionService) ctx.getBean("transactionComponent");
permissionService = (PermissionService) ctx.getBean("permissionService");
permissionModel = (PermissionModel) ctx.getBean("permissionsModelDAO");
contentService = (ContentService) ctx.getBean("contentService");
publicContentService = (ContentService) ctx.getBean("ContentService");
authorityService = (AuthorityService) ctx.getBean("authorityService");
personService = (PersonService) ctx.getBean("personService");
capabilityService = (CapabilityService)ctx.getBean("CapabilityService");
dispositionService = (DispositionService)ctx.getBean("DispositionService");
recordsManagementService = (RecordsManagementService) ctx.getBean("RecordsManagementService");
recordsManagementSecurityService = (RecordsManagementSecurityService) ctx.getBean("RecordsManagementSecurityService");
recordsManagementActionService = (RecordsManagementActionService) ctx.getBean("RecordsManagementActionService");
recordsManagementEventService = (RecordsManagementEventService) ctx.getBean("RecordsManagementEventService");
rmEntryVoter = (RMEntryVoter) ctx.getBean("rmEntryVoter");
retryingTransactionHelper = (RetryingTransactionHelper)ctx.getBean("retryingTransactionHelper");
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
// As system user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
// Create store and get the root node reference
storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
rootNodeRef = nodeService.getRootNode(storeRef);
// As admin user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
// Create test events
recordsManagementEventService.getEvents();
recordsManagementEventService.addEvent("rmEventType.simple", "event", "My Event");
// Create file plan node
filePlan = nodeService.createNode(
rootNodeRef,
ContentModel.ASSOC_CHILDREN,
TYPE_FILE_PLAN,
TYPE_FILE_PLAN).getChildRef();
return null;
}
}, false, true);
// Load in the plan data required for the test
loadFilePlanData();
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
// As system user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
// create people ...
rm_user = "rm_user_" + storeRef.getIdentifier();
rm_power_user = "rm_power_user_" + storeRef.getIdentifier();
rm_security_officer = "rm_security_officer_" + storeRef.getIdentifier();
rm_records_manager = "rm_records_manager_" + storeRef.getIdentifier();
rm_administrator = "rm_administrator_" + storeRef.getIdentifier();
test_user = "test_user_" + storeRef.getIdentifier();
personService.createPerson(createDefaultProperties(rm_user));
personService.createPerson(createDefaultProperties(rm_power_user));
personService.createPerson(createDefaultProperties(rm_security_officer));
personService.createPerson(createDefaultProperties(rm_records_manager));
personService.createPerson(createDefaultProperties(rm_administrator));
personService.createPerson(createDefaultProperties(test_user));
// create roles as groups
// rmUsers = authorityService.createAuthority(AuthorityType.GROUP, "RM_USER_" + storeRef.getIdentifier());
// rmPowerUsers = authorityService.createAuthority(AuthorityType.GROUP, "RM_POWER_USER_" + storeRef.getIdentifier());
// rmSecurityOfficers = authorityService.createAuthority(AuthorityType.GROUP, "RM_SECURITY_OFFICER_" + storeRef.getIdentifier());
// rmRecordsManagers = authorityService.createAuthority(AuthorityType.GROUP, "RM_RECORDS_MANAGER_" + storeRef.getIdentifier());
// rmAdministrators = authorityService.createAuthority(AuthorityType.GROUP, "RM_ADMINISTRATOR_" + storeRef.getIdentifier());
testers = authorityService.createAuthority(AuthorityType.GROUP, "RM_TESTOR_" + storeRef.getIdentifier());
authorityService.addAuthority(testers, test_user);
// rmUsers = recordsManagementSecurityService.assignRoleToAuthority(filePlan, ROLE, rm_user);
setPermissions(rm_user, ROLE_NAME_USER);
setPermissions(rm_power_user, ROLE_NAME_POWER_USER);
setPermissions(rm_security_officer, ROLE_NAME_SECURITY_OFFICER);
setPermissions(rm_records_manager, ROLE_NAME_RECORDS_MANAGER);
setPermissions(rm_administrator, ROLE_NAME_ADMINISTRATOR);
stdUsers = new String[]
{
AuthenticationUtil.getSystemUserName(),
rm_administrator,
rm_records_manager,
rm_security_officer,
rm_power_user,
rm_user
};
stdNodeRefs = new NodeRef[]
{
recordFolder_1,
record_1,
recordFolder_2,
record_2
};
return null;
}
}, false, true);
}
/**
* Test tear down
* @throws Exception
*/
@Override
protected void tearDown() throws Exception
{
// TODO we should clean up as much as we can ....
}
/**
* Set the permissions for a group, user and role
* @param group
* @param user
* @param role
*/
private void setPermissions(String user, String role)
{
recordsManagementSecurityService.assignRoleToAuthority(filePlan, role, user);
recordsManagementSecurityService.setPermission(filePlan, user, FILING);
}
/**
* Loads the file plan date required for the tests
*/
protected void loadFilePlanData()
{
recordSeries = createRecordSeries(filePlan, "RS", "Record Series", "My record series");
recordCategory_1 = createRecordCategory(recordSeries, "Docs", "Docs", "Docs", "week|1", true, false);
recordCategory_2 = createRecordCategory(recordSeries, "More Docs", "More Docs", "More Docs", "week|1", true, true);
recordCategory_3 = createRecordSeries(recordSeries, "No Dis", "No disp schedule", "No disp schedule");
recordFolder_1 = createRecordFolder(recordCategory_1, "F1", "title", "description");
recordFolder_2 = createRecordFolder(recordCategory_2, "F2", "title", "description");
recordFolder_3 = createRecordFolder(recordCategory_3, "F3", "title", "description");
record_1 = createRecord(recordFolder_1);
record_2 = createRecord(recordFolder_2);
record_3 = createRecord(recordFolder_3);
}
/**
* Set permission for authority on node reference.
* @param nodeRef
* @param authority
* @param permission
* @param allow
*/
// private void setPermission(NodeRef nodeRef, String authority, String permission, boolean allow)
// {
// permissionService.setPermission(nodeRef, authority, permission, allow);
// if (permission.equals(FILING))
// {
// if (recordsManagementService.isRecordCategory(nodeRef) == true)
// {
// List<ChildAssociationRef> assocs = nodeService.getChildAssocs(nodeRef, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
// for (ChildAssociationRef assoc : assocs)
// {
// NodeRef child = assoc.getChildRef();
// if (recordsManagementService.isRecordFolder(child) == true ||
// recordsManagementService.isRecordCategory(child) == true)
// {
// setPermission(child, authority, permission, allow);
// }
// }
// }
// }
// }
/**
* Create the default person properties
* @param userName
* @return
*/
private Map<QName, Serializable> createDefaultProperties(String userName)
{
HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(ContentModel.PROP_USERNAME, userName);
properties.put(ContentModel.PROP_HOMEFOLDER, null);
properties.put(ContentModel.PROP_FIRSTNAME, userName);
properties.put(ContentModel.PROP_LASTNAME, userName);
properties.put(ContentModel.PROP_EMAIL, userName);
properties.put(ContentModel.PROP_ORGID, "");
return properties;
}
/**
* Create a new record. Executed in a new transaction.
*/
private NodeRef createRecord(final NodeRef recordFolder)
{
return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
{
@Override
public NodeRef execute() throws Throwable
{
// As admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
// Create the record
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
props.put(ContentModel.PROP_NAME, "MyRecord.txt");
NodeRef recordOne = nodeService.createNode(recordFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "MyRecord.txt"),
ContentModel.TYPE_CONTENT, props).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("There is some content in this record");
return recordOne;
}
}, false, true);
}
/**
* Create a test record series. Executed in a new transaction.
*/
private NodeRef createRecordSeries(final NodeRef filePlan, final String name, final String title, final String description)
{
return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
{
@Override
public NodeRef execute() throws Throwable
{
// As admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(ContentModel.PROP_TITLE, title);
properties.put(ContentModel.PROP_DESCRIPTION, description);
return recordsManagementService.createRecordCategory(filePlan, name, properties);
}
}, false, true);
}
/**
* Create a test record category in a new transaction.
*/
private NodeRef createRecordCategory(
final NodeRef recordSeries,
final String name,
final String title,
final String description,
final String review,
final boolean vital,
final boolean recordLevelDisposition)
{
return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
{
@Override
public NodeRef execute() throws Throwable
{
// As admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(ContentModel.PROP_TITLE, title);
properties.put(ContentModel.PROP_DESCRIPTION, description);
if (vital == true)
{
properties.put(PROP_REVIEW_PERIOD, review);
properties.put(PROP_VITAL_RECORD_INDICATOR, vital);
}
NodeRef rc = recordsManagementService.createRecordCategory(recordSeries, name, properties);
properties = new HashMap<QName, Serializable>();
properties.put(PROP_DISPOSITION_AUTHORITY, "N1-218-00-4 item 023");
properties.put(PROP_DISPOSITION_INSTRUCTIONS, "Cut off monthly, hold 1 month, then destroy.");
properties.put(PROP_RECORD_LEVEL_DISPOSITION, recordLevelDisposition);
DispositionSchedule ds = dispositionService.createDispositionSchedule(rc, properties);
addDispositionAction(ds, "cutoff", "monthend|1", null, "event");
addDispositionAction(ds, "transfer", "month|1", null, null);
addDispositionAction(ds, "accession", "month|1", null, null);
addDispositionAction(ds, "destroy", "month|1", "{http://www.alfresco.org/model/recordsmanagement/1.0}cutOffDate", null);
return rc;
}
}, false, true);
}
/**
* Create disposition action.
* @param disposition
* @param actionName
* @param period
* @param periodProperty
* @param event
* @return
*/
private void addDispositionAction(DispositionSchedule disposition, String actionName, String period, String periodProperty, String event)
{
HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(PROP_DISPOSITION_ACTION_NAME, actionName);
properties.put(PROP_DISPOSITION_PERIOD, period);
if (periodProperty != null)
{
properties.put(PROP_DISPOSITION_PERIOD_PROPERTY, periodProperty);
}
if (event != null)
{
properties.put(PROP_DISPOSITION_EVENT, event);
}
dispositionService.addDispositionActionDefinition(disposition, properties);
}
/**
* Create record folder. Executed in a new transaction.
* @param recordCategory
* @param name
* @param identifier
* @param title
* @param description
* @param review
* @param vital
* @return
*/
private NodeRef createRecordFolder(
final NodeRef recordCategory,
final String name,
final String title,
final String description)
{
return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
{
@Override
public NodeRef execute() throws Throwable
{
// As admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(ContentModel.PROP_TITLE, title);
properties.put(ContentModel.PROP_DESCRIPTION, description);
return recordsManagementService.createRecordFolder(recordCategory, name, properties);
}
}, false, true);
}
/**
*
* @param user
* @param nodeRef
* @param capabilityName
* @param accessStstus
*/
protected void checkCapability(final String user, final NodeRef nodeRef, final String capabilityName, final AccessStatus expected)
{
AuthenticationUtil.runAs(new RunAsWork<Object>()
{
@Override
public Object doWork() throws Exception
{
Capability capability = recordsManagementSecurityService.getCapability(capabilityName);
assertNotNull(capability);
List<String> capabilities = new ArrayList<String>(1);
capabilities.add(capabilityName);
Map<Capability, AccessStatus> access = capabilityService.getCapabilitiesAccessState(nodeRef, capabilities);
AccessStatus actual = access.get(capability);
assertEquals(
"for user: " + user,
expected,
actual);
return null;
}
}, user);
}
/**
*
* @param access
* @param name
* @param accessStatus
*/
protected void check(Map<Capability, AccessStatus> access, String name, AccessStatus accessStatus)
{
Capability capability = recordsManagementSecurityService.getCapability(name);
assertNotNull(capability);
assertEquals(accessStatus, access.get(capability));
}
/**
*
* @param user
* @param nodeRef
* @param permission
* @param accessStstus
*/
protected void checkPermission(final String user, final NodeRef nodeRef, final String permission, final AccessStatus accessStstus)
{
AuthenticationUtil.runAs(new RunAsWork<Object>()
{
@Override
public Object doWork() throws Exception
{
AccessStatus actualAccessStatus = permissionService.hasPermission(nodeRef, permission);
assertTrue(actualAccessStatus == accessStstus);
return null;
}
}, user);
}
/**
*
* @param nodeRef
* @param permission
* @param users
* @param expectedAccessStatus
*/
protected void checkPermissions(
final NodeRef nodeRef,
final String permission,
final String[] users,
final AccessStatus ... expectedAccessStatus)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
assertEquals(
"The number of users should match the number of expected access status",
users.length,
expectedAccessStatus.length);
for (int i = 0; i < users.length; i++)
{
checkPermission(users[i], nodeRef, permission, expectedAccessStatus[i]);
}
return null;
}
}, true, true);
}
/**
*
* @param nodeRef
* @param capability
* @param users
* @param expectedAccessStatus
*/
protected void checkCapabilities(
final NodeRef nodeRef,
final String capability,
final String[] users,
final AccessStatus ... expectedAccessStatus)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
assertEquals(
"The number of users should match the number of expected access status",
users.length,
expectedAccessStatus.length);
for (int i = 0; i < users.length; i++)
{
checkCapability(users[i], nodeRef, capability, expectedAccessStatus[i]);
}
return null;
}
}, true, true);
}
/**
*
* @param user
* @param capability
* @param nodeRefs
* @param expectedAccessStatus
*/
protected void checkCapabilities(
final String user,
final String capability,
final NodeRef[] nodeRefs,
final AccessStatus ... expectedAccessStatus)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
assertEquals(
"The number of node references should match the number of expected access status",
nodeRefs.length,
expectedAccessStatus.length);
for (int i = 0; i < nodeRefs.length; i++)
{
checkCapability(user, nodeRefs[i], capability, expectedAccessStatus[i]);
}
return null;
}
}, true, true);
}
/**
*
* @param capability
* @param accessStatus
*/
protected void checkTestUserCapabilities(String capability, AccessStatus ... accessStatus)
{
checkCapabilities(
test_user,
capability,
stdNodeRefs,
accessStatus);
}
/**
* Execute RM action
* @param action
* @param params
* @param nodeRefs
*/
protected void executeAction(final String action, final Map<String, Serializable> params, final String user, final NodeRef ... nodeRefs)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(user);
for (NodeRef nodeRef : nodeRefs)
{
recordsManagementActionService.executeRecordsManagementAction(nodeRef, action, params);
}
return null;
}
}, false, true);
}
/**
*
* @param action
* @param nodeRefs
*/
protected void executeAction(final String action, final NodeRef ... nodeRefs)
{
executeAction(action, null, AuthenticationUtil.SYSTEM_USER_NAME, nodeRefs);
}
/**
*
* @param action
* @param params
* @param nodeRefs
*/
protected void executeAction(final String action, final Map<String, Serializable> params, final NodeRef ... nodeRefs)
{
executeAction(action, params, AuthenticationUtil.SYSTEM_USER_NAME, nodeRefs);
}
/**
*
* @param action
* @param params
* @param user
* @param nodeRefs
*/
protected void checkExecuteActionFail(final String action, final Map<String, Serializable> params, final String user, final NodeRef ... nodeRefs)
{
try
{
executeAction(action, params, user, nodeRefs);
fail("Action " + action + " has succeded and was expected to fail");
}
catch (AccessDeniedException ade)
{}
}
/**
*
* @param nodeRef
* @param property
* @param user
*/
protected void checkSetPropertyFail(final NodeRef nodeRef, final QName property, final String user, final Serializable value)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(user);
try
{
publicNodeService.setProperty(nodeRef, property, value);
fail("Expected failure when setting property");
}
catch (AccessDeniedException ade)
{}
return null;
}
}, false, true);
}
/**
* Add a capability
* @param capability
* @param authority
* @param nodeRefs
*/
protected void addCapability(final String capability, final String authority, final NodeRef ... nodeRefs)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
for (NodeRef nodeRef : nodeRefs)
{
permissionService.setPermission(nodeRef, authority, capability, true);
}
return null;
}
}, false, true);
}
/**
* Remove capability
* @param capability
* @param authority
* @param nodeRef
*/
protected void removeCapability(final String capability, final String authority, final NodeRef ... nodeRefs)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
for (NodeRef nodeRef : nodeRefs)
{
permissionService.deletePermission(nodeRef, authority, capability);
}
return null;
}
}, false, true);
}
/**
*
* @param nodeRefs
*/
protected void declare(final NodeRef ... nodeRefs)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
for (NodeRef nodeRef : nodeRefs)
{
nodeService.setProperty(nodeRef, RecordsManagementModel.PROP_ORIGINATOR, "origValue");
nodeService.setProperty(nodeRef, RecordsManagementModel.PROP_ORIGINATING_ORGANIZATION, "origOrgValue");
nodeService.setProperty(nodeRef, RecordsManagementModel.PROP_PUBLICATION_DATE, new Date());
nodeService.setProperty(nodeRef, ContentModel.PROP_TITLE, "titleValue");
recordsManagementActionService.executeRecordsManagementAction(nodeRef, "declareRecord");
}
return null;
}
}, false, true);
}
protected void cutoff(final NodeRef ... nodeRefs)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
for (NodeRef nodeRef : nodeRefs)
{
NodeRef ndNodeRef = nodeService.getChildAssocs(nodeRef, RecordsManagementModel.ASSOC_NEXT_DISPOSITION_ACTION, RegexQNamePattern.MATCH_ALL).get(0).getChildRef();
nodeService.setProperty(ndNodeRef, RecordsManagementModel.PROP_DISPOSITION_AS_OF, calendar.getTime());
recordsManagementActionService.executeRecordsManagementAction(nodeRef, "cutoff", null);
}
return null;
}
}, false, true);
}
protected void makeEligible(final NodeRef ... nodeRefs)
{
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
for (NodeRef nodeRef : nodeRefs)
{
NodeRef ndNodeRef = nodeService.getChildAssocs(nodeRef, RecordsManagementModel.ASSOC_NEXT_DISPOSITION_ACTION, RegexQNamePattern.MATCH_ALL).get(0).getChildRef();
nodeService.setProperty(ndNodeRef, RecordsManagementModel.PROP_DISPOSITION_AS_OF, calendar.getTime());
}
return null;
}
}, false, true);
}
}

View File

@@ -0,0 +1,245 @@
/*
* 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.capabilities;
import java.util.ArrayList;
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.FilePlanComponentKind;
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.DeclarativeCapability;
import org.alfresco.module.org_alfresco_module_rm.security.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 recordFolderContainsFrozen;
private NodeRef frozenRecord;
private NodeRef frozenRecord2;
private NodeRef frozenRecordFolder;
@Override
protected boolean isUserTest()
{
return true;
}
@Override
protected void setupTestDataImpl()
{
super.setupTestDataImpl();
// Pre-filed content
record = createRecord(rmFolder, "record.txt");
declaredRecord = createRecord(rmFolder, "declaredRecord.txt");
// Open folder
// Closed folder
recordFolderContainsFrozen = rmService.createRecordFolder(rmContainer, "containsFrozen");
frozenRecord = createRecord(rmFolder, "frozenRecord.txt");
frozenRecord2 = createRecord(recordFolderContainsFrozen, "frozen2.txt");
frozenRecordFolder = rmService.createRecordFolder(rmContainer, "frozenRecordFolder");
}
@Override
protected void setupTestData()
{
super.setupTestData();
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
@Override
public Object execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
declareRecord(declaredRecord);
declareRecord(frozenRecord);
declareRecord(frozenRecord2);
freeze(frozenRecord);
freeze(frozenRecordFolder);
freeze(frozenRecord2);
return null;
}
});
}
@Override
protected void tearDownImpl()
{
// Unfreeze stuff so it can be deleted
unfreeze(frozenRecord);
unfreeze(frozenRecordFolder);
unfreeze(frozenRecord2);
super.tearDownImpl();
}
@Override
protected void setupTestUsersImpl(NodeRef filePlan)
{
super.setupTestUsersImpl(filePlan);
// Give all the users file permission objects
for (String user : testUsers)
{
securityService.setPermission(rmFolder, user, RMPermissionModel.FILING);
}
}
public void testDeclarativeCapabilities()
{
Set<Capability> capabilities = capabilityService.getCapabilities();
for (Capability capability : capabilities)
{
if (capability instanceof DeclarativeCapability &&
capability.isGroupCapability() == false &&
capability.getName().equals("MoveRecords") == false &&
capability.getName().equals("DeleteLinks") == false &&
capability.getName().equals("ChangeOrDeleteReferences") == false &&
capability.getActionNames().isEmpty() == true)
{
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 = securityService.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 = rmService.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<String> roleCapabilities = role.getCapabilities();
if (roleCapabilities.contains(capability.getName()) == 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;
}
public void testFrozenCondition()
{
}
}

View File

@@ -0,0 +1,18 @@
function main()
{
test.assertNotNull(filePlan);
test.assertNotNull(record);
var rmNode = rmService.getRecordsManagementNode(record);
test.assertNotNull(rmNode);
var capabilities = rmNode.capabilities;
var countCheck = capabilities.length != 0;
test.assertTrue(countCheck);
var capability = capabilities[0];
test.assertNotNull(capability);
test.assertNotNull(capability.name);
}
main();

View File

@@ -0,0 +1,159 @@
/*
* 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 = 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"},
new String[]{"rmNode.closed", "false", "boolean"},
new String[]{"rmNode.declared", "false", "boolean"},
new String[]{"rmNode.frozen", "false", "boolean"},
new String[]{"rmNode.metatdata-stub", "false", "boolean"}
//containsFrozen
){});
doTestInTransaction(new JSONTest
(
record,
new String[]{"isRmNode", "true", "boolean"},
new String[]{"rmNode.kind", "RECORD"},
new String[]{"rmNode.declared", "false", "boolean"},
new String[]{"rmNode.frozen", "false", "boolean"},
new String[]{"rmNode.metatdata-stub", "false", "boolean"}
){});
}
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-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.util.HashMap;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.repo.jscript.ClasspathScriptLocation;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.ScriptLocation;
import org.alfresco.service.cmr.repository.ScriptService;
/**
* @author Roy Wetherall
*/
public class RMJScriptTest extends BaseRMTestCase
{
private static String SCRIPT_PATH = "org/alfresco/module/org_alfresco_module_rm/test/jscript/";
private static String CAPABILITIES_TEST = "CapabilitiesTest.js";
private ScriptService scriptService;
@Override
protected void initServices()
{
this.scriptService = (ScriptService)this.applicationContext.getBean("ScriptService");
}
public void testCapabilities() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
NodeRef record = createRecord(rmFolder, "testRecord.txt");
declareRecord(record);
return record;
}
@Override
public void test(NodeRef record) throws Exception
{
// Create a model to pass to the unit test scripts
Map<String, Object> model = new HashMap<String, Object>(1);
model.put("filePlan", filePlan);
model.put("record", record);
executeScript(CAPABILITIES_TEST, model);
}
});
}
private void executeScript(String script, Map<String, Object> model)
{
// Execute the unit test script
ScriptLocation location = new ClasspathScriptLocation(SCRIPT_PATH + script);
this.scriptService.executeScript(location, model);
}
}

View File

@@ -0,0 +1,800 @@
/*
* 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.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionAction;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionActionDefinition;
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.EventCompletionDetails;
import org.alfresco.module.org_alfresco_module_rm.job.publish.PublishExecutor;
import org.alfresco.module.org_alfresco_module_rm.job.publish.PublishExecutorRegistry;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
/**
* Disposition service implementation unit test.
*
* @author Roy Wetherall
*/
public class DispositionServiceImplTest extends BaseRMTestCase
{
@Override
protected boolean isMultiHierarchyTest()
{
return true;
}
/**
* @see DispositionService#getDispositionSchedule(org.alfresco.service.cmr.repository.NodeRef)
*/
public void testGetDispositionSchedule() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// Check for null lookup's
assertNull(dispositionService.getDispositionSchedule(filePlan));
// Get the containers disposition schedule
DispositionSchedule ds = dispositionService.getDispositionSchedule(rmContainer);
assertNotNull(ds);
checkDispositionSchedule(ds, false);
// Get the folders disposition schedule
ds = dispositionService.getDispositionSchedule(rmContainer);
assertNotNull(ds);
checkDispositionSchedule(ds, false);
return null;
}
});
// Failure: Root node
doTestInTransaction(new FailureTest
(
"Should not be able to get adisposition schedule for the root node",
AlfrescoRuntimeException.class
)
{
@Override
public void run()
{
dispositionService.getDispositionSchedule(rootNodeRef);
}
});
// Failure: Non-rm node
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
dispositionService.getDispositionSchedule(folder);
}
});
}
/**
* @see DispositionService#getDispositionSchedule(org.alfresco.service.cmr.repository.NodeRef)
*/
public void testGetDispositionScheduleMultiHier() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertNull(dispositionService.getDispositionSchedule(mhContainer));
// Level 1
doCheck(mhContainer11, "ds11", false);
doCheck(mhContainer12, "ds12", false);
// Level 2
doCheck(mhContainer21, "ds11", false);
doCheck(mhContainer22, "ds12", false);
doCheck(mhContainer23, "ds23", false);
// Level 3
doCheck(mhContainer31, "ds11", false);
doCheck(mhContainer32, "ds12", false);
doCheck(mhContainer33, "ds33", true);
doCheck(mhContainer34, "ds23", false);
doCheck(mhContainer35, "ds35", true);
// Folders
doCheckFolder(mhRecordFolder41, "ds11", false);
doCheckFolder(mhRecordFolder42, "ds12", false);
doCheckFolder(mhRecordFolder43, "ds33", true);
doCheckFolder(mhRecordFolder44, "ds23", false);
doCheckFolder(mhRecordFolder45, "ds35", true);
return null;
}
private void doCheck(NodeRef container, String dispositionInstructions, boolean isRecordLevel)
{
DispositionSchedule ds = dispositionService.getDispositionSchedule(container);
assertNotNull(ds);
checkDispositionSchedule(ds, dispositionInstructions, DEFAULT_DISPOSITION_AUTHORITY, isRecordLevel);
}
private void doCheckFolder(NodeRef container, String dispositionInstructions, boolean isRecordLevel)
{
doCheck(container, dispositionInstructions, isRecordLevel);
if (isRecordLevel == false)
{
assertNotNull(dispositionService.getNextDispositionAction(container));
}
}
});
}
/**
* Checks a disposition schedule
*
* @param ds disposition scheduleS
*/
private void checkDispositionSchedule(DispositionSchedule ds, String dispositionInstructions, String dispositionAuthority, boolean isRecordLevel)
{
assertEquals(dispositionAuthority, ds.getDispositionAuthority());
assertEquals(dispositionInstructions, ds.getDispositionInstructions());
assertEquals(isRecordLevel, ds.isRecordLevelDisposition());
List<DispositionActionDefinition> defs = ds.getDispositionActionDefinitions();
assertNotNull(defs);
assertEquals(2, defs.size());
DispositionActionDefinition defCutoff = ds.getDispositionActionDefinitionByName("cutoff");
assertNotNull(defCutoff);
assertEquals("cutoff", defCutoff.getName());
DispositionActionDefinition defDestroy = ds.getDispositionActionDefinitionByName("destroy");
assertNotNull(defDestroy);
assertEquals("destroy", defDestroy.getName());
}
/**
*
* @param ds
*/
private void checkDispositionSchedule(DispositionSchedule ds, boolean isRecordLevel)
{
checkDispositionSchedule(ds, DEFAULT_DISPOSITION_INSTRUCTIONS, DEFAULT_DISPOSITION_AUTHORITY, isRecordLevel);
}
/**
* @see DispositionService#getAssociatedDispositionSchedule(NodeRef)
*/
public void testGetAssociatedDispositionSchedule() throws Exception
{
// Get associated disposition schedule for rmContainer
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// Get the containers disposition schedule
DispositionSchedule ds = dispositionService.getAssociatedDispositionSchedule(rmContainer);
assertNotNull(ds);
checkDispositionSchedule(ds, false);
// Show the null disposition schedules
assertNull(dispositionService.getAssociatedDispositionSchedule(filePlan));
assertNull(dispositionService.getAssociatedDispositionSchedule(rmFolder));
return null;
}
});
// Failure: associated disposition schedule for non-rm node
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
dispositionService.getAssociatedDispositionSchedule(folder);
}
});
}
/**
* @see DispositionService#getAssociatedDispositionSchedule(NodeRef)
*/
public void testGetAssociatedDispositionScheduleMultiHier() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertNull(dispositionService.getAssociatedDispositionSchedule(mhContainer));
// Level 1
doCheck(mhContainer11, "ds11", false);
doCheck(mhContainer12, "ds12", false);
// Level 2
assertNull(dispositionService.getAssociatedDispositionSchedule(mhContainer21));
assertNull(dispositionService.getAssociatedDispositionSchedule(mhContainer22));
doCheck(mhContainer23, "ds23", false);
// Level 3
assertNull(dispositionService.getAssociatedDispositionSchedule(mhContainer31));
assertNull(dispositionService.getAssociatedDispositionSchedule(mhContainer32));
doCheck(mhContainer33, "ds33", true);
assertNull(dispositionService.getAssociatedDispositionSchedule(mhContainer34));
doCheck(mhContainer35, "ds35", true);
return null;
}
private void doCheck(NodeRef container, String dispositionInstructions, boolean isRecordLevel)
{
DispositionSchedule ds = dispositionService.getAssociatedDispositionSchedule(container);
assertNotNull(ds);
checkDispositionSchedule(ds, dispositionInstructions, DEFAULT_DISPOSITION_AUTHORITY, isRecordLevel);
}
});
}
/**
* @see DispositionService#hasDisposableItems(DispositionSchedule)
*/
public void testHasDisposableItems() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// Add a new disposition schedule
NodeRef container = rmService.createRecordCategory(rmContainer, "hasDisposableTest");
DispositionSchedule ds = createBasicDispositionSchedule(container);
assertTrue(dispositionService.hasDisposableItems(dispositionSchedule));
assertFalse(dispositionService.hasDisposableItems(ds));
return null;
}
});
}
/**
* @see DispositionService#hasDisposableItems(DispositionSchedule)
*/
public void testHasDisposableItemsMultiHier() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
assertTrue(dispositionService.hasDisposableItems(mhDispositionSchedule11));
assertTrue(dispositionService.hasDisposableItems(mhDispositionSchedule12));
assertTrue(dispositionService.hasDisposableItems(mhDispositionSchedule23));
assertFalse(dispositionService.hasDisposableItems(mhDispositionSchedule33));
assertFalse(dispositionService.hasDisposableItems(mhDispositionSchedule35));
return null;
}
});
}
/**
* @see DispositionService#getDisposableItems(DispositionSchedule)
*/
public void testGetDisposableItems() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
List<NodeRef> nodeRefs = dispositionService.getDisposableItems(dispositionSchedule);
assertNotNull(nodeRefs);
assertEquals(1, nodeRefs.size());
assertTrue(nodeRefs.contains(rmFolder));
return null;
}
});
}
/**
* @see DispositionService#getDisposableItems(DispositionSchedule)
*/
public void testGetDisposableItemsMultiHier() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
List<NodeRef> nodeRefs = dispositionService.getDisposableItems(mhDispositionSchedule11);
assertNotNull(nodeRefs);
assertEquals(1, nodeRefs.size());
assertTrue(nodeRefs.contains(mhRecordFolder41));
nodeRefs = dispositionService.getDisposableItems(mhDispositionSchedule12);
assertNotNull(nodeRefs);
assertEquals(1, nodeRefs.size());
assertTrue(nodeRefs.contains(mhRecordFolder42));
nodeRefs = dispositionService.getDisposableItems(mhDispositionSchedule23);
assertNotNull(nodeRefs);
assertEquals(1, nodeRefs.size());
assertTrue(nodeRefs.contains(mhRecordFolder44));
nodeRefs = dispositionService.getDisposableItems(mhDispositionSchedule33);
assertNotNull(nodeRefs);
assertEquals(0, nodeRefs.size());
nodeRefs = dispositionService.getDisposableItems(mhDispositionSchedule35);
assertNotNull(nodeRefs);
assertEquals(0, nodeRefs.size());
return null;
}
});
}
/**
* @see DispositionService#createDispositionSchedule(NodeRef, Map)
*/
public void testCreateDispositionSchedule() throws Exception
{
// Test: simple disposition create
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
// Create a new container
NodeRef container = rmService.createRecordCategory(filePlan, "testCreateDispositionSchedule");
// Create a new disposition schedule
createBasicDispositionSchedule(container, "testCreateDispositionSchedule", "testCreateDispositionSchedule", false, true);
return container;
}
@Override
public void test(NodeRef result) throws Exception
{
// Get the created disposition schedule
DispositionSchedule ds = dispositionService.getAssociatedDispositionSchedule(result);
assertNotNull(ds);
// Check the disposition schedule
checkDispositionSchedule(ds, "testCreateDispositionSchedule", "testCreateDispositionSchedule", false);
}
});
// Failure: create disposition schedule on container with existing disposition schedule
doTestInTransaction(new FailureTest
(
"Can not create a disposition schedule on a container with an existing disposition schedule"
)
{
@Override
public void run()
{
createBasicDispositionSchedule(rmContainer);
}
});
}
/**
* @see DispositionService#createDispositionSchedule(NodeRef, Map)
*/
public void testCreateDispositionScheduleMultiHier() throws Exception
{
// Test: simple disposition create
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
// Create a new structure container
NodeRef testA = rmService.createRecordCategory(mhContainer, "testA");
NodeRef testB = rmService.createRecordCategory(testA, "testB");
// Create new disposition schedules
createBasicDispositionSchedule(testA, "testA", "testA", false, true);
createBasicDispositionSchedule(testB, "testB", "testB", false, true);
// Add created containers to model
setNodeRef("testA", testA);
setNodeRef("testB", testB);
return null;
}
@Override
public void test(Void result) throws Exception
{
// Get the created disposition schedule
DispositionSchedule testA = dispositionService.getAssociatedDispositionSchedule(getNodeRef("testA"));
assertNotNull(testA);
DispositionSchedule testB = dispositionService.getAssociatedDispositionSchedule(getNodeRef("testB"));
assertNotNull(testB);
// Check the disposition schedule
checkDispositionSchedule(testA, "testA", "testA", false);
checkDispositionSchedule(testB, "testB", "testB", false);
}
});
// Failure: create disposition schedule on container with existing disposition schedule
doTestInTransaction(new FailureTest
(
"Can not create a disposition schedule on container with an existing disposition schedule"
)
{
@Override
public void run()
{
createBasicDispositionSchedule(mhContainer11);
}
});
// Failure: create disposition schedule on a container where there are disposable items under management
doTestInTransaction(new FailureTest
(
"Can not create a disposition schedule on a container where there are already disposable items under management"
)
{
@Override
public void run()
{
createBasicDispositionSchedule(mhContainer21);
}
});
}
/**
* @see DispositionService#getAssociatedRecordsManagementContainer(DispositionSchedule)
*/
public void testGetAssociatedRecordsManagementContainer() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
NodeRef nodeRef = dispositionService.getAssociatedRecordsManagementContainer(dispositionSchedule);
assertNotNull(nodeRef);
assertEquals(rmContainer, nodeRef);
return null;
}
});
}
/**
* @see DispositionService#getAssociatedRecordsManagementContainer(DispositionSchedule)
*/
public void testGetAssociatedRecordsManagementContainerMultiHier() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
NodeRef nodeRef = dispositionService.getAssociatedRecordsManagementContainer(mhDispositionSchedule11);
assertNotNull(nodeRef);
assertEquals(mhContainer11, nodeRef);
nodeRef = dispositionService.getAssociatedRecordsManagementContainer(mhDispositionSchedule12);
assertNotNull(nodeRef);
assertEquals(mhContainer12, nodeRef);
nodeRef = dispositionService.getAssociatedRecordsManagementContainer(mhDispositionSchedule23);
assertNotNull(nodeRef);
assertEquals(mhContainer23, nodeRef);
nodeRef = dispositionService.getAssociatedRecordsManagementContainer(mhDispositionSchedule33);
assertNotNull(nodeRef);
assertEquals(mhContainer33, nodeRef);
nodeRef = dispositionService.getAssociatedRecordsManagementContainer(mhDispositionSchedule35);
assertNotNull(nodeRef);
assertEquals(mhContainer35, nodeRef);
return null;
}
});
}
// TODO DispositionActionDefinition addDispositionActionDefinition
// TODO void removeDispositionActionDefinition(
private NodeRef record43;
private NodeRef record45;
public void testUpdateDispositionActionDefinitionMultiHier() throws Exception
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
record43 = createRecord(mhRecordFolder43, "record1.txt");
record45 = createRecord(mhRecordFolder45, "record2.txt");
return null;
}
});
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
// Check all the current record folders first
checkDisposableItemUnchanged(mhRecordFolder41);
checkDisposableItemUnchanged(mhRecordFolder42);
checkDisposableItemUnchanged(record43);
checkDisposableItemUnchanged(mhRecordFolder44);
checkDisposableItemUnchanged(record45);
updateDispositionScheduleOnContainer(mhContainer11);
return null;
}
@Override
public void test(Void result) throws Exception
{
// Check all the current record folders first
checkDisposableItemChanged(mhRecordFolder41);
checkDisposableItemUnchanged(mhRecordFolder42);
checkDisposableItemUnchanged(record43);
checkDisposableItemUnchanged(mhRecordFolder44);
checkDisposableItemUnchanged(record45);;
}
});
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
updateDispositionScheduleOnContainer(mhContainer12);
return null;
}
@Override
public void test(Void result) throws Exception
{
// Check all the current record folders first
checkDisposableItemChanged(mhRecordFolder41);
checkDisposableItemChanged(mhRecordFolder42);
checkDisposableItemUnchanged(record43);
checkDisposableItemUnchanged(mhRecordFolder44);
checkDisposableItemUnchanged(record45);;
}
});
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
updateDispositionScheduleOnContainer(mhContainer33);
return null;
}
@Override
public void test(Void result) throws Exception
{
// Check all the current record folders first
checkDisposableItemChanged(mhRecordFolder41);
checkDisposableItemChanged(mhRecordFolder42);
checkDisposableItemChanged(record43);
checkDisposableItemUnchanged(mhRecordFolder44);
checkDisposableItemUnchanged(record45);;
}
});
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
updateDispositionScheduleOnContainer(mhContainer23);
return null;
}
@Override
public void test(Void result) throws Exception
{
// Check all the current record folders first
checkDisposableItemChanged(mhRecordFolder41);
checkDisposableItemChanged(mhRecordFolder42);
checkDisposableItemChanged(record43);
checkDisposableItemChanged(mhRecordFolder44);
checkDisposableItemUnchanged(record45);
}
});
doTestInTransaction(new Test<Void>()
{
@Override
public Void run() throws Exception
{
updateDispositionScheduleOnContainer(mhContainer35);
return null;
}
@Override
public void test(Void result) throws Exception
{
// Check all the current record folders first
checkDisposableItemChanged(mhRecordFolder41);
checkDisposableItemChanged(mhRecordFolder42);
checkDisposableItemChanged(record43);
checkDisposableItemChanged(mhRecordFolder44);
checkDisposableItemChanged(record45);
}
});
}
private void publishDispositionActionDefinitionChange(DispositionActionDefinition dad)
{
PublishExecutorRegistry reg = (PublishExecutorRegistry)applicationContext.getBean("publishExecutorRegistry");
PublishExecutor pub = reg.get(RecordsManagementModel.UPDATE_TO_DISPOSITION_ACTION_DEFINITION);
assertNotNull(pub);
pub.publish(dad.getNodeRef());
}
private void checkDisposableItemUnchanged(NodeRef recordFolder)
{
checkDispositionAction(
dispositionService.getNextDispositionAction(recordFolder),
"cutoff",
new String[]{DEFAULT_EVENT_NAME},
PERIOD_NONE);
}
private void checkDisposableItemChanged(NodeRef recordFolder) throws Exception
{
checkDispositionAction(
dispositionService.getNextDispositionAction(recordFolder),
"cutoff",
new String[]{DEFAULT_EVENT_NAME, "abolished"},
"week|1");
}
private void updateDispositionScheduleOnContainer(NodeRef nodeRef)
{
Map<QName, Serializable> updateProps = new HashMap<QName, Serializable>(3);
updateProps.put(PROP_DISPOSITION_PERIOD, "week|1");
updateProps.put(PROP_DISPOSITION_EVENT, (Serializable)Arrays.asList(DEFAULT_EVENT_NAME, "abolished"));
DispositionSchedule ds = dispositionService.getDispositionSchedule(nodeRef);
DispositionActionDefinition dad = ds.getDispositionActionDefinitionByName("cutoff");
dispositionService.updateDispositionActionDefinition(dad, updateProps);
publishDispositionActionDefinitionChange(dad);
}
/**
*
* @param da
* @param name
* @param arrEventNames
* @param strPeriod
*/
private void checkDispositionAction(DispositionAction da, String name, String[] arrEventNames, String strPeriod)
{
assertNotNull(da);
assertEquals(name, da.getName());
List<EventCompletionDetails> events = da.getEventCompletionDetails();
assertNotNull(events);
assertEquals(arrEventNames.length, events.size());
List<String> origEvents = new ArrayList<String>(events.size());
for (EventCompletionDetails event : events)
{
origEvents.add(event.getEventName());
}
List<String> expectedEvents = Arrays.asList(arrEventNames);
Collection<String> copy = new ArrayList<String>(origEvents);
for (Iterator<String> i = origEvents.iterator(); i.hasNext(); )
{
String origEvent = i.next();
if (expectedEvents.contains(origEvent) == true)
{
i.remove();
copy.remove(origEvent);
}
}
if (copy.size() != 0 && expectedEvents.size() != 0)
{
StringBuffer buff = new StringBuffer(255);
if (copy.size() != 0)
{
buff.append("The following events where found, but not expected: (");
for (String eventName : copy)
{
buff.append(eventName).append(", ");
}
buff.append("). ");
}
if (expectedEvents.size() != 0)
{
buff.append("The following events where not found, but expected: (");
for (String eventName : expectedEvents)
{
buff.append(eventName).append(", ");
}
buff.append(").");
}
fail(buff.toString());
}
if (PERIOD_NONE.equals(strPeriod) == true)
{
assertNull(da.getAsOfDate());
}
else
{
assertNotNull(da.getAsOfDate());
}
}
// TODO boolean isNextDispositionActionEligible(NodeRef nodeRef);
// TODO DispositionAction getNextDispositionAction(NodeRef nodeRef);
// TODO List<DispositionAction> getCompletedDispositionActions(NodeRef nodeRef);
// TODO DispositionAction getLastCompletedDispostionAction(NodeRef nodeRef);
// TODO List<QName> getDispositionPeriodProperties();
}

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,290 @@
/*
* 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("Cutoff", cutoff.getLabel());
assertEquals("Cutoff", cutoff.getDescription());
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,952 @@
/*
* 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.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)
{
adminService.removeCustomPropertyDefinition(createdCustomProperty);
}
for (QName customisable : madeCustomisable)
{
adminService.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 = adminService.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(adminService.isCustomisable(TYPE_CONTENT));
assertFalse(adminService.isCustomisable(ASPECT_DUBLINCORE));
assertTrue(adminService.isCustomisable(TYPE_RECORD_FOLDER));
assertTrue(adminService.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(adminService.existsCustomProperty(QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, "myRecordProp1")));
return adminService.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(adminService.existsCustomProperty(result));
// Check that property is available as a custom property
Map<QName, PropertyDefinition> propDefs = adminService.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());
assertEquals("Label1", propDef.getTitle());
}
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 adminService.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(adminService.existsCustomProperty(result));
// Check that property is available as a custom property
Map<QName, PropertyDefinition> propDefs = adminService.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());
assertEquals("Label2", propDef.getTitle());
}
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 adminService.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(adminService.existsCustomProperty(result));
// Check that property is available as a custom property
Map<QName, PropertyDefinition> propDefs = adminService.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());
assertEquals("Label3", propDef.getTitle());
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"
)
{
@Override
public void run()
{
adminService.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"
)
{
@Override
public void run()
{
adminService.addCustomPropertyDefinition(
QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, "myContentProp"),
TYPE_CONTENT,
"Label1",
DataTypeDefinition.TEXT,
"Title",
"Description");
}
});
// Failure: Add a property with the label twice (but no id specified)
// doTestInTransaction(new FailureTest
// (
// "Can not create a property with the same label twice if no id is specified."
// )
// {
// @Override
// public void run()
// {
// adminService.addCustomPropertyDefinition(
// null,
// ASPECT_RECORD,
// "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(adminService.isCustomisable(TYPE_CUSTOM_TYPE));
adminService.makeCustomisable(TYPE_CUSTOM_TYPE);
madeCustomisable.add(TYPE_CUSTOM_TYPE);
assertTrue(adminService.isCustomisable(TYPE_CUSTOM_TYPE));
// Add a custom property
return adminService.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(adminService.existsCustomProperty(result));
// Check that property is available as a custom property
Map<QName, PropertyDefinition> propDefs = adminService.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());
assertEquals("Label", propDef.getTitle());
}
});
doTestInTransaction(new Test<QName>()
{
@Override
public QName run() throws Exception
{
// Make an aspect customisable
assertFalse(adminService.isCustomisable(ASPECT_CUSTOM_ASPECT));
adminService.makeCustomisable(ASPECT_CUSTOM_ASPECT);
madeCustomisable.add(ASPECT_CUSTOM_ASPECT);
assertTrue(adminService.isCustomisable(ASPECT_CUSTOM_ASPECT));
// Add a custom property
return adminService.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(adminService.existsCustomProperty(result));
// Check that property is available as a custom property
Map<QName, PropertyDefinition> propDefs = adminService.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());
assertEquals("Label", propDef.getTitle());
}
});
}
public void testUseCustomProperty() throws Exception
{
// Create custom property on type and aspect
doTestInTransaction(new Test<QName>()
{
@Override
public QName run() throws Exception
{
adminService.makeCustomisable(TYPE_CUSTOM_TYPE);
madeCustomisable.add(TYPE_CUSTOM_TYPE);
adminService.addCustomPropertyDefinition(
QName.createQName(RecordsManagementCustomModel.RM_CUSTOM_URI, "myNewProperty"),
TYPE_CUSTOM_TYPE,
"Label",
DataTypeDefinition.TEXT,
"Title",
"Description");
adminService.makeCustomisable(ASPECT_CUSTOM_ASPECT);
madeCustomisable.add(ASPECT_CUSTOM_ASPECT);
adminService.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;
}
});
}
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 = createRecord(rmFolder, "testRecordA" + System.currentTimeMillis());
return result;
}
});
final NodeRef testRecord2 = retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
NodeRef result = createRecord(rmFolder, "testRecordB" + System.currentTimeMillis());
return result;
}
});
final QName generatedQName = retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<QName>()
{
public QName execute() throws Throwable
{
declareRecord(testRecord1);
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 = adminService.addCustomAssocDefinition(label);
}
else
{
// A parent/child reference
qNameResult = adminService.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 = adminService.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 = adminService.getCustomPropertyDefinitions();
for (QName prop : props.keySet())
{
System.out.println(" - " + prop.toString());
String propId = props.get(prop).getTitle();
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 = adminService.getCustomReferenceDefinitions();
for (QName reference : references.keySet())
{
System.out.println(" - " + reference.toString());
System.out.println(" " + references.get(reference).getTitle());
}
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 = adminService.getCustomConstraintDefinitions(RecordsManagementCustomModel.RM_CUSTOM_MODEL);
for (ConstraintDefinition constraint : constraints)
{
System.out.println(" - " + constraint.getName());
System.out.println(" " + constraint.getTitle());
}
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 = createRecord(rmFolder, "testRecordA" + System.currentTimeMillis());
NodeRef rec2 = 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
{
declareRecord(testRecord1);
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);
adminService.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 = adminService.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);
adminService.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 = adminService.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());
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");
adminService.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 = adminService.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());
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 = adminService.addCustomPropertyDefinition(null, ASPECT_RECORD, propLocalName, dataType, propTitle, description, defaultValue, multiValued, mandatory, isProtected, testCon);
createdCustomProperties.add(propName);
return null;
}
});
}
}

View File

@@ -0,0 +1,427 @@
/*
* 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.Map;
import junit.framework.TestCase;
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.test.util.TestUtilities;
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.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.ApplicationContextHelper;
import org.alfresco.util.EqualsHelper;
import org.springframework.context.ApplicationContext;
/**
* @see RecordsManagementAuditService
*
* @author Derek Hulley
* @since 3.2
*/
public class RecordsManagementAuditServiceImplTest extends TestCase
{
private ApplicationContext ctx;
private ServiceRegistry serviceRegistry;
private NodeService nodeService;
private TransactionService transactionService;
private RetryingTransactionHelper txnHelper;
private RecordsManagementAuditService rmAuditService;
private Date testStartTime;
private NodeRef filePlan;
@Override
protected void setUp() throws Exception
{
testStartTime = new Date();
// We require that records management auditing is enabled
// This gets done by the AMP, but as we're not running from
// and AMP, we need to do it ourselves!
System.setProperty("audit.rm.enabled", "true");
// Now we can fetch the context
ctx = ApplicationContextHelper.getApplicationContext();
this.serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
this.transactionService = serviceRegistry.getTransactionService();
this.txnHelper = transactionService.getRetryingTransactionHelper();
this.rmAuditService = (RecordsManagementAuditService) ctx.getBean("RecordsManagementAuditService");
this.nodeService = serviceRegistry.getNodeService();
// Set the current security context as admin
AuthenticationUtil.setRunAsUser(AuthenticationUtil.getSystemUserName());
// Stop and clear the log
rmAuditService.stop();
rmAuditService.clear();
rmAuditService.start();
RetryingTransactionCallback<Void> setUpCallback = new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
if (filePlan == null)
{
filePlan = TestUtilities.loadFilePlanData(ctx);
}
updateFilePlan();
return null;
}
};
txnHelper.doInTransaction(setUpCallback);
}
@Override
protected void tearDown()
{
AuthenticationUtil.clearCurrentSecurityContext();
try
{
rmAuditService.start();
}
catch (Throwable e)
{
// Not too important
}
}
/**
* Perform a full query audit for RM
* @return Returns all the results
*/
private List<RecordsManagementAuditEntry> queryAll()
{
RetryingTransactionCallback<List<RecordsManagementAuditEntry>> testCallback =
new RetryingTransactionCallback<List<RecordsManagementAuditEntry>>()
{
public List<RecordsManagementAuditEntry> execute() throws Throwable
{
RecordsManagementAuditQueryParameters params = new RecordsManagementAuditQueryParameters();
List<RecordsManagementAuditEntry> entries = rmAuditService.getAuditTrail(params);
return entries;
}
};
return txnHelper.doInTransaction(testCallback);
}
/**
* Create a new fileplan
*/
private void updateFilePlan()
{
RetryingTransactionCallback<Void> updateCallback = new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
// Do some stuff
nodeService.setProperty(filePlan, ContentModel.PROP_TITLE, "File Plan - " + System.currentTimeMillis());
return null;
}
};
txnHelper.doInTransaction(updateCallback);
}
public void testSetUp()
{
// Just to get get the fileplan set up
}
public void testQuery_All()
{
queryAll();
}
public void testQuery_UserLimited()
{
// Make sure that something has been done
updateFilePlan();
final int limit = 1;
final String user = AuthenticationUtil.getSystemUserName(); // The user being tested
RetryingTransactionCallback<List<RecordsManagementAuditEntry>> testCallback =
new RetryingTransactionCallback<List<RecordsManagementAuditEntry>>()
{
public List<RecordsManagementAuditEntry> execute() throws Throwable
{
RecordsManagementAuditQueryParameters params = new RecordsManagementAuditQueryParameters();
params.setUser(user);
params.setMaxEntries(limit);
List<RecordsManagementAuditEntry> entries = rmAuditService.getAuditTrail(params);
return entries;
}
};
List<RecordsManagementAuditEntry> entries = txnHelper.doInTransaction(testCallback);
assertNotNull(entries);
assertEquals("Expected results to be limited", limit, entries.size());
}
public void testQuery_Node() throws InterruptedException
{
RetryingTransactionCallback<List<RecordsManagementAuditEntry>> allResultsCallback =
new RetryingTransactionCallback<List<RecordsManagementAuditEntry>>()
{
public List<RecordsManagementAuditEntry> execute() throws Throwable
{
RecordsManagementAuditQueryParameters params = new RecordsManagementAuditQueryParameters();
params.setDateFrom(testStartTime);
List<RecordsManagementAuditEntry> entries = rmAuditService.getAuditTrail(params);
return entries;
}
};
List<RecordsManagementAuditEntry> entries = txnHelper.doInTransaction(allResultsCallback);
assertNotNull("Expect a list of results for the query", entries);
// Find all results for a given node
NodeRef chosenNodeRef = null;
int count = 0;
for (RecordsManagementAuditEntry entry : entries)
{
NodeRef nodeRef = entry.getNodeRef();
assertNotNull("Found entry with null nodeRef: " + entry, nodeRef);
if (chosenNodeRef == null)
{
chosenNodeRef = nodeRef;
count++;
}
else if (nodeRef.equals(chosenNodeRef))
{
count++;
}
}
final NodeRef chosenNodeRefFinal = chosenNodeRef;
// Now search again, but for the chosen node
RetryingTransactionCallback<List<RecordsManagementAuditEntry>> nodeResultsCallback =
new RetryingTransactionCallback<List<RecordsManagementAuditEntry>>()
{
public List<RecordsManagementAuditEntry> execute() throws Throwable
{
RecordsManagementAuditQueryParameters params = new RecordsManagementAuditQueryParameters();
params.setDateFrom(testStartTime);
params.setNodeRef(chosenNodeRefFinal);
List<RecordsManagementAuditEntry> entries = rmAuditService.getAuditTrail(params);
return entries;
}
};
entries = txnHelper.doInTransaction(nodeResultsCallback);
assertNotNull("Expect a list of results for the query", entries);
assertTrue("No results were found for node: " + chosenNodeRefFinal, entries.size() > 0);
// We can't check the size because we need entries for the node and any children as well
Thread.sleep(5000);
// Clear the log
rmAuditService.clear();
entries = txnHelper.doInTransaction(nodeResultsCallback);
assertTrue("Should have cleared all audit entries", entries.isEmpty());
// Delete the node
txnHelper.doInTransaction(new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
return AuthenticationUtil.runAs(new RunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
nodeService.deleteNode(chosenNodeRefFinal);
return null;
}
}, AuthenticationUtil.getSystemUserName());
}
});
Thread.sleep(5000);
entries = txnHelper.doInTransaction(nodeResultsCallback);
assertFalse("Should have recorded node deletion", entries.isEmpty());
}
public void testStartStopDelete() throws InterruptedException
{
// Stop the audit
rmAuditService.stop();
Thread.sleep(5000);
List<RecordsManagementAuditEntry> result1 = queryAll();
assertNotNull(result1);
// Update the fileplan
updateFilePlan();
Thread.sleep(5000);
// There should be no new audit entries
List<RecordsManagementAuditEntry> result2 = queryAll();
assertNotNull(result2);
assertEquals(
"Audit results should not have changed after auditing was disabled",
result1.size(), result2.size());
// repeat with a start
rmAuditService.start();
updateFilePlan();
Thread.sleep(5000);
List<RecordsManagementAuditEntry> result3 = queryAll();
assertNotNull(result3);
assertTrue(
"Expected more results after enabling audit",
result3.size() > result1.size());
Thread.sleep(5000);
// Stop and delete all entries
rmAuditService.stop();
rmAuditService.clear();
// There should be no entries
List<RecordsManagementAuditEntry> result4 = queryAll();
assertNotNull(result4);
assertEquals(
"Audit entries should have been cleared",
0, result4.size());
}
public void xtestAuditAuthentication()
{
rmAuditService.stop();
rmAuditService.clear();
rmAuditService.start();
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.stop();
List<RecordsManagementAuditEntry> result1 = queryAll();
// 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.clear();
rmAuditService.start();
try
{
AuthenticationUtil.pushAuthentication();
authenticationService.authenticate("cdickons", getName().toCharArray());
}
finally
{
AuthenticationUtil.popAuthentication();
}
rmAuditService.stop();
List<RecordsManagementAuditEntry> result2 = queryAll();
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);
}
}

View File

@@ -0,0 +1,139 @@
/*
* 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.RecordsManagementEventService;
import org.alfresco.module.org_alfresco_module_rm.event.RecordsManagementEventType;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.util.BaseSpringTest;
/**
* Event service implementation unit test
*
* @author Roy Wetherall
*/
public class RecordsManagementEventServiceImplTest extends BaseSpringTest implements RecordsManagementModel
{
protected static StoreRef SPACES_STORE = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
private RecordsManagementEventService rmEventService;
private RetryingTransactionHelper transactionHelper;
@Override
protected void onSetUpInTransaction() throws Exception
{
super.onSetUpInTransaction();
// Get the service required in the tests
this.rmEventService = (RecordsManagementEventService)this.applicationContext.getBean("RecordsManagementEventService");
this.transactionHelper = (RetryingTransactionHelper)this.applicationContext.getBean("retryingTransactionHelper");
// Set the current security context as admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
}
public void testGetEventTypes()
{
setComplete();
endTransaction();
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()
{
setComplete();
endTransaction();
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()
{
setComplete();
endTransaction();
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,311 @@
/*
* 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.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.util.TestWithUserUtils;
/**
* Search service implementation unit test.
*
* @author Roy Wetherall
*/
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 MutableAuthenticationService authenticationService;
private int numberOfReports;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase#setupTestData()
*/
@Override
protected void setupTestData()
{
super.setupTestData();
authenticationService = (MutableAuthenticationService)applicationContext.getBean("AuthenticationService");
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(SITE_ID);
assertNotNull(searches);
numberOfReports = searches.size();
return null;
}
});
}
/**
* @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 = createRecord(folderLevelRecordFolder, "recordOne.txt", null, "record one - folder level - elephant");
recordTwo = createRecord(folderLevelRecordFolder, "recordTwo.txt", null, "record two - folder level - snake");
recordThree = createRecord(folderLevelRecordFolder, "recordThree.txt", null, "record three - folder level - monkey");
recordFour = createRecord(recordLevelRecordFolder, "recordFour.txt", null, "record four - record level - elephant");
recordFive = createRecord(recordLevelRecordFolder, "recordFive.txt", null, "record five - record level - snake");
recordSix = createRecord(recordLevelRecordFolder, "recordSix.txt", null, "record six - record level - monkey");
return null;
}
});
}
@Override
protected void tearDown() throws Exception
{
super.tearDown();
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;
}
});
}
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(SITE_ID, query, params);
assertNotNull(results);
assertEquals(2, results.size());
return null;
}
});
// Property search
//
}
public void testSaveSearch()
{
// Add some saved searches (as admin user)
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
SavedSearchDetails details1 = rmSearchService.saveSearch(SITE_ID, SEARCH1, "description1", "query1", new RecordsManagementSearchParameters(), true);
checkSearchDetails(details1, "mySite", "search1", "description1", "query1", new RecordsManagementSearchParameters(), true);
SavedSearchDetails details2 = rmSearchService.saveSearch(SITE_ID, SEARCH2, "description2", "query2", new RecordsManagementSearchParameters(), false);
checkSearchDetails(details2, "mySite", "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(SITE_ID, SEARCH3, "description3", "query3", new RecordsManagementSearchParameters(), false);
checkSearchDetails(details1, "mySite", SEARCH3, "description3", "query3", new RecordsManagementSearchParameters(), false);
SavedSearchDetails details2 = rmSearchService.saveSearch(SITE_ID, SEARCH4, "description4", "query4", new RecordsManagementSearchParameters(), false);
checkSearchDetails(details2, "mySite", 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(SITE_ID);
assertNotNull(searches);
assertEquals(numberOfReports + 2, searches.size());
SavedSearchDetails search1 = rmSearchService.getSavedSearch(SITE_ID, SEARCH1);
assertNotNull(search1);
checkSearchDetails(search1, "mySite", "search1", "description1", "query1", new RecordsManagementSearchParameters(), true);
SavedSearchDetails search2 = rmSearchService.getSavedSearch(SITE_ID, SEARCH2);
assertNotNull(search2);
checkSearchDetails(search2, "mySite", "search2", "description2", "query2", new RecordsManagementSearchParameters(), false);
SavedSearchDetails search3 = rmSearchService.getSavedSearch(SITE_ID, SEARCH3);
assertNull(search3);
SavedSearchDetails search4 = rmSearchService.getSavedSearch(SITE_ID, SEARCH4);
assertNull(search4);
return null;
}
});
// Get searches (as user1)
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
List<SavedSearchDetails> searches = rmSearchService.getSavedSearches(SITE_ID);
assertNotNull(searches);
assertEquals(numberOfReports + 3, searches.size());
SavedSearchDetails search1 = rmSearchService.getSavedSearch(SITE_ID, SEARCH1);
assertNotNull(search1);
checkSearchDetails(search1, "mySite", "search1", "description1", "query1", new RecordsManagementSearchParameters(), true);
SavedSearchDetails search2 = rmSearchService.getSavedSearch(SITE_ID, SEARCH2);
assertNull(search2);
SavedSearchDetails search3 = rmSearchService.getSavedSearch(SITE_ID, SEARCH3);
assertNotNull(search3);
checkSearchDetails(search3, "mySite", SEARCH3, "description3", "query3", new RecordsManagementSearchParameters(), false);
SavedSearchDetails search4 = rmSearchService.getSavedSearch(SITE_ID, SEARCH4);
assertNotNull(search4);
checkSearchDetails(search4, "mySite", "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(SITE_ID, SEARCH1);
assertNotNull(search1);
checkSearchDetails(search1, SITE_ID, SEARCH1, "description1", "query1", new RecordsManagementSearchParameters(), true);
rmSearchService.saveSearch(SITE_ID, SEARCH1, "change", "change", new RecordsManagementSearchParameters(), true);
search1 = rmSearchService.getSavedSearch(SITE_ID, SEARCH1);
assertNotNull(search1);
checkSearchDetails(search1, SITE_ID, 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,692 @@
/*
* 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.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.capability.Capability;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.security.RecordsManagementSecurityService;
import org.alfresco.module.org_alfresco_module_rm.security.Role;
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.repository.ChildAssociationRef;
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.AccessPermission;
import org.alfresco.service.cmr.security.AccessStatus;
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.PermissionService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.BaseSpringTest;
import org.alfresco.util.GUID;
import org.alfresco.util.PropertyMap;
/**
* Event service implementation unit test
*
* @author Roy Wetherall
*/
public class RecordsManagementSecurityServiceImplTest extends BaseSpringTest
implements RecordsManagementModel
{
protected static StoreRef SPACES_STORE = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
private NodeService nodeService;
private MutableAuthenticationService authenticationService;
private AuthorityService authorityService;
private PermissionService permissionService;
private PersonService personService;
private RecordsManagementSecurityService rmSecurityService;
private RecordsManagementActionService rmActionService;
private RetryingTransactionHelper transactionHelper;
@Override
protected void onSetUpInTransaction() throws Exception
{
super.onSetUpInTransaction();
// Get the service required in the tests
this.nodeService = (NodeService)this.applicationContext.getBean("NodeService");
this.authenticationService = (MutableAuthenticationService)this.applicationContext.getBean("AuthenticationService");
this.personService = (PersonService)this.applicationContext.getBean("PersonService");
this.authorityService = (AuthorityService)this.applicationContext.getBean("authorityService");
this.rmSecurityService = (RecordsManagementSecurityService)this.applicationContext.getBean("RecordsManagementSecurityService");
this.transactionHelper = (RetryingTransactionHelper)this.applicationContext.getBean("retryingTransactionHelper");
this.permissionService = (PermissionService)this.applicationContext.getBean("PermissionService");
this.rmActionService = (RecordsManagementActionService)this.applicationContext.getBean("RecordsManagementActionService");
// Set the current security context as admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
}
public void testRoles()
{
final NodeRef rmRootNode = createRMRootNodeRef();
setComplete();
endTransaction();
transactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
public Object execute() throws Throwable
{
Set<Role> roles = rmSecurityService.getRoles(rmRootNode);
assertNotNull(roles);
assertEquals(5, roles.size());
rmSecurityService.createRole(rmRootNode, "MyRole", "My Role", getListOfCapabilities(5));
roles = rmSecurityService.getRoles(rmRootNode);
assertNotNull(roles);
assertEquals(6, roles.size());
Role role = findRole(roles, "MyRole");
assertNotNull(role);
assertEquals("MyRole", role.getName());
assertEquals("My Role", role.getDisplayLabel());
assertNotNull(role.getCapabilities());
assertEquals(5, role.getCapabilities().size());
assertNotNull(role.getRoleGroupName());
// Add a user to the role
String userName = createAndAddUserToRole(role.getRoleGroupName());
// Check that we can retrieve the users roles
Set<Role> userRoles = rmSecurityService.getRolesByUser(rmRootNode, userName);
assertNotNull(userRoles);
assertEquals(1, userRoles.size());
Role userRole = userRoles.iterator().next();
assertEquals("MyRole", userRole.getName());
try
{
rmSecurityService.createRole(rmRootNode, "MyRole", "My Role", getListOfCapabilities(5));
fail("Duplicate role id's not allowed for the same rm root node");
}
catch (AlfrescoRuntimeException e)
{
// Expected
}
rmSecurityService.createRole(rmRootNode, "MyRole2", "My Role", getListOfCapabilities(5));
roles = rmSecurityService.getRoles(rmRootNode);
assertNotNull(roles);
assertEquals(7, roles.size());
Set<Capability> list = getListOfCapabilities(3, 4);
assertEquals(3, list.size());
Role result = rmSecurityService.updateRole(rmRootNode, "MyRole", "SomethingDifferent", list);
assertNotNull(result);
assertEquals("MyRole", result.getName());
assertEquals("SomethingDifferent", result.getDisplayLabel());
assertNotNull(result.getCapabilities());
assertEquals(3, result.getCapabilities().size());
assertNotNull(result.getRoleGroupName());
roles = rmSecurityService.getRoles(rmRootNode);
assertNotNull(roles);
assertEquals(7, roles.size());
Role role2 = findRole(roles, "MyRole");
assertNotNull(role2);
assertEquals("MyRole", role2.getName());
assertEquals("SomethingDifferent", role2.getDisplayLabel());
assertNotNull(role2.getCapabilities());
assertEquals(3, role2.getCapabilities().size());
assertNotNull(role2.getRoleGroupName());
rmSecurityService.deleteRole(rmRootNode, "MyRole2");
roles = rmSecurityService.getRoles(rmRootNode);
assertNotNull(roles);
assertEquals(6, roles.size());
return null;
}
});
}
private Role findRole(Set<Role> roles, String name)
{
Role result = null;
for (Role role : roles)
{
if (name.equals(role.getName()) == true)
{
result = role;
break;
}
}
return result;
}
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 = rmSecurityService.getCapabilities();
int count = 0;
for (Capability cap : caps)
{
if (count < size+offset)
{
if (count >= offset)
{
result.add(cap);
}
}
else
{
break;
}
count ++;
}
return result;
}
private NodeRef createRMRootNodeRef()
{
NodeRef root = this.nodeService.getRootNode(SPACES_STORE);
NodeRef filePlan = this.nodeService.createNode(root, ContentModel.ASSOC_CHILDREN, ContentModel.ASSOC_CHILDREN, TYPE_FILE_PLAN).getChildRef();
return filePlan;
}
private NodeRef addFilePlanCompoent(NodeRef parent, QName type)
{
String id = GUID.generate();
String seriesName = "Series" + id;
Map<QName, Serializable> props = new HashMap<QName, Serializable>(2);
props.put(ContentModel.PROP_NAME, seriesName);
props.put(PROP_IDENTIFIER, id);
return nodeService.createNode(
parent,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, seriesName),
type,
props).getChildRef();
}
private String createAndAddUserToRole(String role)
{
// Create an athentication
String userName = GUID.generate();
authenticationService.createAuthentication(userName, "PWD".toCharArray());
// Create a person
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);
// Assign the new user to the role passed
authorityService.addAuthority(role, userName);
return userName;
}
private String createUser()
{
// Create an athentication
String userName = GUID.generate();
authenticationService.createAuthentication(userName, "PWD".toCharArray());
// Create a person
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);
return userName;
}
public void testExecutionAsRMAdmin()
{
final NodeRef filePlan = createRMRootNodeRef();
setComplete();
endTransaction();
transactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
public Object execute() throws Throwable
{
System.out.println("Groups:");
Set<String> temp = authorityService.getAllRootAuthorities(AuthorityType.GROUP);
for (String g : temp)
{
System.out.println(" - " + g);
}
System.out.println("");
assertTrue(permissionService.hasPermission(filePlan, RMPermissionModel.READ_RECORDS).equals(AccessStatus.ALLOWED));
assertTrue(permissionService.hasPermission(filePlan, RMPermissionModel.FILE_RECORDS).equals(AccessStatus.ALLOWED));
assertTrue(permissionService.hasPermission(filePlan, RMPermissionModel.FILING).equals(AccessStatus.ALLOWED));
Role adminRole = rmSecurityService.getRole(filePlan, "Administrator");
assertNotNull(adminRole);
String adminUser = createAndAddUserToRole(adminRole.getRoleGroupName());
AuthenticationUtil.setFullyAuthenticatedUser(adminUser);
try
{
assertTrue(permissionService.hasPermission(filePlan, RMPermissionModel.READ_RECORDS).equals(AccessStatus.ALLOWED));
assertTrue(permissionService.hasPermission(filePlan, RMPermissionModel.FILE_RECORDS).equals(AccessStatus.ALLOWED));
assertTrue(permissionService.hasPermission(filePlan, RMPermissionModel.FILING).equals(AccessStatus.ALLOWED));
// Read the properties of the filePlan
nodeService.getProperties(filePlan);
}
finally
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
}
return null;
}
});
}
public void testDefaultRolesBootstrap()
{
NodeRef rootNode = nodeService.getRootNode(SPACES_STORE);
final NodeRef filePlan = nodeService.createNode(rootNode, ContentModel.ASSOC_CHILDREN,
TYPE_FILE_PLAN,
TYPE_FILE_PLAN).getChildRef();
setComplete();
endTransaction();
transactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
public Object execute() throws Throwable
{
Set<Role> roles = rmSecurityService.getRoles(filePlan);
assertNotNull(roles);
assertEquals(5, roles.size());
Role role = rmSecurityService.getRole(filePlan, "User");
assertNotNull(role);
assertEquals("User", role.getName());
assertNotNull(role.getDisplayLabel());
Set<String> caps = role.getCapabilities();
assertNotNull(caps);
System.out.println("\nUser capabilities: ");
for (String cap : caps)
{
assertNotNull(rmSecurityService.getCapability(cap));
System.out.println(cap);
}
role = rmSecurityService.getRole(filePlan, "PowerUser");
assertNotNull(role);
assertEquals("PowerUser", role.getName());
assertNotNull(role.getDisplayLabel());
caps = role.getCapabilities();
assertNotNull(caps);
System.out.println("\nPowerUser capabilities: ");
for (String cap : caps)
{
assertNotNull(rmSecurityService.getCapability(cap));
System.out.println(cap);
}
role = rmSecurityService.getRole(filePlan, "SecurityOfficer");
assertNotNull(role);
assertEquals("SecurityOfficer", role.getName());
assertNotNull(role.getDisplayLabel());
caps = role.getCapabilities();
assertNotNull(caps);
System.out.println("\nSecurityOfficer capabilities: ");
for (String cap : caps)
{
assertNotNull(rmSecurityService.getCapability(cap));
System.out.println(cap);
}
role = rmSecurityService.getRole(filePlan, "RecordsManager");
assertNotNull(role);
assertEquals("RecordsManager", role.getName());
assertNotNull(role.getDisplayLabel());
caps = role.getCapabilities();
assertNotNull(caps);
System.out.println("\nRecordsManager capabilities: ");
for (String cap : caps)
{
assertNotNull(rmSecurityService.getCapability(cap));
System.out.println(cap);
}
role = rmSecurityService.getRole(filePlan, "Administrator");
assertNotNull(role);
assertEquals("Administrator", role.getName());
assertNotNull(role.getDisplayLabel());
caps = role.getCapabilities();
assertNotNull(caps);
System.out.println("\nAdministrator capabilities: ");
for (String cap : caps)
{
assertNotNull("No capability called " + cap, rmSecurityService.getCapability(cap));
System.out.println(cap);
}
return null;
}
});
}
public void xtestCreateNewRMUserAccessToFilePlan()
{
final NodeRef rmRootNode = createRMRootNodeRef();
final NodeRef seriesOne = addFilePlanCompoent(rmRootNode, TYPE_RECORD_CATEGORY);
final NodeRef seriesTwo = addFilePlanCompoent(rmRootNode, TYPE_RECORD_CATEGORY);
final NodeRef seriesThree = addFilePlanCompoent(rmRootNode, TYPE_RECORD_CATEGORY);
final NodeRef catOne = addFilePlanCompoent(seriesOne, TYPE_RECORD_CATEGORY);
final NodeRef catTwo = addFilePlanCompoent(seriesOne, TYPE_RECORD_CATEGORY);
final NodeRef catThree = addFilePlanCompoent(seriesOne, TYPE_RECORD_CATEGORY);
final NodeRef folderOne = addFilePlanCompoent(catOne, TYPE_RECORD_FOLDER);
final NodeRef folderTwo = addFilePlanCompoent(catOne, TYPE_RECORD_FOLDER);
final NodeRef folderThree = addFilePlanCompoent(catOne, TYPE_RECORD_FOLDER);
setComplete();
endTransaction();
final String user = transactionHelper.doInTransaction(new RetryingTransactionCallback<String>()
{
public String execute() throws Throwable
{
// Create a new role
Set<Capability> caps = new HashSet<Capability>(1);
caps.add(rmSecurityService.getCapability(RMPermissionModel.VIEW_RECORDS));
Role role = rmSecurityService.createRole(rmRootNode, "TestRole", "My Test Role", caps);
String user = createUser();
// Check the role group and allRole group are set up correctly
Set<String> groups = authorityService.getContainingAuthorities(AuthorityType.GROUP, role.getRoleGroupName(), true);
assertNotNull(groups);
// expect allRole group and the capability group
assertEquals(1, groups.size());
List<String> tempList = new ArrayList<String>(groups);
assertTrue(tempList.get(0).startsWith("GROUP_AllRoles"));
// User shouldn't be able to see the file plan node
AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
{
public Object doWork() throws Exception
{
// Check the permissions of the group on the root node
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(rmRootNode, RMPermissionModel.READ_RECORDS));
try
{
nodeService.getChildAssocs(rmRootNode);
fail("The user shouldn't be able to read the children");
}
catch (AlfrescoRuntimeException e)
{
// expected
}
return null;
}
}, user);
// Assign the new user to the role
rmSecurityService.assignRoleToAuthority(rmRootNode, role.getName(), user);
return user;
}
});
transactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
public Object execute() throws Throwable
{
// Prove that all the series are there
List<ChildAssociationRef> assocs = nodeService.getChildAssocs(rmRootNode);
assertNotNull(assocs);
assertEquals(3, assocs.size());
// User should be able to see the file plan node
AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
{
public Object doWork() throws Exception
{
// Check user has read on the root
// assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(rmRootNode, RMPermissionModel.READ_RECORDS));
// Check that the user can not see any of the series
List<ChildAssociationRef> assocs = nodeService.getChildAssocs(rmRootNode);
assertNotNull(assocs);
assertEquals(0, assocs.size());
return null;
}
}, user);
// Add read permissions to one of the series
permissionService.setPermission(seriesOne, user, RMPermissionModel.READ_RECORDS, true);
// Show that user can now see that series
AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
{
public Object doWork() throws Exception
{
// Check that the user can not see any of the series
List<ChildAssociationRef> assocs = nodeService.getChildAssocs(rmRootNode);
assertNotNull(assocs);
assertEquals(1, assocs.size());
return null;
}
}, user);
// Add the read permission and file permission to get to the folder
permissionService.setPermission(catOne, user, RMPermissionModel.READ_RECORDS, true);
permissionService.setPermission(folderOne, user, RMPermissionModel.FILING, true);
// TODO check visibility of items as we add the permissions
// TODO check that records inherit the permissions ok
// Try and close the folder as the new user
AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
{
public Object doWork() throws Exception
{
try
{
rmActionService.executeRecordsManagementAction(folderOne, "closeRecordFolder");
fail("User does not have the capability for this");
}
catch (org.alfresco.repo.security.permissions.AccessDeniedException exception)
{
// expected
}
return null;
}
}, user);
// Add the capability to the role
Set<Capability> caps2 = new HashSet<Capability>(1);
caps2.add(rmSecurityService.getCapability(RMPermissionModel.VIEW_RECORDS));
caps2.add(rmSecurityService.getCapability(RMPermissionModel.CLOSE_FOLDERS));
rmSecurityService.updateRole(rmRootNode, "TestRole", "My Test Role", caps2);
Set<AccessPermission> aps = permissionService.getAllSetPermissions(rmRootNode);
System.out.println("\nPermissions on new series node: ");
for (AccessPermission ap : aps)
{
System.out.println(" - " + ap.getAuthority() + " has " + ap.getPermission());
}
// Try and close the folder as the new user
AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
{
public Object doWork() throws Exception
{
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(rmRootNode, RMPermissionModel.CLOSE_FOLDERS));
rmActionService.executeRecordsManagementAction(folderOne, "closeRecordFolder");
return null;
}
}, user);
return null;
}
});
}
public void testSetPermissions()
{
final NodeRef rmRootNode = createRMRootNodeRef();
final NodeRef seriesOne = addFilePlanCompoent(rmRootNode, TYPE_RECORD_CATEGORY);
final NodeRef seriesTwo = addFilePlanCompoent(rmRootNode, TYPE_RECORD_CATEGORY);
final NodeRef seriesThree = addFilePlanCompoent(rmRootNode, TYPE_RECORD_CATEGORY);
final NodeRef catOne = addFilePlanCompoent(seriesOne, TYPE_RECORD_CATEGORY);
final NodeRef catTwo = addFilePlanCompoent(seriesOne, TYPE_RECORD_CATEGORY);
final NodeRef catThree = addFilePlanCompoent(seriesOne, TYPE_RECORD_CATEGORY);
final NodeRef folderOne = addFilePlanCompoent(catOne, TYPE_RECORD_FOLDER);
final NodeRef folderTwo = addFilePlanCompoent(catOne, TYPE_RECORD_FOLDER);
final NodeRef folderThree = addFilePlanCompoent(catOne, TYPE_RECORD_FOLDER);
setComplete();
endTransaction();
transactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
{
public Object execute() throws Throwable
{
// Create a new role
Set<Capability> caps = new HashSet<Capability>(1);
caps.add(rmSecurityService.getCapability(RMPermissionModel.VIEW_RECORDS));
Role role = rmSecurityService.createRole(rmRootNode, "TestRole", "My Test Role", caps);
String user = createUser();
rmSecurityService.assignRoleToAuthority(rmRootNode, role.getName(), user);
AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
{
public Object doWork() throws Exception
{
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(rmRootNode, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(seriesOne, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(seriesTwo, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(seriesThree, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(catOne, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(catTwo, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(catThree, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(folderOne, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(folderTwo, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(folderThree, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(rmRootNode, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(seriesOne, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(seriesTwo, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(seriesThree, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(catOne, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(catTwo, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(catThree, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(folderOne, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(folderTwo, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(folderThree, RMPermissionModel.FILING));
return null;
}
}, user);
rmSecurityService.setPermission(catOne, user, RMPermissionModel.FILING);
AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
{
public Object doWork() throws Exception
{
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(rmRootNode, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(seriesOne, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(seriesTwo, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(seriesThree, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(catOne, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(catTwo, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(catThree, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(folderOne, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(folderTwo, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(folderThree, RMPermissionModel.READ_RECORDS));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(rmRootNode, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(seriesOne, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(seriesTwo, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(seriesThree, RMPermissionModel.FILING));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(catOne, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(catTwo, RMPermissionModel.FILING));
assertEquals(AccessStatus.DENIED, permissionService.hasPermission(catThree, RMPermissionModel.FILING));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(folderOne, RMPermissionModel.FILING));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(folderTwo, RMPermissionModel.FILING));
assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(folderThree, RMPermissionModel.FILING));
return null;
}
}, user);
return null;
}
});
}
}

View File

@@ -0,0 +1,670 @@
/*
* 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 java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.FilePlanComponentKind;
import org.alfresco.module.org_alfresco_module_rm.RecordsManagementService;
import org.alfresco.module.org_alfresco_module_rm.dod5015.DOD5015Model;
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;
import org.springframework.util.CollectionUtils;
/**
* Records management service test.
*
* @author Roy Wetherall
*/
public class RecordsManagementServiceImplTest extends BaseRMTestCase
{
/********** RM Component methods **********/
/**
* @see RecordsManagementService#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", rmService.isFilePlanComponent(filePlan));
assertTrue("The rm container should be a rm component", rmService.isFilePlanComponent(rmContainer));
assertTrue("The rm folder should be a rm component", rmService.isFilePlanComponent(rmFolder));
return null;
}
});
}
/**
* @see RecordsManagementService#getFilePlanComponentKind(NodeRef)
*/
public void testGetFilePlanComponentKind() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run() throws Exception
{
return createRecord(rmFolder, "testRecord.txt");
}
@Override
public void test(NodeRef result) throws Exception
{
assertEquals(FilePlanComponentKind.FILE_PLAN, rmService.getFilePlanComponentKind(filePlan));
assertEquals(FilePlanComponentKind.RECORD_CATEGORY, rmService.getFilePlanComponentKind(rmContainer));
assertEquals(FilePlanComponentKind.RECORD_FOLDER, rmService.getFilePlanComponentKind(rmFolder));
assertEquals(FilePlanComponentKind.RECORD, rmService.getFilePlanComponentKind(result));
// TODO HOLD and TRANSFER
assertNull(rmService.getFilePlanComponentKind(folder));
}
});
}
/**
* @see RecordsManagementService#isFilePlan(NodeRef)
*/
public void testIsFilePlan() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
assertTrue("This is a records management root", rmService.isFilePlan(filePlan));
assertFalse("This should not be a records management root", rmService.isFilePlan(rmContainer));
assertFalse("This should not be a records management root", rmService.isFilePlan(rmFolder));
return null;
}
});
}
/**
* @see RecordsManagementService#isRecordCategory(NodeRef)
*/
public void testIsRecordCategory() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
assertFalse("This should not be a record category.", rmService.isRecordCategory(filePlan));
assertTrue("This is a record category.", rmService.isRecordCategory(rmContainer));
assertFalse("This should not be a record category.", rmService.isRecordCategory(rmFolder));
return null;
}
});
}
/**
* @see RecordsManagementService#isRecordFolder(NodeRef)
*/
public void testIsRecordFolder() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
assertFalse("This should not be a record folder", rmService.isRecordFolder(filePlan));
assertFalse("This should not be a record folder", rmService.isRecordFolder(rmContainer));
assertTrue("This should be a record folder", rmService.isRecordFolder(rmFolder));
return null;
}
});
}
// TODO void testIsRecord()
// TODO void testIsHold()
// TODO void testIsTransfer()
// TODO void testGetNodeRefPath()
/**
* @see RecordsManagementService#getRecordsManagementRoot()
*/
public void testGetRecordsManagementRoot() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
assertEquals(filePlan, rmService.getFilePlan(filePlan));
assertEquals(filePlan, rmService.getFilePlan(rmContainer));
assertEquals(filePlan, rmService.getFilePlan(rmFolder));
return null;
}
});
}
/********** Record Management Root methods **********/
/**
* @see RecordsManagementService#getFilePlans()
*/
public void testGetRecordsManagementRoots() throws Exception
{
doTestInTransaction(new Test<NodeRef>()
{
@Override
public NodeRef run()
{
// List<NodeRef> roots = rmService.getRecordsManagementRoots(storeRef);
// assertNotNull(roots);
// assertTrue(roots.size() != 0);
// assertTrue(roots.contains(rmRootContainer));
//
// RecordsManagementServiceImpl temp = (RecordsManagementServiceImpl)applicationContext.getBean("recordsManagementService");
// temp.setDefaultStoreRef(storeRef);
List<NodeRef> roots = rmService.getFilePlans();
assertNotNull(roots);
assertTrue(roots.size() != 0);
assertTrue(roots.contains(filePlan));
return null;
}
});
}
/**
* @see RecordsManagementService#createFilePlan(org.alfresco.service.cmr.repository.NodeRef, String)
* @see RecordsManagementService#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 rmService.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 rmService.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()
{
rmService.createFilePlan(rmContainer, GUID.generate());
}
});
// Failure: type no extended from root container
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
rmService.createFilePlan(folder, GUID.generate(), TYPE_FOLDER);
}
});
}
/********** Records Management Container methods **********/
/**
* @see RecordsManagementService#createRecordCategory(NodeRef, String)
* @see RecordsManagementService#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 rmService.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 rmService.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()
{
rmService.createRecordCategory(folder, GUID.generate());
}
});
// Fail Test: type is not a sub-type of rm:recordsManagementContainer
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
rmService.createRecordCategory(filePlan, GUID.generate(), TYPE_FOLDER);
}
});
}
/**
* @see RecordsManagementService#getAllContained(NodeRef)
* @see RecordsManagementService#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 = rmService.createRecordCategory(rmContainer, "rmSeries");
NodeRef seriesChildFolder = rmService.createRecordFolder(series, "seriesRecordFolder");
NodeRef seriesChildContainer = rmService.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 = rmService.getAllContained(rmContainer);
assertNotNull(nodes);
assertEquals(2, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
assertTrue(nodes.contains(rmFolder));
nodes = rmService.getAllContained(rmContainer, false);
assertNotNull(nodes);
assertEquals(2, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
assertTrue(nodes.contains(rmFolder));
nodes = rmService.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()
{
rmService.getAllContained(rmFolder);
}
});
}
/**
* @see RecordsManagementService#getContainedRecordCategories(NodeRef)
* @see RecordsManagementService#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 = rmService.createRecordCategory(rmContainer, "rmSeries");
NodeRef seriesChildFolder = rmService.createRecordFolder(series, "seriesRecordFolder");
NodeRef seriesChildContainer = rmService.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 = rmService.getContainedRecordCategories(rmContainer);
assertNotNull(nodes);
assertEquals(1, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
nodes = rmService.getContainedRecordCategories(rmContainer, false);
assertNotNull(nodes);
assertEquals(1, nodes.size());
assertTrue(nodes.contains(getNodeRef("series")));
nodes = rmService.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()
{
rmService.getContainedRecordCategories(rmFolder);
}
});
}
/**
* @see RecordsManagementService#getContainedRecordFolders(NodeRef)
* @see RecordsManagementService#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 = rmService.createRecordCategory(rmContainer, "rmSeries");
NodeRef seriesChildFolder = rmService.createRecordFolder(series, "seriesRecordFolder");
NodeRef seriesChildContainer = rmService.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 = rmService.getContainedRecordFolders(rmContainer);
assertNotNull(nodes);
assertEquals(1, nodes.size());
assertTrue(nodes.contains(rmFolder));
nodes = rmService.getContainedRecordFolders(rmContainer, false);
assertNotNull(nodes);
assertEquals(1, nodes.size());
assertTrue(nodes.contains(rmFolder));
nodes = rmService.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()
{
rmService.getContainedRecordFolders(rmFolder);
}
});
}
/********** Record Folder methods **********/
// TODO void testIsRecordFolderDeclared()
// TODO void testIsRecordFolderClosed()
// TODO void testGetRecords()
/**
* @see RecordsManagementService#createRecordFolder(NodeRef, String)
* @see RecordsManagementService#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 rmService.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()
{
rmService.createRecordFolder(rmContainer, GUID.generate(), TYPE_FOLDER);
}
});
// Failure: Create record folder in root
doTestInTransaction(new FailureTest()
{
@Override
public void run()
{
rmService.createRecordFolder(filePlan, GUID.generate());
}
});
}
/********** Record methods **********/
// TODO void testIsRecordFrozen()
/**
* @see RecordsManagementService#getRecordMetaDataAspects()
*/
public void testGetRecordMetaDataAspects()
{
doTestInTransaction(new Test<Void>()
{
@Override
public Void run()
{
Set<QName> aspects = rmService.getRecordMetaDataAspects();
assertNotNull(aspects);
assertEquals(5, aspects.size());
assertTrue(aspects.containsAll(
CollectionUtils.arrayToList(new QName[]
{
DOD5015Model.ASPECT_DIGITAL_PHOTOGRAPH_RECORD,
DOD5015Model.ASPECT_PDF_RECORD,
DOD5015Model.ASPECT_WEB_RECORD,
DOD5015Model.ASPECT_SCANNED_RECORD,
ASPECT_RECORD_META_DATA
})));
return null;
}
});
}
// TODO void testGetRecordFolders(NodeRef record);
// TODO void testIsRecordDeclared(NodeRef nodeRef);
/********** 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", rmService.createRecordCategory(filePlan, "container1"));
assertNotNull("Unable to create container", levelOne);
NodeRef levelTwo = setNodeRef("container2", rmService.createRecordCategory(levelOne, "container2"));
assertNotNull("Unable to create container", levelTwo);
NodeRef levelThree = setNodeRef("container3", rmService.createRecordCategory(levelTwo, "container3"));
assertNotNull("Unable to create container", levelThree);
NodeRef levelThreeRecordFolder = setNodeRef("recordFolder3", rmService.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,381 @@
/*
* 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.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.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
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 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 = createRecord(mhRecordFolder41, "record51.txt");
mhRecord52 = createRecord(mhRecordFolder42, "record52.txt");
mhRecord53 = createRecord(mhRecordFolder43, "record53.txt");
mhRecord54 = createRecord(mhRecordFolder44, "record54.txt");
mhRecord55 = 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 rmService.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 rmService.createRecordFolder(mhContainer32, GUID.generate());
}
@Override
public void test(NodeRef result) throws Exception
{
assertHasVitalRecordDefinition(result, false, PERIOD_WEEK);
}
});
}
/**
* 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,78 @@
/*
* 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 org.alfresco.module.org_alfresco_module_rm.RecordsManagementService;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionService;
import org.alfresco.module.org_alfresco_module_rm.test.util.TestUtilities;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.cmr.view.ImporterService;
import org.alfresco.util.BaseSpringTest;
/**
*
*
* @author Roy Wetherall
*/
public class DODDataLoadSystemTest extends BaseSpringTest
{
private NodeService nodeService;
private AuthenticationComponent authenticationComponent;
private ImporterService importer;
private PermissionService permissionService;
private SearchService searchService;
private RecordsManagementService rmService;
private RecordsManagementActionService rmActionService;
@Override
protected void onSetUpInTransaction() throws Exception
{
super.onSetUpInTransaction();
// Get the service required in the tests
this.nodeService = (NodeService)this.applicationContext.getBean("NodeService");
this.authenticationComponent = (AuthenticationComponent)this.applicationContext.getBean("authenticationComponent");
this.importer = (ImporterService)this.applicationContext.getBean("ImporterService");
this.permissionService = (PermissionService)this.applicationContext.getBean("PermissionService");
searchService = (SearchService)applicationContext.getBean("SearchService");
rmService = (RecordsManagementService)applicationContext.getBean("RecordsManagementService");
rmActionService = (RecordsManagementActionService)applicationContext.getBean("RecordsManagementActionService");
// Set the current security context as admin
this.authenticationComponent.setCurrentUser(AuthenticationUtil.getSystemUserName());
}
public void testSetup()
{
// NOOP
}
public void testLoadFilePlanData()
{
TestUtilities.loadFilePlanData(applicationContext);
setComplete();
endTransaction();
}
}

View File

@@ -0,0 +1,158 @@
/*
* 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.security.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.AuthorityService;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
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;
private MutableAuthenticationService authenticationService;
private PersonService personService;
private AuthorityService authorityService;
/** 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");
authenticationService = (MutableAuthenticationService)applicationContext.getBean("AuthenticationService");
authorityService = (AuthorityService)applicationContext.getBean("AuthorityService");
personService = (PersonService)applicationContext.getBean("PersonService");
}
@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 = securityService.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 = createRecord(rmFolder, "recordOne");
NodeRef record2 = createRecord(rmFolder, "recordTwo");
NodeRef record3 = 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,253 @@
/*
* 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.List;
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.RecordsManagementService;
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.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 RecordsManagementService rmService;
private DispositionService dispositionService;
private TransactionService transactionService;
private NodeService nodeService;
private ContentService contentService;
private IdentifierService identifierService;
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");
rmService = (RecordsManagementService)appContext.getBean("recordsManagementService");
contentService = (ContentService)appContext.getBean("contentService");
identifierService = (IdentifierService)appContext.getBean("identifierService");
dispositionService = (DispositionService)appContext.getBean("dispositionService");
// 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
{
// Get the file plan node
List<NodeRef> roots = rmService.getFilePlans();
if (roots.size() != 1)
{
fail("There is more than one root to load the test data into.");
}
NodeRef filePlan = roots.get(0);
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,812 @@
/*
* 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.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.transaction.UserTransaction;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.RecordsManagementService;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionService;
import org.alfresco.module.org_alfresco_module_rm.action.impl.BroadcastDispositionActionDefinitionUpdateAction;
import org.alfresco.module.org_alfresco_module_rm.action.impl.FileAction;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionAction;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionActionDefinition;
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.RecordsManagementEvent;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.TestUtilities;
import org.alfresco.module.org_alfresco_module_rm.vital.VitalRecordDefinition;
import org.alfresco.module.org_alfresco_module_rm.vital.VitalRecordService;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
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.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.BaseSpringTest;
/**
* System test for records management service.
*
* Awaiting refactoring into records management test.
*
* @author Roy Wetherall
*/
public class RecordsManagementServiceImplSystemTest extends BaseSpringTest implements RecordsManagementModel
{
protected static StoreRef SPACES_STORE = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
private NodeRef filePlan;
private FileFolderService fileFolderService;
private NodeService nodeService;
private NodeService unprotectedNodeService;
private RecordsManagementActionService rmActionService;
private RecordsManagementService rmService;
private SearchService searchService;
private TransactionService transactionService;
private RetryingTransactionHelper transactionHelper;
private DispositionService dispositionService;
private VitalRecordService vitalRecordService;
@Override
protected void onSetUpInTransaction() throws Exception
{
super.onSetUpInTransaction();
// Get the service required in the tests
this.fileFolderService = (FileFolderService)this.applicationContext.getBean("FileFolderService");
this.nodeService = (NodeService)this.applicationContext.getBean("NodeService");
this.unprotectedNodeService = (NodeService)this.applicationContext.getBean("nodeService");
this.transactionService = (TransactionService)this.applicationContext.getBean("TransactionService");
this.searchService = (SearchService)this.applicationContext.getBean("searchService");
this.rmActionService = (RecordsManagementActionService)this.applicationContext.getBean("recordsManagementActionService");
this.rmService = (RecordsManagementService)this.applicationContext.getBean("recordsManagementService");
this.transactionHelper = (RetryingTransactionHelper)this.applicationContext.getBean("retryingTransactionHelper");
this.dispositionService = (DispositionService)this.applicationContext.getBean("dispositionService");
vitalRecordService = (VitalRecordService)applicationContext.getBean("VitalRecordService");
// Set the current security context as admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
// Get the test data
setUpTestData();
}
private void setUpTestData()
{
filePlan = TestUtilities.loadFilePlanData(applicationContext);
}
@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!");
}
}
public void testDispositionPresence() throws Exception
{
setComplete();
endTransaction();
// create a record category node in
final NodeRef nodeRef = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
NodeRef rootNode = nodeService.getRootNode(SPACES_STORE);
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
String recordCategoryName = "Test Record Category";
props.put(ContentModel.PROP_NAME, recordCategoryName);
NodeRef result = nodeService.createNode(rootNode, ContentModel.ASSOC_CHILDREN,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, QName.createValidLocalName(recordCategoryName)),
TYPE_RECORD_CATEGORY, props).getChildRef();
return result;
}
});
// ensure the record category node has the scheduled aspect and the disposition schedule association
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
assertTrue(nodeService.hasAspect(nodeRef, RecordsManagementModel.ASPECT_SCHEDULED));
List<ChildAssociationRef> scheduleAssocs = nodeService.getChildAssocs(nodeRef, ASSOC_DISPOSITION_SCHEDULE, RegexQNamePattern.MATCH_ALL);
assertNotNull(scheduleAssocs);
assertEquals(1, scheduleAssocs.size());
// test retrieval of the disposition schedule via RM service
DispositionSchedule schedule = dispositionService.getDispositionSchedule(nodeRef);
assertNotNull(schedule);
return null;
}
});
}
/**
* This test method contains a subset of the tests in TC 7-2 of the DoD doc.
* @throws Exception
*/
public void testRescheduleRecord_IsNotCutOff() throws Exception
{
final NodeRef recCat = TestUtilities.getRecordCategory(searchService, "Reports", "AIS Audit Records");
// This RC has disposition instructions "Cut off monthly, hold 1 month, then destroy."
setComplete();
endTransaction();
// Create a suitable folder for this test.
final NodeRef testFolder = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
Map<QName, Serializable> folderProps = new HashMap<QName, Serializable>(1);
String folderName = "testFolder" + System.currentTimeMillis();
folderProps.put(ContentModel.PROP_NAME, folderName);
NodeRef recordFolder = nodeService.createNode(recCat,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, folderName),
TYPE_RECORD_FOLDER).getChildRef();
return recordFolder;
}
});
// Create a record in the test folder. File it and declare it.
final NodeRef testRecord = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
final NodeRef result = nodeService.createNode(testFolder, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI,
"Record" + System.currentTimeMillis() + ".txt"),
ContentModel.TYPE_CONTENT).getChildRef();
rmActionService.executeRecordsManagementAction(result, "file");
TestUtilities.declareRecord(result, unprotectedNodeService, rmActionService);
return result;
}
});
assertTrue("recCat missing scheduled aspect", nodeService.hasAspect(recCat, RecordsManagementModel.ASPECT_SCHEDULED));
assertFalse("folder should not have scheduled aspect", nodeService.hasAspect(testFolder, RecordsManagementModel.ASPECT_SCHEDULED));
assertFalse("record should not have scheduled aspect", nodeService.hasAspect(testRecord, RecordsManagementModel.ASPECT_SCHEDULED));
assertFalse("recCat should not have dispositionLifecycle aspect", nodeService.hasAspect(recCat, RecordsManagementModel.ASPECT_DISPOSITION_LIFECYCLE));
assertTrue("testFolder missing dispositionLifecycle aspect", nodeService.hasAspect(testFolder, RecordsManagementModel.ASPECT_DISPOSITION_LIFECYCLE));
assertFalse("testRecord should not have dispositionLifecycle aspect", nodeService.hasAspect(testRecord, RecordsManagementModel.ASPECT_DISPOSITION_LIFECYCLE));
// Change the cutoff conditions for the associated record category
final Date dateBeforeChange = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Date>()
{
public Date execute() throws Throwable
{
Date asOfDate = dispositionService.getNextDispositionAction(testFolder).getAsOfDate();
System.out.println("Going to change the disposition asOf Date.");
System.out.println(" - Original value: " + asOfDate);
// Now change "Cut off monthly, hold 1 month, then destroy."
// to "Cut off yearly, hold 1 month, then destroy."
List<DispositionActionDefinition> dads = dispositionService.getDispositionSchedule(testFolder).getDispositionActionDefinitions();
DispositionActionDefinition firstDAD = dads.get(0);
assertEquals("cutoff", firstDAD.getName());
NodeRef dadNode = firstDAD.getNodeRef();
nodeService.setProperty(dadNode, PROP_DISPOSITION_PERIOD, new Period("year|1"));
List<QName> updatedProps = new ArrayList<QName>(1);
updatedProps.add(PROP_DISPOSITION_PERIOD);
refreshDispositionActionDefinition(dadNode, updatedProps);
return asOfDate;
}
});
// view the record metadata to verify that the record has been rescheduled.
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
DispositionAction nextDispositionAction = dispositionService.getNextDispositionAction(testFolder);
assertEquals("cutoff", nextDispositionAction.getName());
Date asOfDateAfterChange = nextDispositionAction.getAsOfDate();
System.out.println(" - Updated value: " + asOfDateAfterChange);
assertFalse("Expected disposition asOf date to change.", asOfDateAfterChange.equals(dateBeforeChange));
return null;
}
});
// Change the disposition type (e.g. time-based to event-based)
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
List<RecordsManagementEvent> rmes = dispositionService.getNextDispositionAction(testFolder).getDispositionActionDefinition().getEvents();
System.out.println("Going to change the RMEs.");
System.out.println(" - Original value: " + rmes);
List<DispositionActionDefinition> dads = dispositionService.getDispositionSchedule(testFolder).getDispositionActionDefinitions();
DispositionActionDefinition firstDAD = dads.get(0);
assertEquals("cutoff", firstDAD.getName());
NodeRef dadNode = firstDAD.getNodeRef();
// nodeService.setProperty(dadNode, PROP_DISPOSITION_PERIOD, null);
List<String> eventNames= new ArrayList<String>();
eventNames.add("study_complete");
nodeService.setProperty(dadNode, PROP_DISPOSITION_EVENT, (Serializable)eventNames);
return null;
}
});
// Now add a second event to the same
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
DispositionAction nextDispositionAction = dispositionService.getNextDispositionAction(testFolder);
StringBuilder buf = new StringBuilder();
for (RecordsManagementEvent e : nextDispositionAction.getDispositionActionDefinition().getEvents()) {
buf.append(e.getName()).append(',');
}
System.out.println("Going to change the RMEs again.");
System.out.println(" - Original value: " + buf.toString());
List<DispositionActionDefinition> dads = dispositionService.getDispositionSchedule(testFolder).getDispositionActionDefinitions();
DispositionActionDefinition firstDAD = dads.get(0);
assertEquals("cutoff", firstDAD.getName());
NodeRef dadNode = firstDAD.getNodeRef();
List<String> eventNames= new ArrayList<String>();
eventNames.add("study_complete");
eventNames.add("case_complete");
nodeService.setProperty(dadNode, PROP_DISPOSITION_EVENT, (Serializable)eventNames);
return null;
}
});
// View the record metadata to verify that the record has been rescheduled.
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
DispositionAction nextDispositionAction = dispositionService.getNextDispositionAction(testFolder);
assertEquals("cutoff", nextDispositionAction.getName());
StringBuilder buf = new StringBuilder();
for (RecordsManagementEvent e : nextDispositionAction.getDispositionActionDefinition().getEvents()) {
buf.append(e.getName()).append(',');
}
System.out.println(" - Updated value: " + buf.toString());
assertFalse("Disposition should not be eligible.", nextDispositionAction.isEventsEligible());
return null;
}
});
// Tidy up test nodes.
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
nodeService.deleteNode(testRecord);
// Change the disposition Period back to what it was.
List<DispositionActionDefinition> dads = dispositionService.getDispositionSchedule(testFolder).getDispositionActionDefinitions();
DispositionActionDefinition firstDAD = dads.get(0);
assertEquals("cutoff", firstDAD.getName());
NodeRef dadNode = firstDAD.getNodeRef();
nodeService.setProperty(dadNode, PROP_DISPOSITION_PERIOD, new Period("month|1"));
nodeService.deleteNode(testFolder);
return null;
}
});
}
private void refreshDispositionActionDefinition(NodeRef nodeRef, List<QName> updatedProps)
{
if (updatedProps != null)
{
Map<String, Serializable> params = new HashMap<String, Serializable>();
params.put(BroadcastDispositionActionDefinitionUpdateAction.CHANGED_PROPERTIES, (Serializable)updatedProps);
rmActionService.executeRecordsManagementAction(nodeRef, BroadcastDispositionActionDefinitionUpdateAction.NAME, params);
}
// Remove the unpublished update aspect
nodeService.removeAspect(nodeRef, ASPECT_UNPUBLISHED_UPDATE);
}
public void testGetDispositionInstructions() throws Exception
{
setComplete();
endTransaction();
// Get a record
// TODO
// Get a record folder
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
NodeRef folderRecord = TestUtilities.getRecordFolder(searchService, "Reports", "AIS Audit Records", "January AIS Audit Records");
assertNotNull(folderRecord);
assertEquals("January AIS Audit Records", nodeService.getProperty(folderRecord, ContentModel.PROP_NAME));
assertFalse(rmService.isRecord(folderRecord));
assertTrue(rmService.isRecordFolder(folderRecord));
assertFalse(rmService.isRecordCategory(folderRecord));
DispositionSchedule di = dispositionService.getDispositionSchedule(folderRecord);
assertNotNull(di);
assertEquals("N1-218-00-4 item 023", di.getDispositionAuthority());
assertEquals("Cut off monthly, hold 1 month, then destroy.", di.getDispositionInstructions());
assertFalse(di.isRecordLevelDisposition());
// Get a record category
NodeRef recordCategory = TestUtilities.getRecordCategory(searchService, "Reports", "AIS Audit Records");
assertNotNull(recordCategory);
assertEquals("AIS Audit Records", nodeService.getProperty(recordCategory, ContentModel.PROP_NAME));
assertFalse(rmService.isRecord(recordCategory));
assertFalse(rmService.isRecordFolder(recordCategory));
assertTrue(rmService.isRecordCategory(recordCategory));
di = dispositionService.getDispositionSchedule(recordCategory);
assertNotNull(di);
assertEquals("N1-218-00-4 item 023", di.getDispositionAuthority());
assertEquals("Cut off monthly, hold 1 month, then destroy.", di.getDispositionInstructions());
assertFalse(di.isRecordLevelDisposition());
List<DispositionActionDefinition> das = di.getDispositionActionDefinitions();
assertNotNull(das);
assertEquals(2, das.size());
assertEquals("cutoff", das.get(0).getName());
assertEquals("destroy", das.get(1).getName());
return null;
}
});
}
public void testMoveRecordWithinFileplan()
{
setComplete();
endTransaction();
// We need record folders for test-filing as follows:
// 1. A 'clean' record folder with no disposition schedult and no review period.
// 2. A 'vital' record folder which has a review period defined.
// 3. A 'dispositionable' record folder which has an applicable disposition schedule.
//
// The example fileplan includes a folder which covers [2] and [3] together.
final NodeRef cleanRecordFolder = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
NodeRef result = TestUtilities.getRecordFolder(searchService, "Civilian Files", "Case Files and Papers", "Gilbert Competency Hearing");
assertNotNull("cleanRecordFolder was null", result);
final DispositionSchedule dispositionSchedule = dispositionService.getDispositionSchedule(result);
assertNull("cleanRecordFolder had non-null disposition instructions.", dispositionSchedule.getDispositionInstructions());
assertTrue("cleanRecordFolder had non-empty disposition instruction definitions.", dispositionSchedule.getDispositionActionDefinitions().isEmpty());
final VitalRecordDefinition vitalRecordDefinition = vitalRecordService.getVitalRecordDefinition(result);
assertEquals("cleanRecordFolder had wrong review period.", "0", vitalRecordDefinition.getReviewPeriod().getExpression());
assertNull("cleanRecordFolder had non-null review date.", vitalRecordDefinition.getNextReviewDate());
return result;
}
});
final NodeRef dispAndVitalRecordFolder = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
NodeRef result = TestUtilities.getRecordFolder(searchService, "Reports", "AIS Audit Records", "January AIS Audit Records");
assertNotNull("dispositionAndVitalRecordFolder was null", result);
final DispositionSchedule dispositionSchedule = dispositionService.getDispositionSchedule(result);
assertNotNull("dispositionAndVitalRecordFolder had null disposition instructions.", dispositionSchedule.getDispositionInstructions());
assertFalse("dispositionAndVitalRecordFolder had empty disposition instruction definitions.", dispositionSchedule.getDispositionActionDefinitions().isEmpty());
final VitalRecordDefinition vitalRecordDefinition = vitalRecordService.getVitalRecordDefinition(result);
assertFalse("dispositionAndVitalRecordFolder had wrong review period.", "none|0".equals(vitalRecordDefinition.getReviewPeriod().getExpression()));
assertNotNull("dispositionAndVitalRecordFolder had null review date.", vitalRecordDefinition.getNextReviewDate());
return result;
}
});
// Create a record in the 'clean' folder.
final NodeRef testRecord = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
final NodeRef result = nodeService.createNode(cleanRecordFolder, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI,
"Record" + System.currentTimeMillis() + ".txt"),
ContentModel.TYPE_CONTENT).getChildRef();
rmActionService.executeRecordsManagementAction(result, "file");
TestUtilities.declareRecord(result, unprotectedNodeService, rmActionService);
return result;
}
});
// Ensure it's devoid of all disposition and review-related state.
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
final DispositionSchedule dispositionSchedule = dispositionService.getDispositionSchedule(testRecord);
assertNull("testRecord had non-null disposition instructions.", dispositionSchedule.getDispositionInstructions());
assertTrue("testRecord had non-empty disposition instruction definitions.", dispositionSchedule.getDispositionActionDefinitions().isEmpty());
final VitalRecordDefinition vitalRecordDefinition = vitalRecordService.getVitalRecordDefinition(testRecord);
assertEquals("testRecord had wrong review period.", "0", vitalRecordDefinition.getReviewPeriod().getExpression());
assertNull("testRecord had non-null review date.", vitalRecordDefinition.getNextReviewDate());
return null;
}
});
// Move from non-vital to vital - also non-dispositionable to dispositionable at the same time.
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
nodeService.moveNode(testRecord, dispAndVitalRecordFolder, ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS);
return null;
}
});
// Assert that the disposition and review-related data are correct after the move.
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
final DispositionSchedule dispositionSchedule = dispositionService.getDispositionSchedule(testRecord);
assertNotNull("testRecord had null disposition instructions.", dispositionSchedule.getDispositionInstructions());
assertFalse("testRecord had empty disposition instruction definitions.", dispositionSchedule.getDispositionActionDefinitions().isEmpty());
final VitalRecordDefinition vitalRecordDefinition = vitalRecordService.getVitalRecordDefinition(testRecord);
assertFalse("testRecord had wrong review period.", "0".equals(vitalRecordDefinition.getReviewPeriod().getExpression()));
assertNotNull("testRecord had null review date.", vitalRecordDefinition.getNextReviewDate());
return null;
}
});
// Move the test record back from vital to non-vital - also dispositionable to non-dispositionable at the same time.
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
nodeService.moveNode(testRecord, cleanRecordFolder, ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS);
return null;
}
});
// Assert that the disposition and review-related data are correct after the move.
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
final DispositionSchedule dispositionSchedule = dispositionService.getDispositionSchedule(testRecord);
assertNull("testRecord had non-null disposition instructions.", dispositionSchedule.getDispositionInstructions());
assertTrue("testRecord had non-empty disposition instruction definitions.", dispositionSchedule.getDispositionActionDefinitions().isEmpty());
final VitalRecordDefinition vitalRecordDefinition = vitalRecordService.getVitalRecordDefinition(testRecord);
assertEquals("testRecord had wrong review period.", "0", vitalRecordDefinition.getReviewPeriod().getExpression());
assertNull("testRecord had non-null review date.", vitalRecordDefinition.getNextReviewDate());
return null;
}
});
//TODO check the search aspect
// Tidy up.
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
nodeService.deleteNode(testRecord);
return null;
}
});
}
public void testCopyRecordWithinFileplan()
{
setComplete();
endTransaction();
// We need record folders for test-filing as follows:
// 1. A 'clean' record folder with no disposition schedule and no review period.
// 2. A 'vital' record folder which has a review period defined.
// 3. A 'dispositionable' record folder which has an applicable disposition schedule.
//
// The example fileplan includes a folder which covers [2] and [3] together.
final NodeRef cleanRecordFolder = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
NodeRef result = TestUtilities.getRecordFolder(searchService, "Civilian Files", "Case Files and Papers", "Gilbert Competency Hearing");
assertNotNull("cleanRecordFolder was null", result);
final DispositionSchedule dispositionSchedule = dispositionService.getDispositionSchedule(result);
assertNull("cleanRecordFolder had non-null disposition instructions.", dispositionSchedule.getDispositionInstructions());
assertTrue("cleanRecordFolder had non-empty disposition instruction definitions.", dispositionSchedule.getDispositionActionDefinitions().isEmpty());
final VitalRecordDefinition vitalRecordDefinition = vitalRecordService.getVitalRecordDefinition(result);
assertEquals("cleanRecordFolder had wrong review period.", "0", vitalRecordDefinition.getReviewPeriod().getExpression());
assertNull("cleanRecordFolder had non-null review date.", vitalRecordDefinition.getNextReviewDate());
return result;
}
});
final NodeRef dispAndVitalRecordFolder = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
NodeRef result = TestUtilities.getRecordFolder(searchService, "Reports", "AIS Audit Records", "January AIS Audit Records");
assertNotNull("dispositionAndVitalRecordFolder was null", result);
final DispositionSchedule dispositionSchedule = dispositionService.getDispositionSchedule(result);
assertNotNull("dispositionAndVitalRecordFolder had null disposition instructions.", dispositionSchedule.getDispositionInstructions());
assertFalse("dispositionAndVitalRecordFolder had empty disposition instruction definitions.", dispositionSchedule.getDispositionActionDefinitions().isEmpty());
final VitalRecordDefinition vitalRecordDefinition = vitalRecordService.getVitalRecordDefinition(result);
assertFalse("dispositionAndVitalRecordFolder had wrong review period.", "none|0".equals(vitalRecordDefinition.getReviewPeriod().getExpression()));
assertNotNull("dispositionAndVitalRecordFolder had null review date.", vitalRecordDefinition.getNextReviewDate());
return result;
}
});
// Create a record in the 'clean' folder.
final NodeRef testRecord = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
final NodeRef result = nodeService.createNode(cleanRecordFolder, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI,
"Record" + System.currentTimeMillis() + ".txt"),
ContentModel.TYPE_CONTENT).getChildRef();
rmActionService.executeRecordsManagementAction(result, "file");
TestUtilities.declareRecord(result, unprotectedNodeService, rmActionService);
return result;
}
});
// Ensure it's devoid of all disposition and review-related state.
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
final DispositionSchedule dispositionSchedule = dispositionService.getDispositionSchedule(testRecord);
assertNull("testRecord had non-null disposition instructions.", dispositionSchedule.getDispositionInstructions());
assertTrue("testRecord had non-empty disposition instruction definitions.", dispositionSchedule.getDispositionActionDefinitions().isEmpty());
final VitalRecordDefinition vitalRecordDefinition = vitalRecordService.getVitalRecordDefinition(testRecord);
assertEquals("testRecord had wrong review period.", "0", vitalRecordDefinition.getReviewPeriod().getExpression());
assertNull("testRecord had non-null review date.", vitalRecordDefinition.getNextReviewDate());
return null;
}
});
// Copy from non-vital to vital - also non-dispositionable to dispositionable at the same time.
final NodeRef copiedNode = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
FileInfo fileInfo = fileFolderService.copy(testRecord, dispAndVitalRecordFolder, null);
NodeRef n = fileInfo.getNodeRef();
return n;
}
});
// Assert that the disposition and review-related data are correct after the copy.
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
final DispositionSchedule dispositionSchedule = dispositionService.getDispositionSchedule(copiedNode);
assertNotNull("copiedNode had null disposition instructions.", dispositionSchedule.getDispositionInstructions());
assertFalse("copiedNode had empty disposition instruction definitions.", dispositionSchedule.getDispositionActionDefinitions().isEmpty());
final VitalRecordDefinition vitalRecordDefinition = vitalRecordService.getVitalRecordDefinition(copiedNode);
assertFalse("copiedNode had wrong review period.", "0".equals(vitalRecordDefinition.getReviewPeriod().getExpression()));
assertNotNull("copiedNode had null review date.", vitalRecordDefinition.getNextReviewDate());
return null;
}
});
// Create a record in the 'vital and disposition' folder.
final NodeRef testRecord2 = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
final NodeRef result = nodeService.createNode(dispAndVitalRecordFolder, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI,
"Record2" + System.currentTimeMillis() + ".txt"),
ContentModel.TYPE_CONTENT).getChildRef();
rmActionService.executeRecordsManagementAction(result, "file");
TestUtilities.declareRecord(result, unprotectedNodeService, rmActionService);
return result;
}
});
// Check the vital and disposition status.
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
final DispositionSchedule dispositionSchedule = dispositionService.getDispositionSchedule(testRecord2);
assertNotNull("testRecord2 had null disposition instructions.", dispositionSchedule.getDispositionInstructions());
assertFalse("testRecord2 had empty disposition instruction definitions.", dispositionSchedule.getDispositionActionDefinitions().isEmpty());
final VitalRecordDefinition vitalRecordDefinition = vitalRecordService.getVitalRecordDefinition(testRecord2);
assertFalse("testRecord2 had wrong review period.", "0".equals(vitalRecordDefinition.getReviewPeriod().getExpression()));
assertNotNull("testRecord2 had null review date.", vitalRecordDefinition.getNextReviewDate());
return null;
}
});
// copy the record back from vital to non-vital - also dispositionable to non-dispositionable at the same time.
final NodeRef copiedBackNode = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
FileInfo fileInfo = fileFolderService.copy(testRecord2, cleanRecordFolder, null); // TODO Something wrong here.
NodeRef n = fileInfo.getNodeRef();
return n;
}
});
// Assert that the disposition and review-related data are correct after the copy-back.
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
final DispositionSchedule dispositionSchedule = dispositionService.getDispositionSchedule(copiedBackNode);
assertNull("copiedBackNode had non-null disposition instructions.", dispositionSchedule.getDispositionInstructions());
assertTrue("copiedBackNode had non-empty disposition instruction definitions.", dispositionSchedule.getDispositionActionDefinitions().isEmpty());
final VitalRecordDefinition vitalRecordDefinition = vitalRecordService.getVitalRecordDefinition(copiedBackNode);
assertEquals("copiedBackNode had wrong review period.", "0", vitalRecordDefinition.getReviewPeriod().getExpression());
assertNull("copiedBackNode had non-null review date.", vitalRecordDefinition.getNextReviewDate());
return null;
}
});
//TODO check the search aspect
// Tidy up.
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
nodeService.deleteNode(copiedBackNode);
nodeService.deleteNode(testRecord2);
nodeService.deleteNode(copiedNode);
nodeService.deleteNode(testRecord);
return null;
}
});
}
public void xxxtestUpdateNextDispositionAction()
{
setComplete();
endTransaction();
final FileAction fileAction = (FileAction)applicationContext.getBean("file");
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
// Get a record folder
NodeRef folderRecord = TestUtilities.getRecordFolder(searchService, "Reports", "AIS Audit Records", "January AIS Audit Records");
assertNotNull(folderRecord);
assertEquals("January AIS Audit Records", nodeService.getProperty(folderRecord, ContentModel.PROP_NAME));
DispositionSchedule di = dispositionService.getDispositionSchedule(folderRecord);
assertNotNull(di);
assertEquals("N1-218-00-4 item 023", di.getDispositionAuthority());
assertEquals("Cut off monthly, hold 1 month, then destroy.", di.getDispositionInstructions());
assertFalse(di.isRecordLevelDisposition());
assertFalse(nodeService.hasAspect(folderRecord, ASPECT_DISPOSITION_LIFECYCLE));
fileAction.updateNextDispositionAction(folderRecord);
// Check the next disposition action
assertTrue(nodeService.hasAspect(folderRecord, ASPECT_DISPOSITION_LIFECYCLE));
NodeRef ndNodeRef = nodeService.getChildAssocs(folderRecord, ASSOC_NEXT_DISPOSITION_ACTION, RegexQNamePattern.MATCH_ALL).get(0).getChildRef();
assertNotNull(ndNodeRef);
assertEquals("cutoff", nodeService.getProperty(ndNodeRef, PROP_DISPOSITION_ACTION));
assertEquals(di.getDispositionActionDefinitions().get(0).getId(), nodeService.getProperty(ndNodeRef, PROP_DISPOSITION_ACTION_ID));
assertNotNull(nodeService.getProperty(ndNodeRef, PROP_DISPOSITION_AS_OF));
// Check the history is empty
// TODO
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
props.put(PROP_CUT_OFF_DATE, new Date());
unprotectedNodeService.addAspect(folderRecord, ASPECT_CUT_OFF, props);
fileAction.updateNextDispositionAction(folderRecord);
assertTrue(nodeService.hasAspect(folderRecord, ASPECT_DISPOSITION_LIFECYCLE));
ndNodeRef = nodeService.getChildAssocs(folderRecord, ASSOC_NEXT_DISPOSITION_ACTION, RegexQNamePattern.MATCH_ALL).get(0).getChildRef();
assertNotNull(ndNodeRef);
assertEquals("destroy", nodeService.getProperty(ndNodeRef, PROP_DISPOSITION_ACTION));
assertEquals(di.getDispositionActionDefinitions().get(1).getId(), nodeService.getProperty(ndNodeRef, PROP_DISPOSITION_ACTION_ID));
assertNotNull(nodeService.getProperty(ndNodeRef, PROP_DISPOSITION_AS_OF));
// Check the history has an action
// TODO
fileAction.updateNextDispositionAction(folderRecord);
assertTrue(nodeService.hasAspect(folderRecord, ASPECT_DISPOSITION_LIFECYCLE));
assertTrue(nodeService.getChildAssocs(folderRecord, ASSOC_NEXT_DISPOSITION_ACTION, RegexQNamePattern.MATCH_ALL).isEmpty());
// Check the history has both actions
// TODO
return null;
}
});
}
}

View File

@@ -0,0 +1,635 @@
/*
* 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.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.RecordsManagementAdminService;
import org.alfresco.module.org_alfresco_module_rm.RecordsManagementService;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionService;
import org.alfresco.module.org_alfresco_module_rm.action.impl.FreezeAction;
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.event.RecordsManagementEventService;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.model.RmSiteType;
import org.alfresco.module.org_alfresco_module_rm.search.RecordsManagementSearchService;
import org.alfresco.module.org_alfresco_module_rm.security.RecordsManagementSecurityService;
import org.alfresco.module.org_alfresco_module_rm.vital.VitalRecordService;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.policy.PolicyComponent;
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.dictionary.DictionaryService;
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.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.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.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
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
{
/** Application context */
protected static final String[] CONFIG_LOCATIONS = new String[]
{
"classpath:alfresco/application-context.xml",
"classpath:test-context.xml"
};
protected ApplicationContext applicationContext;
/** Test model contants */
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 */
protected static final String SITE_ID = "mySite";
/** 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;
/** RM Services */
protected RecordsManagementService rmService;
protected DispositionService dispositionService;
protected RecordsManagementEventService eventService;
protected RecordsManagementAdminService adminService;
protected RecordsManagementActionService actionService;
protected RecordsManagementSearchService rmSearchService;
protected RecordsManagementSecurityService securityService;
protected CapabilityService capabilityService;
protected VitalRecordService vitalRecordService;
/** test data */
protected StoreRef storeRef;
protected NodeRef rootNodeRef;
protected SiteInfo siteInfo;
protected NodeRef folder;
protected NodeRef filePlan;
protected NodeRef rmContainer;
protected DispositionSchedule dispositionSchedule;
protected NodeRef rmFolder;
/** 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 values */
protected static final String DEFAULT_DISPOSITION_AUTHORITY = "disposition authority";
protected static final String DEFAULT_DISPOSITION_INSTRUCTIONS = "disposition instructions";
protected static final String DEFAULT_DISPOSITION_DESCRIPTION = "disposition action description";
protected static final String DEFAULT_EVENT_NAME = "case_closed";
protected static final String PERIOD_NONE = "none|0";
/**
* 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.
* @return
*/
protected boolean isUserTest()
{
return false;
}
/**
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception
{
// Get the application context
applicationContext = ApplicationContextHelper.getApplicationContext(CONFIG_LOCATIONS);
// Initialise the service beans
initServices();
// Setup test data
setupTestData();
if (isMultiHierarchyTest() == true)
{
setupMultiHierarchyTestData();
}
// 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");
// Get RM services
rmService = (RecordsManagementService)applicationContext.getBean("RecordsManagementService");
dispositionService = (DispositionService)applicationContext.getBean("DispositionService");
eventService = (RecordsManagementEventService)applicationContext.getBean("RecordsManagementEventService");
adminService = (RecordsManagementAdminService)applicationContext.getBean("RecordsManagementAdminService");
actionService = (RecordsManagementActionService)this.applicationContext.getBean("RecordsManagementActionService");
rmSearchService = (RecordsManagementSearchService)this.applicationContext.getBean("RecordsManagementSearchService");
securityService = (RecordsManagementSecurityService)this.applicationContext.getBean("RecordsManagementSecurityService");
capabilityService = (CapabilityService)this.applicationContext.getBean("CapabilityService");
vitalRecordService = (VitalRecordService)this.applicationContext.getBean("VitalRecordService");
}
/**
* @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(SITE_ID);
}
/**
* @see org.alfresco.util.RetryingTransactionHelperTestCase#getRetryingTransactionHelper()
*/
@Override
public RetryingTransactionHelper getRetryingTransactionHelper()
{
return retryingTransactionHelper;
}
/**
* 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;
}
});
}
/**
* 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
siteInfo = siteService.createSite("preset", SITE_ID, "title", "descrition", SiteVisibility.PUBLIC, RecordsManagementModel.TYPE_RM_SITE);
filePlan = siteService.getContainer(SITE_ID, RmSiteType.COMPONENT_DOCUMENT_LIBRARY);
assertNotNull("Site document library container was not created successfully.", filePlan);
// Create RM container
rmContainer = rmService.createRecordCategory(filePlan, "rmContainer");
assertNotNull("Could not create rm container", rmContainer);
// Create disposition schedule
dispositionSchedule = createBasicDispositionSchedule(rmContainer);
// Create RM folder
rmFolder = rmService.createRecordFolder(rmContainer, "rmFolder");
assertNotNull("Could not create rm folder", rmFolder);
}
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);
securityService.assignRoleToAuthority(filePlan, "User", rmUserName);
powerUserName = GUID.generate();
powerUserPerson = createPerson(powerUserName);
securityService.assignRoleToAuthority(filePlan, "PowerUser", powerUserName);
securityOfficerName = GUID.generate();
securityOfficerPerson = createPerson(securityOfficerName);
securityService.assignRoleToAuthority(filePlan, "SecurityOfficer", securityOfficerName);
recordsManagerName = GUID.generate();
recordsManagerPerson = createPerson(recordsManagerName);
securityService.assignRoleToAuthority(filePlan, "RecordsManager", recordsManagerName);
rmAdminName = GUID.generate();
rmAdminPerson = createPerson(rmAdminName);
securityService.assignRoleToAuthority(filePlan, "Administrator", rmAdminName);
testUsers = new String[]
{
userName,
rmUserName,
powerUserName,
securityOfficerName,
recordsManagerName,
rmAdminName
};
}
protected NodeRef createPerson(String userName)
{
authenticationService.createAuthentication(userName, "password".toCharArray());
Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(ContentModel.PROP_USERNAME, userName);
return personService.createPerson(properties);
}
/**
* 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 = rmService.createRecordCategory(filePlan, "mhContainer");
// Level 1
mhContainer11 = rmService.createRecordCategory(mhContainer, "mhContainer11");
mhDispositionSchedule11 = createBasicDispositionSchedule(mhContainer11, "ds11", DEFAULT_DISPOSITION_AUTHORITY, false, true);
mhContainer12 = rmService.createRecordCategory(mhContainer, "mhContainer12");
mhDispositionSchedule12 = createBasicDispositionSchedule(mhContainer12, "ds12", DEFAULT_DISPOSITION_AUTHORITY, false, true);
// Level 2
mhContainer21 = rmService.createRecordCategory(mhContainer11, "mhContainer21");
mhContainer22 = rmService.createRecordCategory(mhContainer12, "mhContainer22");
mhContainer23 = rmService.createRecordCategory(mhContainer12, "mhContainer23");
mhDispositionSchedule23 = createBasicDispositionSchedule(mhContainer23, "ds23", DEFAULT_DISPOSITION_AUTHORITY, false, true);
// Level 3
mhContainer31 = rmService.createRecordCategory(mhContainer21, "mhContainer31");
mhContainer32 = rmService.createRecordCategory(mhContainer22, "mhContainer32");
mhContainer33 = rmService.createRecordCategory(mhContainer22, "mhContainer33");
mhDispositionSchedule33 = createBasicDispositionSchedule(mhContainer33, "ds33", DEFAULT_DISPOSITION_AUTHORITY, true, true);
mhContainer34 = rmService.createRecordCategory(mhContainer23, "mhContainer34");
mhContainer35 = rmService.createRecordCategory(mhContainer23, "mhContainer35");
mhDispositionSchedule35 = createBasicDispositionSchedule(mhContainer35, "ds35", DEFAULT_DISPOSITION_AUTHORITY, true, true);
// Record folders
mhRecordFolder41 = rmService.createRecordFolder(mhContainer31, "mhFolder41");
mhRecordFolder42 = rmService.createRecordFolder(mhContainer32, "mhFolder42");
mhRecordFolder43 = rmService.createRecordFolder(mhContainer33, "mhFolder43");
mhRecordFolder44 = rmService.createRecordFolder(mhContainer34, "mhFolder44");
mhRecordFolder45 = rmService.createRecordFolder(mhContainer35, "mhFolder45");
}
/**
*
* @param container
* @return
*/
protected DispositionSchedule createBasicDispositionSchedule(NodeRef container)
{
return createBasicDispositionSchedule(container, DEFAULT_DISPOSITION_INSTRUCTIONS, DEFAULT_DISPOSITION_AUTHORITY, false, true);
}
/**
*
* @param container
* @param isRecordLevel
* @param defaultDispositionActions
* @return
*/
protected DispositionSchedule createBasicDispositionSchedule(
NodeRef container,
String dispositionInstructions,
String dispositionAuthority,
boolean isRecordLevel,
boolean defaultDispositionActions)
{
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);
assertNotNull(dispositionSchedule);
if (defaultDispositionActions == true)
{
Map<QName, Serializable> adParams = new HashMap<QName, Serializable>(3);
adParams.put(PROP_DISPOSITION_ACTION_NAME, "cutoff");
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);
adParams = new HashMap<QName, Serializable>(3);
adParams.put(PROP_DISPOSITION_ACTION_NAME, "destroy");
adParams.put(PROP_DISPOSITION_DESCRIPTION, DEFAULT_DISPOSITION_DESCRIPTION);
adParams.put(PROP_DISPOSITION_PERIOD, "immediately|0");
dispositionService.addDispositionActionDefinition(dispositionSchedule, adParams);
}
return dispositionSchedule;
}
protected NodeRef createRecord(NodeRef recordFolder, String name)
{
return createRecord(recordFolder, name, null, "Some test content");
}
protected 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 = this.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;
}
protected void declareRecord(final NodeRef record)
{
AuthenticationUtil.runAs(new RunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
// Declare record
nodeService.setProperty(record, RecordsManagementModel.PROP_PUBLICATION_DATE, new Date());
nodeService.setProperty(record, RecordsManagementModel.PROP_MEDIA_TYPE, "mediaTypeValue");
nodeService.setProperty(record, RecordsManagementModel.PROP_FORMAT, "formatValue");
nodeService.setProperty(record, RecordsManagementModel.PROP_DATE_RECEIVED, new Date());
nodeService.setProperty(record, RecordsManagementModel.PROP_DATE_FILED, new Date());
nodeService.setProperty(record, RecordsManagementModel.PROP_ORIGINATOR, "origValue");
nodeService.setProperty(record, RecordsManagementModel.PROP_ORIGINATING_ORGANIZATION, "origOrgValue");
nodeService.setProperty(record, ContentModel.PROP_TITLE, "titleValue");
actionService.executeRecordsManagementAction(record, "declareRecord");
return null;
}
}, AuthenticationUtil.getAdminUserName());
}
protected 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());
}
protected void unfreeze(final NodeRef nodeRef)
{
AuthenticationUtil.runAs(new RunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
actionService.executeRecordsManagementAction(nodeRef, "unfreeze");
return null;
}
}, AuthenticationUtil.getSystemUserName());
}
}

View File

@@ -0,0 +1,57 @@
/*
* 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.Map;
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;
}
@Override
protected boolean isExecutableImpl(NodeRef filePlanComponent, Map<String, Serializable> parameters, boolean throwException)
{
return true;
}
}

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.util;
import java.io.Serializable;
import java.util.Map;
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;
}
@Override
protected boolean isExecutableImpl(NodeRef filePlanComponent, Map<String, Serializable> parameters, boolean throwException)
{
return true;
}
}

View File

@@ -0,0 +1,52 @@
/*
* 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.Map;
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 we not a Date as expected.");
}
}
/* (non-Javadoc)
* @see org.alfresco.module.org_alfresco_module_rm.action.RMActionExecuterAbstractBase#isExecutableImpl(org.alfresco.service.cmr.repository.NodeRef, java.util.Map, boolean)
*/
@Override
protected boolean isExecutableImpl(NodeRef filePlanComponent, Map<String, Serializable> parameters, boolean throwException)
{
return true;
}
}

View File

@@ -0,0 +1,238 @@
/*
* 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.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.RecordsManagementService;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionService;
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.RecordsManagementSearchBehaviour;
import org.alfresco.module.org_alfresco_module_rm.script.BootstrapTestDataGet;
import org.alfresco.module.org_alfresco_module_rm.security.RecordsManagementSecurityService;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
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.ResultSet;
import org.alfresco.service.cmr.search.SearchParameters;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.cmr.view.ImporterBinding;
import org.alfresco.service.cmr.view.ImporterService;
import org.alfresco.service.cmr.view.Location;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.ISO9075;
import org.springframework.context.ApplicationContext;
/**
* This class is an initial placeholder for miscellaneous helper methods used in
* the testing or test initialisation of the DOD5015 module.
*
* @author neilm
*/
public class TestUtilities implements RecordsManagementModel
{
public static NodeRef loadFilePlanData(ApplicationContext applicationContext)
{
return TestUtilities.loadFilePlanData(applicationContext, true, false);
}
public static NodeRef loadFilePlanData(ApplicationContext applicationContext, boolean patchData, boolean alwaysLoad)
{
NodeService nodeService = (NodeService)applicationContext.getBean("NodeService");
AuthorityService authorityService = (AuthorityService)applicationContext.getBean("AuthorityService");
PermissionService permissionService = (PermissionService)applicationContext.getBean("PermissionService");
SearchService searchService = (SearchService)applicationContext.getBean("SearchService");
ImporterService importerService = (ImporterService)applicationContext.getBean("importerComponent");
RecordsManagementService recordsManagementService = (RecordsManagementService)applicationContext.getBean("RecordsManagementService");
RecordsManagementActionService recordsManagementActionService = (RecordsManagementActionService)applicationContext.getBean("RecordsManagementActionService");
RecordsManagementSecurityService recordsManagementSecurityService = (RecordsManagementSecurityService)applicationContext.getBean("RecordsManagementSecurityService");
RecordsManagementSearchBehaviour recordsManagementSearchBehaviour = (RecordsManagementSearchBehaviour)applicationContext.getBean("recordsManagementSearchBehaviour");
DispositionService dispositionService = (DispositionService)applicationContext.getBean("DispositionService");
NodeRef filePlan = null;
NodeRef rootNode = nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
if (alwaysLoad == false)
{
// Try and find a file plan hanging from the root node
List<ChildAssociationRef> assocs = nodeService.getChildAssocs(rootNode, ContentModel.ASSOC_CHILDREN, TYPE_FILE_PLAN);
if (assocs.size() != 0)
{
filePlan = assocs.get(0).getChildRef();
return filePlan;
}
}
// For now creating the filePlan beneath the
filePlan = nodeService.createNode(rootNode, ContentModel.ASSOC_CHILDREN,
TYPE_FILE_PLAN,
TYPE_FILE_PLAN).getChildRef();
// Do the data load into the the provided filePlan node reference
// TODO ...
InputStream is = TestUtilities.class.getClassLoader().getResourceAsStream(
"alfresco/module/org_alfresco_module_rm/dod5015/DODExampleFilePlan.xml");
//"alfresco/module/org_alfresco_module_rm/bootstrap/temp.xml");
Assert.assertNotNull("The DODExampleFilePlan.xml import file could not be found", is);
Reader viewReader = new InputStreamReader(is);
Location location = new Location(filePlan);
importerService.importView(viewReader, location, REPLACE_BINDING, null);
if (patchData == true)
{
// Tempory call out to patch data after AMP
BootstrapTestDataGet.patchLoadedData(searchService, nodeService, recordsManagementService,
recordsManagementActionService, permissionService,
authorityService, recordsManagementSecurityService,
recordsManagementSearchBehaviour,
dispositionService);
}
return filePlan;
}
public static NodeRef getRecordSeries(SearchService searchService, String seriesName)
{
SearchParameters searchParameters = new SearchParameters();
searchParameters.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
String query = "PATH:\"dod:filePlan/cm:" + ISO9075.encode(seriesName) + "\"";
searchParameters.setQuery(query);
searchParameters.setLanguage(SearchService.LANGUAGE_LUCENE);
ResultSet rs = searchService.query(searchParameters);
try
{
//setComplete();
//endTransaction();
return rs.getNodeRefs().isEmpty() ? null : rs.getNodeRef(0);
}
finally
{
rs.close();
}
}
public static NodeRef getRecordCategory(SearchService searchService, String seriesName, String categoryName)
{
SearchParameters searchParameters = new SearchParameters();
searchParameters.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
String query = "PATH:\"dod:filePlan/cm:" + ISO9075.encode(seriesName) + "/cm:" + ISO9075.encode(categoryName) + "\"";
searchParameters.setQuery(query);
searchParameters.setLanguage(SearchService.LANGUAGE_LUCENE);
ResultSet rs = searchService.query(searchParameters);
try
{
//setComplete();
//endTransaction();
return rs.getNodeRefs().isEmpty() ? null : rs.getNodeRef(0);
}
finally
{
rs.close();
}
}
public static NodeRef getRecordFolder(SearchService searchService, String seriesName, String categoryName, String folderName)
{
SearchParameters searchParameters = new SearchParameters();
searchParameters.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
String query = "PATH:\"dod:filePlan/cm:" + ISO9075.encode(seriesName)
+ "/cm:" + ISO9075.encode(categoryName)
+ "/cm:" + ISO9075.encode(folderName) + "\"";
System.out.println("Query: " + query);
searchParameters.setQuery(query);
searchParameters.setLanguage(SearchService.LANGUAGE_LUCENE);
ResultSet rs = searchService.query(searchParameters);
try
{
// setComplete();
// endTransaction();
return rs.getNodeRefs().isEmpty() ? null : rs.getNodeRef(0);
}
finally
{
rs.close();
}
}
// TODO .. do we need to redeclare this here ??
private static ImporterBinding REPLACE_BINDING = new ImporterBinding()
{
public UUID_BINDING getUUIDBinding()
{
return UUID_BINDING.REPLACE_EXISTING;
}
public String getValue(String key)
{
return null;
}
public boolean allowReferenceWithinTransaction()
{
return false;
}
public QName[] getExcludedClasses()
{
return null;
}
};
public static void declareRecord(NodeRef recordToDeclare, NodeService nodeService,
RecordsManagementActionService rmActionService)
{
// Declare record
Map<QName, Serializable> propValues = nodeService.getProperties(recordToDeclare);
propValues.put(RecordsManagementModel.PROP_PUBLICATION_DATE, new Date());
List<String> smList = new ArrayList<String>(2);
// smList.add(DOD5015Test.FOUO);
// smList.add(DOD5015Test.NOFORN);
propValues.put(RecordsManagementModel.PROP_SUPPLEMENTAL_MARKING_LIST, (Serializable)smList);
propValues.put(RecordsManagementModel.PROP_MEDIA_TYPE, "mediaTypeValue");
propValues.put(RecordsManagementModel.PROP_FORMAT, "formatValue");
propValues.put(RecordsManagementModel.PROP_DATE_RECEIVED, new Date());
propValues.put(RecordsManagementModel.PROP_ORIGINATOR, "origValue");
propValues.put(RecordsManagementModel.PROP_ORIGINATING_ORGANIZATION, "origOrgValue");
propValues.put(ContentModel.PROP_TITLE, "titleValue");
nodeService.setProperties(recordToDeclare, propValues);
rmActionService.executeRecordsManagementAction(recordToDeclare, "declareRecord");
}
}

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,78 @@
/*
* 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.TestUtilities;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
/**
* This class tests the Rest API for disposition related operations
*
* @author Roy Wetherall
*/
public class BootstraptestDataRestApiTest extends BaseWebScriptTest implements RecordsManagementModel
{
protected static StoreRef SPACES_STORE = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
protected static final String URL = "/api/rma/bootstraptestdata";
protected static final String SERVICE_URL_PREFIX = "/alfresco/service";
protected static final String APPLICATION_JSON = "application/json";
protected NodeService nodeService;
protected RetryingTransactionHelper transactionHelper;
@Override
protected void setUp() throws Exception
{
super.setUp();
nodeService = (NodeService) getServer().getApplicationContext().getBean("NodeService");
transactionHelper = (RetryingTransactionHelper)getServer().getApplicationContext().getBean("retryingTransactionHelper");
}
public void testBoostrapTestData() throws Exception
{
final NodeRef filePlan = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
return TestUtilities.loadFilePlanData(getServer().getApplicationContext(), false, true);
}
});
sendRequest(new GetRequest(URL), 200);
transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
nodeService.deleteNode(filePlan);
return null;
}
});
}
}

View File

@@ -0,0 +1,633 @@
/*
* 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.Serializable;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Map;
import javax.transaction.UserTransaction;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.RecordsManagementService;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionService;
import org.alfresco.module.org_alfresco_module_rm.event.RecordsManagementEventService;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.TestUtilities;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
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.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.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.cmr.view.ImporterService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
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 BaseWebScriptTest 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";
protected NodeService nodeService;
protected ContentService contentService;
protected SearchService searchService;
protected ImporterService importService;
protected PermissionService permissionService;
protected TransactionService transactionService;
protected RecordsManagementService rmService;
protected RecordsManagementActionService rmActionService;
protected RecordsManagementEventService rmEventService;
protected RetryingTransactionHelper retryingTransactionHelper;
@Override
protected void setUp() throws Exception
{
super.setUp();
this.nodeService = (NodeService) getServer().getApplicationContext().getBean("NodeService");
this.contentService = (ContentService)getServer().getApplicationContext().getBean("ContentService");
this.searchService = (SearchService)getServer().getApplicationContext().getBean("SearchService");
this.importService = (ImporterService)getServer().getApplicationContext().getBean("ImporterService");
this.permissionService = (PermissionService)getServer().getApplicationContext().getBean("PermissionService");
this.transactionService = (TransactionService)getServer().getApplicationContext().getBean("TransactionService");
this.rmService = (RecordsManagementService)getServer().getApplicationContext().getBean("RecordsManagementService");
this.rmActionService = (RecordsManagementActionService)getServer().getApplicationContext().getBean("RecordsManagementActionService");
this.rmEventService = (RecordsManagementEventService)getServer().getApplicationContext().getBean("RecordsManagementEventService");
this.retryingTransactionHelper = (RetryingTransactionHelper)getServer().getApplicationContext().getBean("retryingTransactionHelper");
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
TestUtilities.loadFilePlanData(getServer().getApplicationContext());
return null;
}
});
// Bring the filePlan into the test database.
//
// This is quite a slow call, so if this class grew to have many test methods,
// there would be a real benefit in using something like @BeforeClass for the line below.
//TestUtilities.loadFilePlanData(getServer().getApplicationContext());
}
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
NodeRef series = TestUtilities.getRecordSeries(searchService, "Reports");
assertNotNull(series);
String seriesNodeUrl = series.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;
NodeRef recordCategory = TestUtilities.getRecordCategory(this.searchService, "Reports", "AIS Audit Records");
assertNotNull(recordCategory);
String categoryNodeUrl = recordCategory.toString().replace("://", "/");
String requestUrl = MessageFormat.format(GET_SCHEDULE_URL_FORMAT, categoryNodeUrl);
rsp = sendRequest(new GetRequest(requestUrl), expectedStatus);
System.out.println(" 888 GET response: " + 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 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("N1-218-00-4 item 023", authority);
String instructions = rootDataObject.getString("instructions");
assertEquals("Cut off monthly, hold 1 month, then destroy.", 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(7, action1.length());
assertNotNull(action1.get("id"));
assertNotNull(action1.get("url"));
assertEquals(0, action1.getInt("index"));
assertEquals("cutoff", action1.getString("name"));
assertEquals("Cutoff", action1.getString("label"));
assertEquals("monthend|1", action1.getString("period"));
assertTrue(action1.getBoolean("eligibleOnFirstCompleteEvent"));
JSONObject action2 = (JSONObject)actions.get(1);
assertEquals(8, action2.length());
assertEquals("rma:cutOffDate", action2.get("periodProperty"));
// 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));
// Test data structure returned from "Personnel Security Program Records"
recordCategory = TestUtilities.getRecordCategory(this.searchService, "Civilian Files", "Employee Performance File System Records");
assertNotNull(recordCategory);
categoryNodeUrl = recordCategory.toString().replace("://", "/");
requestUrl = MessageFormat.format(GET_SCHEDULE_URL_FORMAT, categoryNodeUrl);
rsp = sendRequest(new GetRequest(requestUrl), expectedStatus);
//System.out.println("GET response: " + rsp.getContentAsString());
assertEquals("application/json;charset=UTF-8", rsp.getContentType());
// get response as JSON
jsonParsedObject = new JSONObject(new JSONTokener(rsp.getContentAsString()));
assertNotNull(jsonParsedObject);
// check JSON data
dataObj = jsonParsedObject.getJSONObject("data");
assertNotNull(dataObj);
rootDataObject = (JSONObject)dataObj;
assertEquals(10, rootDataObject.length());
// check individual data items
serviceUrl = SERVICE_URL_PREFIX + requestUrl;
url = rootDataObject.getString("url");
assertEquals(serviceUrl, url);
authority = rootDataObject.getString("authority");
assertEquals("GRS 1 item 23b(1)", authority);
instructions = rootDataObject.getString("instructions");
assertEquals("Cutoff when superseded. Destroy immediately after cutoff", instructions);
recordLevel = rootDataObject.getBoolean("recordLevelDisposition");
assertTrue(recordLevel);
assertTrue(rootDataObject.getBoolean("canStepsBeRemoved"));
actions = rootDataObject.getJSONArray("actions");
assertNotNull(actions);
assertEquals(2, actions.length());
action1 = (JSONObject)actions.get(0);
assertEquals(8, action1.length());
assertNotNull(action1.get("id"));
assertNotNull(action1.get("url"));
assertEquals(0, action1.getInt("index"));
assertEquals("cutoff", action1.getString("name"));
assertEquals("Cutoff", action1.getString("label"));
assertTrue(action1.getBoolean("eligibleOnFirstCompleteEvent"));
JSONArray events = action1.getJSONArray("events");
assertNotNull(events);
assertEquals(1, events.length());
assertEquals("superseded", events.get(0));
// Test the retrieval of an empty disposition schedule
NodeRef recordSeries = TestUtilities.getRecordSeries(this.searchService, "Civilian Files");
assertNotNull(recordSeries);
// create a new recordCategory node in the recordSeries and then get
// the disposition schedule
NodeRef newRecordCategory = this.nodeService.createNode(recordSeries, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, QName.createValidLocalName("recordCategory")),
TYPE_RECORD_CATEGORY).getChildRef();
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 recordCategory to get a disposition schedule
NodeRef recordSeries = TestUtilities.getRecordSeries(this.searchService, "Civilian Files");
assertNotNull(recordSeries);
// create a new recordCategory node in the recordSeries and then get
// the disposition schedule
NodeRef newRecordCategory = this.nodeService.createNode(recordSeries, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, QName.createValidLocalName("recordCategory")),
TYPE_RECORD_CATEGORY).getChildRef();
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
{
// create a new recordCategory node in the recordSeries and then get
// the disposition schedule
NodeRef recordSeries = TestUtilities.getRecordSeries(this.searchService, "Civilian Files");
assertNotNull(recordSeries);
NodeRef newRecordCategory = this.nodeService.createNode(recordSeries, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, QName.createValidLocalName("recordCategory")),
TYPE_RECORD_CATEGORY).getChildRef();
// 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("Cutoff", actionDef.getString("label"));
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
{
// create a new recordCategory node in the recordSeries and then get
// the disposition schedule
NodeRef recordSeries = TestUtilities.getRecordSeries(this.searchService, "Civilian Files");
assertNotNull(recordSeries);
NodeRef newRecordCategory = this.nodeService.createNode(recordSeries, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, QName.createValidLocalName("recordCategory")),
TYPE_RECORD_CATEGORY).getChildRef();
// 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
{
// create a new recordFolder in a recordCategory
NodeRef recordCategory = TestUtilities.getRecordCategory(this.searchService, "Military Files",
"Military Assignment Documents");
assertNotNull(recordCategory);
// 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), 404);
UserTransaction txn = transactionService.getUserTransaction(false);
txn.begin();
NodeRef newRecordFolder = this.nodeService.createNode(recordCategory, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, QName.createValidLocalName("recordFolder")),
TYPE_RECORD_FOLDER).getChildRef();
txn.commit();
txn = transactionService.getUserTransaction(false);
txn.begin();
// Create the document
NodeRef recordOne = this.nodeService.createNode(newRecordFolder,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "record"),
ContentModel.TYPE_CONTENT).getChildRef();
// Set the content
ContentWriter writer = this.contentService.getWriter(recordOne, ContentModel.PROP_CONTENT, true);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
writer.setEncoding("UTF-8");
writer.putContent("There is some content in this record");
txn.commit(); // - triggers FileAction
txn = transactionService.getUserTransaction(false);
txn.begin();
declareRecord(recordOne);
txn.commit();
// there should now be a disposition lifecycle for the record
String recordUrl = recordOne.toString().replace("://", "/");
requestUrl = MessageFormat.format(GET_LIFECYCLE_URL_FORMAT, recordUrl);
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"));
assertEquals("Cutoff", dataObj.getString("label"));
assertFalse(dataObj.getBoolean("eventsEligible"));
assertTrue(dataObj.has("events"));
JSONArray events = dataObj.getJSONArray("events");
assertEquals(1, events.length());
JSONObject event1 = events.getJSONObject(0);
assertEquals("superseded", event1.get("name"));
assertEquals("Superseded", event1.get("label"));
assertFalse(event1.getBoolean("complete"));
assertTrue(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);
//System.out.println("GET : " + rsp.getContentAsString());
assertEquals("application/json;charset=UTF-8", rsp.getContentType());
//System.out.println(rsp.getContentAsString());
// 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(this.rmActionService.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(this.rmEventService.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(4, items.length());
assertTrue(items.length() > 0);
item = items.getJSONObject(0);
assertTrue(item.length() == 2);
assertTrue(item.has("label"));
assertTrue(item.has("value"));
}
private void declareRecord(NodeRef recordOne)
{
// Declare record
Map<QName, Serializable> propValues = this.nodeService.getProperties(recordOne);
propValues.put(RecordsManagementModel.PROP_PUBLICATION_DATE, new Date());
// List<String> smList = new ArrayList<String>(2);
// smList.add("FOUO");
// smList.add("NOFORN");
// propValues.put(RecordsManagementModel.PROP_SUPPLEMENTAL_MARKING_LIST, (Serializable)smList);
propValues.put(RecordsManagementModel.PROP_MEDIA_TYPE, "mediaTypeValue");
propValues.put(RecordsManagementModel.PROP_FORMAT, "formatValue");
propValues.put(RecordsManagementModel.PROP_DATE_RECEIVED, new Date());
propValues.put(RecordsManagementModel.PROP_ORIGINATOR, "origValue");
propValues.put(RecordsManagementModel.PROP_ORIGINATING_ORGANIZATION, "origOrgValue");
propValues.put(ContentModel.PROP_TITLE, "titleValue");
this.nodeService.setProperties(recordOne, propValues);
this.rmActionService.executeRecordsManagementAction(recordOne, "declareRecord");
}
}

View File

@@ -0,0 +1,150 @@
/*
* 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.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.service.cmr.security.AuthenticationService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.Status;
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 BaseWebScriptTest
{
public final static String URL_RM_EMAILMAP = "/api/rma/admin/emailmap";
AuthenticationService authenticationService;
@Override
protected void setUp() throws Exception
{
this.authenticationService = (AuthenticationService)getServer().getApplicationContext().getBean("AuthenticationService");
// setCurrentUser(AuthenticationUtil.getAdminUserName());
super.setUp();
// Set the current security context as admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
}
@Override
protected void tearDown() throws Exception
{
super.tearDown();
}
public void testGetEmailMap() throws Exception
{
{
Response response = sendRequest(new GetRequest(URL_RM_EMAILMAP), Status.STATUS_OK);
@SuppressWarnings("unused")
JSONObject top = new JSONObject(response.getContentAsString());
System.out.println(response.getContentAsString());
//JSONArray data = top.getJSONArray("data");
}
}
public void testUpdateEmailMap() throws Exception
{
/**
* Update the list by adding two values
*/
{
JSONObject obj = new JSONObject();
JSONArray add = new JSONArray();
JSONObject val = new JSONObject();
val.put("from", "whatever");
val.put("to", "rmc:Wibble");
add.put(val);
JSONObject val2 = new JSONObject();
val2.put("from", "whatever");
val2.put("to", "rmc:wobble");
add.put(val2);
obj.put("add", add);
System.out.println(obj.toString());
/**
* Now do a post to add a couple of values
*/
Response response = sendRequest(new PostRequest(URL_RM_EMAILMAP, obj.toString(), "application/json"), Status.STATUS_OK);
System.out.println(response.getContentAsString());
// Check the response
JSONArray delete = new JSONArray();
delete.put(val2);
}
/**
* Update the list by deleting a value
*
* "whatever" has two mappings, delete one of them
*/
{
JSONObject obj = new JSONObject();
JSONObject val2 = new JSONObject();
JSONArray delete = new JSONArray();
val2.put("from", "whatever");
val2.put("to", "rmc:wobble");
delete.put(val2);
obj.put("delete", delete);
/**
* Now do a post to delete a couple of values
*/
Response response = sendRequest(new PostRequest(URL_RM_EMAILMAP, obj.toString(), "application/json"), Status.STATUS_OK);
System.out.println(response.getContentAsString());
JSONObject top = new JSONObject(response.getContentAsString());
JSONObject data = top.getJSONObject("data");
JSONArray mappings = data.getJSONArray("mappings");
boolean wibbleFound = false;
for(int i = 0; i < mappings.length(); i++)
{
JSONObject mapping = mappings.getJSONObject(i);
if(mapping.get("from").equals("whatever"))
{
if(mapping.get("to").equals("rmc:Wibble"))
{
wibbleFound = true;
}
else
{
fail("custom mapping for field not deleted");
}
}
}
assertTrue(wibbleFound);
}
}
}

View File

@@ -0,0 +1,257 @@
/*
* 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.RecordsManagementService;
import org.alfresco.module.org_alfresco_module_rm.event.RecordsManagementEventService;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.util.GUID;
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;
import org.json.JSONObject;
/**
* RM event REST API test
*
* @author Roy Wetherall
*/
public class EventRestApiTest extends BaseWebScriptTest implements RecordsManagementModel
{
protected static StoreRef SPACES_STORE = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
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";
protected NodeService nodeService;
protected RecordsManagementService rmService;
protected RecordsManagementEventService rmEventService;
@Override
protected void setUp() throws Exception
{
super.setUp();
this.nodeService = (NodeService) getServer().getApplicationContext().getBean("NodeService");
this.rmService = (RecordsManagementService)getServer().getApplicationContext().getBean("RecordsManagementService");
this.rmEventService = (RecordsManagementEventService)getServer().getApplicationContext().getBean("RecordsManagementEventService");
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
}
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
rmEventService.addEvent(EVENT_TYPE, event1, DISPLAY_LABEL);
rmEventService.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
rmEventService.removeEvent(event1);
rmEventService.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
{
rmEventService.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
{
rmEventService.removeEvent(eventName);
}
}
public void testPutRole() throws Exception
{
String eventName = GUID.generate();
rmEventService.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
sendRequest(new PutRequest(GET_EVENTS_URL + "/cheese", obj.toString(), APPLICATION_JSON), 404);
}
finally
{
// Clean up
rmEventService.removeEvent(eventName);
}
}
public void testGetRole() throws Exception
{
String eventName = GUID.generate();
rmEventService.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
rmEventService.removeEvent(eventName);
}
}
public void testDeleteRole() throws Exception
{
String eventName = GUID.generate();
assertFalse(rmEventService.existsEvent(eventName));
rmEventService.addEvent(EVENT_TYPE, eventName, DISPLAY_LABEL);
assertTrue(rmEventService.existsEvent(eventName));
sendRequest(new DeleteRequest(GET_EVENTS_URL + "/" + eventName),200);
assertFalse(rmEventService.existsEvent(eventName));
// Bad request
sendRequest(new DeleteRequest(GET_EVENTS_URL + "/cheese"), 404);
}
}

View File

@@ -0,0 +1,971 @@
/*
* 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.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
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
*/
public class RMCaveatConfigScriptTest extends BaseWebScriptTest
{
private MutableAuthenticationService authenticationService;
private RMCaveatConfigService caveatConfigService;
private PersonService personService;
private static final String USER_ONE = "RMCaveatConfigTestOne";
private static final String USER_TWO = "RMCaveatConfigTestTwo";
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";
@Override
protected void setUp() throws Exception
{
super.setUp();
this.caveatConfigService = (RMCaveatConfigService)getServer().getApplicationContext().getBean("CaveatConfigService");
this.authenticationService = (MutableAuthenticationService)getServer().getApplicationContext().getBean("AuthenticationService");
this.personService = (PersonService)getServer().getApplicationContext().getBean("PersonService");
// Set the current security context as admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
}
private void createUser(String userName)
{
if (this.authenticationService.authenticationExists(userName) == false)
{
this.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");
this.personService.createPerson(ppOne);
}
}
@Override
protected void tearDown() throws Exception
{
super.tearDown();
//this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
}
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());
JSONArray data = 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);
}
personService.deletePerson("fbloggs");
personService.deletePerson("jrogers");
personService.deletePerson("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", "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_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 = "Generated title list";
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", "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_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);
}
personService.deletePerson("fbloggs");
personService.deletePerson("jrogers");
personService.deletePerson("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,164 @@
/*
* 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.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
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.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* Test of GET RM Constraint (User facing scripts)
*
* @author Mark Rogers
*/
public class RMConstraintScriptTest extends BaseWebScriptTest
{
private MutableAuthenticationService authenticationService;
private RMCaveatConfigService caveatConfigService;
private PersonService personService;
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";
@Override
protected void setUp() throws Exception
{
this.caveatConfigService = (RMCaveatConfigService)getServer().getApplicationContext().getBean("CaveatConfigService");
this.authenticationService = (MutableAuthenticationService)getServer().getApplicationContext().getBean("AuthenticationService");
this.personService = (PersonService)getServer().getApplicationContext().getBean("PersonService");
super.setUp();
}
@Override
protected void tearDown() throws Exception
{
super.tearDown();
}
/**
*
* @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());
JSONArray allowedValues = data.getJSONArray("allowedValuesForCurrentUser");
// 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);
// }
//
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
personService.deletePerson("fbloggs");
personService.deletePerson("jrogers");
personService.deletePerson("jdoe");
}
private void createUser(String userName)
{
if (this.authenticationService.authenticationExists(userName) == false)
{
this.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");
this.personService.createPerson(ppOne);
}
}
}

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.webscript;
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.RecordsManagementService;
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.security.RecordsManagementSecurityService;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.util.GUID;
import org.json.JSONArray;
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 BaseWebScriptTest implements RecordsManagementModel
{
protected static StoreRef SPACES_STORE = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
protected static final String GET_ROLES_URL = "/api/rma/admin/rmroles";
protected static final String SERVICE_URL_PREFIX = "/alfresco/service";
protected static final String APPLICATION_JSON = "application/json";
protected NodeService nodeService;
protected RecordsManagementService rmService;
protected RecordsManagementSecurityService rmSecurityService;
private NodeRef rmRootNode;
@Override
protected void setUp() throws Exception
{
super.setUp();
this.nodeService = (NodeService) getServer().getApplicationContext().getBean("NodeService");
this.rmService = (RecordsManagementService)getServer().getApplicationContext().getBean("RecordsManagementService");
this.rmSecurityService = (RecordsManagementSecurityService)getServer().getApplicationContext().getBean("RecordsManagementSecurityService");
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
List<NodeRef> roots = rmService.getFilePlans();
if (roots.size() != 0)
{
rmRootNode = roots.get(0);
}
else
{
NodeRef root = this.nodeService.getRootNode(new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore"));
rmRootNode = this.nodeService.createNode(root, ContentModel.ASSOC_CHILDREN, ContentModel.ASSOC_CHILDREN, TYPE_FILE_PLAN).getChildRef();
}
}
public void testGetRoles() throws Exception
{
String role1 = GUID.generate();
String role2 = GUID.generate();
// Create a couple or roles by hand
rmSecurityService.createRole(rmRootNode, role1, "My Test Role", getListOfCapabilities(5));
rmSecurityService.createRole(rmRootNode, role2, "My Test Role Too", getListOfCapabilities(5));
// Add the admin user to one of the roles
rmSecurityService.assignRoleToAuthority(rmRootNode, role1, "admin");
try
{
// Get the roles
Response rsp = sendRequest(new GetRequest(GET_ROLES_URL),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"));
JSONArray caps = roleObj.getJSONArray("capabilities");
assertNotNull(caps);
assertEquals(5, caps.length());
roleObj = roles.getJSONObject(role2);
assertNotNull(roleObj);
assertEquals(role2, roleObj.get("name"));
assertEquals("My Test Role Too", roleObj.get("displayLabel"));
caps = roleObj.getJSONArray("capabilities");
assertNotNull(caps);
assertEquals(5, caps.length());
// Get the roles for "admin"
rsp = sendRequest(new GetRequest(GET_ROLES_URL + "?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"));
caps = roleObj.getJSONArray("capabilities");
assertNotNull(caps);
assertEquals(5, caps.length());
assertFalse(roles.has(role2));
}
finally
{
// Clean up
rmSecurityService.deleteRole(rmRootNode, role1);
rmSecurityService.deleteRole(rmRootNode, role2);
}
}
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(GET_ROLES_URL, 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"));
JSONArray resultCaps = roleObj.getJSONArray("capabilities");
assertNotNull(resultCaps);
assertEquals(5, resultCaps.length());
}
finally
{
rmSecurityService.deleteRole(rmRootNode, roleName);
}
}
public void testPutRole() throws Exception
{
String role1 = GUID.generate();
rmSecurityService.createRole(rmRootNode, 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(GET_ROLES_URL + "/" + 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"));
JSONArray bob = roleObj.getJSONArray("capabilities");
assertNotNull(bob);
assertEquals(4, bob.length());
// Bad requests
sendRequest(new PutRequest(GET_ROLES_URL + "/cheese", obj.toString(), APPLICATION_JSON), 404);
}
finally
{
// Clean up
rmSecurityService.deleteRole(rmRootNode, role1);
}
}
public void testGetRole() throws Exception
{
String role1 = GUID.generate();
rmSecurityService.createRole(rmRootNode, role1, "My Test Role", getListOfCapabilities(5));
try
{
// Get the roles
Response rsp = sendRequest(new GetRequest(GET_ROLES_URL + "/" + 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"));
JSONArray caps = roleObj.getJSONArray("capabilities");
assertNotNull(caps);
assertEquals(5, caps.length());
// Bad requests
sendRequest(new GetRequest(GET_ROLES_URL + "/cheese"), 404);
}
finally
{
// Clean up
rmSecurityService.deleteRole(rmRootNode, role1);
}
}
public void testDeleteRole() throws Exception
{
String role1 = GUID.generate();
assertFalse(rmSecurityService.existsRole(rmRootNode, role1));
rmSecurityService.createRole(rmRootNode, role1, "My Test Role", getListOfCapabilities(5));
assertTrue(rmSecurityService.existsRole(rmRootNode, role1));
sendRequest(new DeleteRequest(GET_ROLES_URL + "/" + role1),200);
assertFalse(rmSecurityService.existsRole(rmRootNode, role1));
// Bad request
sendRequest(new DeleteRequest(GET_ROLES_URL + "/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 = rmSecurityService.getCapabilities();
int count = 0;
for (Capability cap : caps)
{
if (count < size+offset)
{
if (count >= offset)
{
result.add(cap);
}
}
else
{
break;
}
count ++;
}
return result;
}
}