MOB-412: Decouple thread local authentication methods from AuthenticationComponent into new AuthenticationContext super-interface. The AuthenticationContext is a delegate of AbstractAuthenticationComponent and can be accessed directly by low-level classes (e.g. schema bootstrap) before the authentication subsystem is available.

git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@13721 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Dave Ward
2009-03-23 14:01:29 +00:00
parent 61442fd07b
commit facbdaf5b7
43 changed files with 16171 additions and 16073 deletions

View File

@@ -41,8 +41,8 @@
<property name="transactionService"> <property name="transactionService">
<ref bean="transactionService"/> <ref bean="transactionService"/>
</property> </property>
<property name="authenticationComponent"> <property name="authenticationContext">
<ref bean="AuthenticationComponent"/> <ref bean="authenticationContext"/>
</property> </property>
<property name="nodeService"> <property name="nodeService">
<ref bean="NodeService"/> <ref bean="NodeService"/>
@@ -59,8 +59,8 @@
<property name="transactionService"> <property name="transactionService">
<ref bean="transactionService"/> <ref bean="transactionService"/>
</property> </property>
<property name="authenticationComponent"> <property name="authenticationContext">
<ref bean="AuthenticationComponent"/> <ref bean="authenticationContext"/>
</property> </property>
<property name="nodeService"> <property name="nodeService">
<ref bean="NodeService"/> <ref bean="NodeService"/>
@@ -78,8 +78,8 @@
<property name="searchService"> <property name="searchService">
<ref bean="ADMSearchService" /> <ref bean="ADMSearchService" />
</property> </property>
<property name="authenticationComponent"> <property name="authenticationContext">
<ref bean="authenticationComponent" /> <ref bean="authenticationContext" />
</property> </property>
<property name="dictionaryService"> <property name="dictionaryService">
<ref bean="DictionaryService" /> <ref bean="DictionaryService" />

View File

@@ -152,6 +152,12 @@
<!-- Parent bean for beans derived from AbstractAuthenticationComponent --> <!-- Parent bean for beans derived from AbstractAuthenticationComponent -->
<bean id="authenticationComponentBase" abstract="true"> <bean id="authenticationComponentBase" abstract="true">
<property name="authenticationContext">
<ref bean="authenticationContext"/>
</property>
</bean>
<bean id="authenticationContext" class="org.alfresco.repo.security.authentication.AuthenticationContextImpl">
<property name="tenantService"> <property name="tenantService">
<ref bean="tenantService"/> <ref bean="tenantService"/>
</property> </property>

View File

@@ -194,8 +194,8 @@
<property name="nodeService"> <property name="nodeService">
<ref bean="nodeService"/> <ref bean="nodeService"/>
</property> </property>
<property name="authenticationComponent"> <property name="authenticationContext">
<ref bean="authenticationComponent" /> <ref bean="authenticationContext" />
</property> </property>
<property name="systemImporter"> <property name="systemImporter">
<ref bean="systemExporterImporter" /> <ref bean="systemExporterImporter" />
@@ -222,8 +222,8 @@
<property name="namespaceService"> <property name="namespaceService">
<ref bean="namespaceService"/> <ref bean="namespaceService"/>
</property> </property>
<property name="authenticationComponent"> <property name="authenticationContext">
<ref bean="authenticationComponent" /> <ref bean="authenticationContext" />
</property> </property>
<property name="allowWrite"> <property name="allowWrite">
<value>${server.transaction.allow-writes}</value> <value>${server.transaction.allow-writes}</value>

View File

@@ -221,8 +221,8 @@
lazy-init="true" lazy-init="true"
init-method="register"> init-method="register">
<property name="authenticationComponent"> <property name="authenticationContext">
<ref bean="authenticationComponent"/> <ref bean="authenticationContext"/>
</property> </property>
<property name="attributeService"> <property name="attributeService">
<ref bean="AttributeService"/> <ref bean="AttributeService"/>

View File

@@ -10,7 +10,7 @@
--> -->
<property name="nodeService" ref="dbNodeServiceImpl"/> <!-- TODO - go direct, until we expose deleteStore via public NodeService API --> <property name="nodeService" ref="dbNodeServiceImpl"/> <!-- TODO - go direct, until we expose deleteStore via public NodeService API -->
<property name="dictionaryComponent" ref="dictionaryService"/> <property name="dictionaryComponent" ref="dictionaryService"/>
<property name="authenticationComponent" ref="authenticationComponent"/> <property name="authenticationContext" ref="authenticationContext"/>
<property name="repoAdminService" ref="RepoAdminService"/> <property name="repoAdminService" ref="RepoAdminService"/>
<property name="tenantService" ref="tenantService"/> <property name="tenantService" ref="tenantService"/>
<property name="transactionService" ref="transactionComponent"/> <property name="transactionService" ref="transactionComponent"/>

View File

@@ -80,7 +80,7 @@
<property name="contentService"><ref bean="ContentService" /></property> <property name="contentService"><ref bean="ContentService" /></property>
<property name="mimetypeService"><ref bean="MimetypeService" /></property> <property name="mimetypeService"><ref bean="MimetypeService" /></property>
<property name="permissionService"><ref bean="permissionService"/></property> <property name="permissionService"><ref bean="permissionService"/></property>
<property name="authenticationComponent"><ref bean="authenticationComponent"/></property> <property name="authenticationContext"><ref bean="authenticationContext"/></property>
<property name="authenticationService"><ref bean="authenticationService"/></property> <property name="authenticationService"><ref bean="authenticationService"/></property>
<property name="fileFolderService"><ref bean="FileFolderService" /></property> <property name="fileFolderService"><ref bean="FileFolderService" /></property>
<property name="serviceRegistry"><ref bean="ServiceRegistry"/></property> <property name="serviceRegistry"><ref bean="ServiceRegistry"/></property>

View File

@@ -66,8 +66,8 @@
<property name="nodeService"> <property name="nodeService">
<ref bean="nodeService"/> <ref bean="nodeService"/>
</property> </property>
<property name="authenticationComponent"> <property name="authenticationContext">
<ref bean="authenticationComponent" /> <ref bean="authenticationContext" />
</property> </property>
<property name="tenantAdminService"> <property name="tenantAdminService">
<ref bean="tenantAdminService" /> <ref bean="tenantAdminService" />

View File

@@ -42,7 +42,7 @@
<property name="contentService" ref="ContentService"/> <property name="contentService" ref="ContentService"/>
<property name="personService" ref="PersonService"/> <property name="personService" ref="PersonService"/>
<property name="permissionService" ref="PermissionService"/> <property name="permissionService" ref="PermissionService"/>
<property name="authenticationComponent" ref="authenticationComponent"/> <property name="authenticationContext" ref="authenticationContext"/>
</bean> </bean>
<bean id="preferenceServiceScript" parent="baseJavaScriptExtension" class="org.alfresco.repo.preference.script.ScriptPreferenceService"> <bean id="preferenceServiceScript" parent="baseJavaScriptExtension" class="org.alfresco.repo.preference.script.ScriptPreferenceService">

View File

@@ -65,7 +65,7 @@
<property name="searchService" ref="SearchService"/> <property name="searchService" ref="SearchService"/>
<property name="namespaceService" ref="NamespaceService"/> <property name="namespaceService" ref="NamespaceService"/>
<property name="permissionService" ref="PermissionService"/> <property name="permissionService" ref="PermissionService"/>
<property name="authenticationComponent" ref="authenticationComponent"/> <property name="authenticationContext" ref="authenticationContext"/>
<property name="personService" ref="PersonService"/> <property name="personService" ref="PersonService"/>
<property name="activityService" ref="activityService"/> <property name="activityService" ref="activityService"/>
<property name="taggingService" ref="TaggingService"/> <property name="taggingService" ref="TaggingService"/>

View File

@@ -24,7 +24,7 @@
<property name="nodeService" ref="nodeService"/> <property name="nodeService" ref="nodeService"/>
<property name="policyComponent" ref="policyComponent"/> <property name="policyComponent" ref="policyComponent"/>
<property name="usageService" ref="usageService"/> <property name="usageService" ref="usageService"/>
<property name="authenticationComponent" ref="authenticationComponent"/> <property name="authenticationContext" ref="authenticationContext"/>
<property name="tenantService" ref="tenantService"/> <property name="tenantService" ref="tenantService"/>
<property name="enabled"> <property name="enabled">
<value>${system.usages.enabled}</value> <value>${system.usages.enabled}</value>

View File

@@ -9,7 +9,7 @@
<bean id="workflowDeployer" class="org.alfresco.repo.workflow.WorkflowDeployer" abstract="true"> <bean id="workflowDeployer" class="org.alfresco.repo.workflow.WorkflowDeployer" abstract="true">
<property name="transactionService" ref="transactionService"/> <property name="transactionService" ref="transactionService"/>
<property name="authenticationComponent" ref="authenticationComponent" /> <property name="authenticationContext" ref="authenticationContext" />
<property name="workflowService" ref="WorkflowService" /> <property name="workflowService" ref="WorkflowService" />
<property name="dictionaryDAO" ref="dictionaryDAO"/> <property name="dictionaryDAO" ref="dictionaryDAO"/>
<property name="allowWrite"> <property name="allowWrite">

File diff suppressed because it is too large Load Diff

View File

@@ -37,7 +37,7 @@ import org.alfresco.model.ContentModel;
import org.alfresco.repo.node.NodeServicePolicies; import org.alfresco.repo.node.NodeServicePolicies;
import org.alfresco.repo.policy.JavaBehaviour; import org.alfresco.repo.policy.JavaBehaviour;
import org.alfresco.repo.policy.PolicyComponent; import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.repo.transaction.AlfrescoTransactionSupport; import org.alfresco.repo.transaction.AlfrescoTransactionSupport;
import org.alfresco.repo.transaction.TransactionListenerAdapter; import org.alfresco.repo.transaction.TransactionListenerAdapter;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
@@ -516,8 +516,8 @@ public class NodeMonitor extends TransactionListenerAdapter
// Use the system user as the authenticated context for the node monitor // Use the system user as the authenticated context for the node monitor
AuthenticationComponent authComponent = m_filesysDriver.getAuthComponent(); AuthenticationContext authenticationContext = m_filesysDriver.getAuthenticationContext();
authComponent.setCurrentUser( authComponent.getSystemUserName()); authenticationContext.setSystemUserAsCurrentUser();
// Loop until shutdown // Loop until shutdown

View File

@@ -1,148 +1,148 @@
/* /*
* Copyright (C) 2005-2007 Alfresco Software Limited. * Copyright (C) 2005-2007 Alfresco Software Limited.
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2 * as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. * of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* As a special exception to the terms and conditions of version 2.0 of * As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre * the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's * and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have recieved a copy of the text describing * FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here: * the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing" * http://www.alfresco.com/legal/licensing"
*/ */
package org.alfresco.jcr.test; package org.alfresco.jcr.test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Properties; import java.util.Properties;
import org.alfresco.repo.importer.ImporterBootstrap; import org.alfresco.repo.importer.ImporterBootstrap;
import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.repo.security.authentication.MutableAuthenticationDao; import org.alfresco.repo.security.authentication.MutableAuthenticationDao;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.ServiceRegistry; import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.security.PermissionService; import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.cmr.view.ImporterService; import org.alfresco.service.cmr.view.ImporterService;
import org.alfresco.service.namespace.NamespaceService; import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.transaction.TransactionService; import org.alfresco.service.transaction.TransactionService;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestData public class TestData
{ {
public static final String TEST_WORKSPACE = "test"; public static final String TEST_WORKSPACE = "test";
/** /**
* Generate Test Workspace within Repository * Generate Test Workspace within Repository
* *
* @param args * @param args
*/ */
public static void main(String[] args) public static void main(String[] args)
{ {
ApplicationContext context = new ClassPathXmlApplicationContext("org/alfresco/jcr/test/test-context.xml"); ApplicationContext context = new ClassPathXmlApplicationContext("org/alfresco/jcr/test/test-context.xml");
generateTestData(context, TEST_WORKSPACE); generateTestData(context, TEST_WORKSPACE);
System.out.println("Generated TCK test data to workspace: " + TEST_WORKSPACE); System.out.println("Generated TCK test data to workspace: " + TEST_WORKSPACE);
System.exit(0); System.exit(0);
} }
/** /**
* Bootstrap Repository with JCR Test Data * Bootstrap Repository with JCR Test Data
* *
* @param applicationContext * @param applicationContext
* @param workspaceName * @param workspaceName
*/ */
public static void generateTestData(final ApplicationContext applicationContext, String workspaceName) public static void generateTestData(final ApplicationContext applicationContext, String workspaceName)
{ {
final ServiceRegistry serviceRegistry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY); final ServiceRegistry serviceRegistry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY);
TransactionService transactionService = serviceRegistry.getTransactionService(); TransactionService transactionService = serviceRegistry.getTransactionService();
RetryingTransactionCallback<Object> createUserWork = new RetryingTransactionCallback<Object>() RetryingTransactionCallback<Object> createUserWork = new RetryingTransactionCallback<Object>()
{ {
public Object execute() throws Exception public Object execute() throws Exception
{ {
// Bootstrap Users // Bootstrap Users
MutableAuthenticationDao authDAO = (MutableAuthenticationDao) applicationContext.getBean("authenticationDao"); MutableAuthenticationDao authDAO = (MutableAuthenticationDao) applicationContext.getBean("authenticationDao");
if (authDAO.userExists("superuser") == false) if (authDAO.userExists("superuser") == false)
{ {
authDAO.createUser("superuser", "".toCharArray()); authDAO.createUser("superuser", "".toCharArray());
} }
if (authDAO.userExists("user") == false) if (authDAO.userExists("user") == false)
{ {
authDAO.createUser("user", "".toCharArray()); authDAO.createUser("user", "".toCharArray());
} }
if (authDAO.userExists("anonymous") == false) if (authDAO.userExists("anonymous") == false)
{ {
authDAO.createUser("anonymous", "".toCharArray()); authDAO.createUser("anonymous", "".toCharArray());
} }
return null; return null;
} }
}; };
transactionService.getRetryingTransactionHelper().doInTransaction(createUserWork); transactionService.getRetryingTransactionHelper().doInTransaction(createUserWork);
try try
{ {
AuthenticationComponent authenticationComponent = (AuthenticationComponent)applicationContext.getBean("authenticationComponent"); AuthenticationContext authenticationContext = (AuthenticationContext)applicationContext.getBean("authenticationContext");
authenticationComponent.setSystemUserAsCurrentUser(); authenticationContext.setSystemUserAsCurrentUser();
try try
{ {
// Bootstrap Workspace Test Data // Bootstrap Workspace Test Data
StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, workspaceName); StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, workspaceName);
ImporterBootstrap bootstrap = new ImporterBootstrap(); ImporterBootstrap bootstrap = new ImporterBootstrap();
bootstrap.setAuthenticationComponent((AuthenticationComponent) applicationContext.getBean("authenticationComponent")); bootstrap.setAuthenticationContext((AuthenticationContext) applicationContext.getBean("authenticationContext"));
bootstrap.setImporterService((ImporterService) applicationContext.getBean(ServiceRegistry.IMPORTER_SERVICE.getLocalName())); bootstrap.setImporterService((ImporterService) applicationContext.getBean(ServiceRegistry.IMPORTER_SERVICE.getLocalName()));
bootstrap.setNodeService((NodeService) applicationContext.getBean(ServiceRegistry.NODE_SERVICE.getLocalName())); bootstrap.setNodeService((NodeService) applicationContext.getBean(ServiceRegistry.NODE_SERVICE.getLocalName()));
bootstrap.setNamespaceService((NamespaceService) applicationContext.getBean(ServiceRegistry.NAMESPACE_SERVICE.getLocalName())); bootstrap.setNamespaceService((NamespaceService) applicationContext.getBean(ServiceRegistry.NAMESPACE_SERVICE.getLocalName()));
bootstrap.setTransactionService((TransactionService) applicationContext.getBean(ServiceRegistry.TRANSACTION_SERVICE.getLocalName())); bootstrap.setTransactionService((TransactionService) applicationContext.getBean(ServiceRegistry.TRANSACTION_SERVICE.getLocalName()));
bootstrap.setStoreUrl(storeRef.toString()); bootstrap.setStoreUrl(storeRef.toString());
List<Properties> views = new ArrayList<Properties>(); List<Properties> views = new ArrayList<Properties>();
Properties testView = new Properties(); Properties testView = new Properties();
testView.setProperty("path", "/"); testView.setProperty("path", "/");
testView.setProperty("location", "org/alfresco/jcr/test/testData.xml"); testView.setProperty("location", "org/alfresco/jcr/test/testData.xml");
views.add(testView); views.add(testView);
bootstrap.setBootstrapViews(views); bootstrap.setBootstrapViews(views);
bootstrap.bootstrap(); bootstrap.bootstrap();
// Bootstrap clears security context // Bootstrap clears security context
authenticationComponent.setSystemUserAsCurrentUser(); authenticationContext.setSystemUserAsCurrentUser();
PermissionService permissionService = (PermissionService)applicationContext.getBean(ServiceRegistry.PERMISSIONS_SERVICE.getLocalName()); PermissionService permissionService = (PermissionService)applicationContext.getBean(ServiceRegistry.PERMISSIONS_SERVICE.getLocalName());
NodeService nodeService = (NodeService)applicationContext.getBean(ServiceRegistry.NODE_SERVICE.getLocalName()); NodeService nodeService = (NodeService)applicationContext.getBean(ServiceRegistry.NODE_SERVICE.getLocalName());
// permissionService.setPermission(nodeService.getRootNode(storeRef), PermissionService.ALL_AUTHORITIES, PermissionService.ALL_PERMISSIONS, true); // permissionService.setPermission(nodeService.getRootNode(storeRef), PermissionService.ALL_AUTHORITIES, PermissionService.ALL_PERMISSIONS, true);
permissionService.setPermission(nodeService.getRootNode(storeRef), "superuser", PermissionService.ALL_PERMISSIONS, true); permissionService.setPermission(nodeService.getRootNode(storeRef), "superuser", PermissionService.ALL_PERMISSIONS, true);
permissionService.setPermission(nodeService.getRootNode(storeRef), "anonymous", PermissionService.READ, true); permissionService.setPermission(nodeService.getRootNode(storeRef), "anonymous", PermissionService.READ, true);
permissionService.setPermission(nodeService.getRootNode(storeRef), "user", PermissionService.READ, true); permissionService.setPermission(nodeService.getRootNode(storeRef), "user", PermissionService.READ, true);
permissionService.setPermission(nodeService.getRootNode(storeRef), "user", PermissionService.WRITE, true); permissionService.setPermission(nodeService.getRootNode(storeRef), "user", PermissionService.WRITE, true);
} }
finally finally
{ {
authenticationComponent.clearCurrentSecurityContext(); authenticationContext.clearCurrentSecurityContext();
} }
} }
catch (RuntimeException e) catch (RuntimeException e)
{ {
System.out.println("Exception: " + e); System.out.println("Exception: " + e);
e.printStackTrace(); e.printStackTrace();
throw e; throw e;
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -34,7 +34,7 @@ import org.alfresco.repo.action.AsynchronousActionExecutionQueuePolicies.OnAsync
import org.alfresco.repo.policy.ClassPolicyDelegate; import org.alfresco.repo.policy.ClassPolicyDelegate;
import org.alfresco.repo.policy.PolicyComponent; import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.rule.RuleServiceImpl; import org.alfresco.repo.rule.RuleServiceImpl;
import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.transaction.AlfrescoTransactionSupport; import org.alfresco.repo.transaction.AlfrescoTransactionSupport;
@@ -62,7 +62,7 @@ public class AsynchronousActionExecutionQueueImpl implements AsynchronousActionE
/** Services */ /** Services */
private ThreadPoolExecutor threadPoolExecutor; private ThreadPoolExecutor threadPoolExecutor;
private TransactionService transactionService; private TransactionService transactionService;
private AuthenticationComponent authenticationComponent; private AuthenticationContext authenticationContext;
private PolicyComponent policyComponent; private PolicyComponent policyComponent;
private NodeService nodeService; private NodeService nodeService;
@@ -109,11 +109,11 @@ public class AsynchronousActionExecutionQueueImpl implements AsynchronousActionE
/** /**
* Set the authentication component * Set the authentication component
* *
* @param authenticationComponent the authentication component * @param authenticationContext the authentication component
*/ */
public void setAuthenticationComponent(AuthenticationComponent authenticationComponent) public void setAuthenticationContext(AuthenticationContext authenticationContext)
{ {
this.authenticationComponent = authenticationComponent; this.authenticationContext = authenticationContext;
} }
/** /**

File diff suppressed because it is too large Load Diff

View File

@@ -1,199 +1,198 @@
/* /*
* Copyright (C) 2005-2007 Alfresco Software Limited. * Copyright (C) 2005-2007 Alfresco Software Limited.
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2 * as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. * of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* As a special exception to the terms and conditions of version 2.0 of * As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre * the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's * and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have recieved a copy of the text describing * FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here: * the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing" * http://www.alfresco.com/legal/licensing"
*/ */
package org.alfresco.repo.admin.patch; package org.alfresco.repo.admin.patch;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.alfresco.error.AlfrescoRuntimeException; import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.domain.AppliedPatch; import org.alfresco.repo.domain.AppliedPatch;
import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.service.cmr.admin.PatchException; import org.alfresco.service.cmr.admin.PatchException;
import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.search.SearchService; import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.AuthorityService; import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.NamespaceService; import org.alfresco.service.transaction.TransactionService;
import org.alfresco.service.transaction.TransactionService; import org.alfresco.util.ApplicationContextHelper;
import org.alfresco.util.ApplicationContextHelper; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContext;
/**
/** * @see org.alfresco.repo.admin.patch.Patch
* @see org.alfresco.repo.admin.patch.Patch * @see org.alfresco.repo.admin.patch.AbstractPatch
* @see org.alfresco.repo.admin.patch.AbstractPatch * @see org.alfresco.repo.admin.patch.PatchService
* @see org.alfresco.repo.admin.patch.PatchService *
* * @author Derek Hulley
* @author Derek Hulley */
*/ public class PatchTest extends TestCase
public class PatchTest extends TestCase {
{ private static final ApplicationContext ctx = ApplicationContextHelper.getApplicationContext();
private static final ApplicationContext ctx = ApplicationContextHelper.getApplicationContext();
private TransactionService transactionService;
private TransactionService transactionService; private NamespaceService namespaceService;
private NamespaceService namespaceService; private NodeService nodeService;
private NodeService nodeService; private SearchService searchService;
private SearchService searchService; private AuthenticationContext authenticationContext;
private AuthenticationComponent authenticationComponent; private PatchService patchService;
private PatchService patchService; private PatchDaoService patchDaoComponent;
private PatchDaoService patchDaoComponent;
public PatchTest(String name)
public PatchTest(String name) {
{ super(name);
super(name); }
}
public void setUp() throws Exception
public void setUp() throws Exception {
{ transactionService = (TransactionService) ctx.getBean("transactionComponent");
transactionService = (TransactionService) ctx.getBean("transactionComponent"); namespaceService = (NamespaceService) ctx.getBean("namespaceService");
namespaceService = (NamespaceService) ctx.getBean("namespaceService"); nodeService = (NodeService) ctx.getBean("nodeService");
nodeService = (NodeService) ctx.getBean("nodeService"); searchService = (SearchService) ctx.getBean("searchService");
searchService = (SearchService) ctx.getBean("searchService"); authenticationContext = (AuthenticationContext) ctx.getBean("authenticationContext");
authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
patchService = (PatchService) ctx.getBean("PatchService");
patchService = (PatchService) ctx.getBean("PatchService"); patchDaoComponent = (PatchDaoService) ctx.getBean("patchDaoComponent");
patchDaoComponent = (PatchDaoService) ctx.getBean("patchDaoComponent");
// get the patches to play with
// get the patches to play with patchService.registerPatch((Patch)ctx.getBean("patch.sample.02"));
patchService.registerPatch((Patch)ctx.getBean("patch.sample.02")); patchService.registerPatch((Patch)ctx.getBean("patch.sample.01"));
patchService.registerPatch((Patch)ctx.getBean("patch.sample.01")); }
}
public void testSetup() throws Exception
public void testSetup() throws Exception {
{ assertNotNull(transactionService);
assertNotNull(transactionService); assertNotNull(patchService);
assertNotNull(patchService); assertNotNull(patchDaoComponent);
assertNotNull(patchDaoComponent); }
}
private SamplePatch constructSamplePatch(boolean mustFail)
private SamplePatch constructSamplePatch(boolean mustFail) {
{ SamplePatch patch = new SamplePatch(mustFail, transactionService);
SamplePatch patch = new SamplePatch(mustFail, transactionService); patch.setNamespaceService(namespaceService);
patch.setNamespaceService(namespaceService); patch.setNodeService(nodeService);
patch.setNodeService(nodeService); patch.setSearchService(searchService);
patch.setSearchService(searchService); patch.setAuthenticationContext(authenticationContext);
patch.setAuthenticationComponent(authenticationComponent); // done
// done return patch;
return patch; }
}
public void testSimplePatchSuccess() throws Exception
public void testSimplePatchSuccess() throws Exception {
{ Patch patch = constructSamplePatch(false);
Patch patch = constructSamplePatch(false); String report = patch.apply();
String report = patch.apply(); // check that the report was generated
// check that the report was generated assertEquals("Patch report incorrect", SamplePatch.MSG_SUCCESS, report);
assertEquals("Patch report incorrect", SamplePatch.MSG_SUCCESS, report); }
}
public void testPatchReapplication()
public void testPatchReapplication() {
{ // successfully apply a patch
// successfully apply a patch Patch patch = constructSamplePatch(false);
Patch patch = constructSamplePatch(false); patch.apply();
patch.apply(); // check that the patch cannot be reapplied
// check that the patch cannot be reapplied try
try {
{ patch.apply();
patch.apply(); fail("AbstractPatch failed to prevent reapplication");
fail("AbstractPatch failed to prevent reapplication"); }
} catch (AlfrescoRuntimeException e)
catch (AlfrescoRuntimeException e) {
{ // expected
// expected }
}
// apply an unsuccessful patch
// apply an unsuccessful patch patch = constructSamplePatch(true);
patch = constructSamplePatch(true); try
try {
{ patch.apply();
patch.apply(); fail("Failed patch didn't throw PatchException");
fail("Failed patch didn't throw PatchException"); }
} catch (PatchException e)
catch (PatchException e) {
{ // expected
// expected }
} // repeat
// repeat try
try {
{ patch.apply();
patch.apply(); fail("Reapplication of failed patch didn't throw PatchException");
fail("Reapplication of failed patch didn't throw PatchException"); }
} catch (PatchException e)
catch (PatchException e) {
{ // expected
// expected }
} }
}
public void testApplyOutstandingPatches() throws Exception
public void testApplyOutstandingPatches() throws Exception {
{ // apply outstanding patches
// apply outstanding patches boolean success = patchService.applyOutstandingPatches();
boolean success = patchService.applyOutstandingPatches(); assertTrue(success);
assertTrue(success); // get applied patches
// get applied patches List<AppliedPatch> appliedPatches = patchDaoComponent.getAppliedPatches();
List<AppliedPatch> appliedPatches = patchDaoComponent.getAppliedPatches(); // check that the patch application was recorded
// check that the patch application was recorded boolean found01 = false;
boolean found01 = false; boolean found02 = false;
boolean found02 = false; for (AppliedPatch appliedPatch : appliedPatches)
for (AppliedPatch appliedPatch : appliedPatches) {
{ if (appliedPatch.getId().equals("Sample01"))
if (appliedPatch.getId().equals("Sample01")) {
{ found01 = true;
found01 = true; assertTrue("Patch info didn't indicate success: " + appliedPatch, appliedPatch.getSucceeded());
assertTrue("Patch info didn't indicate success: " + appliedPatch, appliedPatch.getSucceeded()); }
} else if (appliedPatch.getId().equals("Sample02"))
else if (appliedPatch.getId().equals("Sample02")) {
{ found02 = true;
found02 = true; assertTrue("Patch info didn't indicate success: " + appliedPatch, appliedPatch.getSucceeded());
assertTrue("Patch info didn't indicate success: " + appliedPatch, appliedPatch.getSucceeded()); }
} }
} assertTrue("Sample 01 not in list of applied patches", found01);
assertTrue("Sample 01 not in list of applied patches", found01); assertTrue("Sample 02 not in list of applied patches", found02);
assertTrue("Sample 02 not in list of applied patches", found02); }
}
public void testGetPatchesByDate() throws Exception
public void testGetPatchesByDate() throws Exception {
{ // ensure that there are some applied patches
// ensure that there are some applied patches testApplyOutstandingPatches();
testApplyOutstandingPatches(); // get the number of applied patches
// get the number of applied patches List<AppliedPatch> appliedPatches = patchDaoComponent.getAppliedPatches();
List<AppliedPatch> appliedPatches = patchDaoComponent.getAppliedPatches(); assertTrue("Expected at least 2 applied patches", appliedPatches.size() >= 2);
assertTrue("Expected at least 2 applied patches", appliedPatches.size() >= 2);
// now requery using null dates
// now requery using null dates List<PatchInfo> appliedPatchesAllDates = patchService.getPatches(null, null);
List<PatchInfo> appliedPatchesAllDates = patchService.getPatches(null, null); assertEquals("Applied patches by all dates doesn't match all applied patches",
assertEquals("Applied patches by all dates doesn't match all applied patches", appliedPatches.size(), appliedPatchesAllDates.size());
appliedPatches.size(), appliedPatchesAllDates.size());
// make sure that the objects are not connected to the persistence layer
// make sure that the objects are not connected to the persistence layer PatchInfo disconnectedObject = appliedPatchesAllDates.get(0);
PatchInfo disconnectedObject = appliedPatchesAllDates.get(0); AppliedPatch persistedObject = patchDaoComponent.getAppliedPatch(disconnectedObject.getId());
AppliedPatch persistedObject = patchDaoComponent.getAppliedPatch(disconnectedObject.getId()); assertNotSame("Instances should not be shared between evicted and cached objects",
assertNotSame("Instances should not be shared between evicted and cached objects", disconnectedObject, persistedObject);
disconnectedObject, persistedObject);
// perform another query with dates that should return no results
// perform another query with dates that should return no results List<PatchInfo> appliedPatchesFutureDates = patchService.getPatches(new Date(), new Date());
List<PatchInfo> appliedPatchesFutureDates = patchService.getPatches(new Date(), new Date()); assertEquals("Query returned results for dates when no patches should exist", 0, appliedPatchesFutureDates.size());
assertEquals("Query returned results for dates when no patches should exist", 0, appliedPatchesFutureDates.size()); }
} }
}

View File

@@ -181,7 +181,7 @@ public class EmailTemplatesContentPatch extends AbstractPatch
return null; return null;
} }
}; };
AuthenticationUtil.runAs(importRunAs, authenticationComponent.getSystemUserName()); AuthenticationUtil.runAs(importRunAs, authenticationContext.getSystemUserName());
// output a message to describe the result // output a message to describe the result
return I18NUtil.getMessage(MSG_CREATED); return I18NUtil.getMessage(MSG_CREATED);

View File

@@ -232,7 +232,7 @@ public class ScriptsFolderPatch extends AbstractPatch
return null; return null;
} }
}; };
AuthenticationUtil.runAs(importRunAs, authenticationComponent.getSystemUserName()); AuthenticationUtil.runAs(importRunAs, authenticationContext.getSystemUserName());
msg = I18NUtil.getMessage(MSG_CREATED, scriptsFolderNodeRef); msg = I18NUtil.getMessage(MSG_CREATED, scriptsFolderNodeRef);
} }

View File

@@ -116,10 +116,10 @@ public abstract class AVMNodeImpl implements AVMNode, Serializable
fIsRoot = false; fIsRoot = false;
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
String user = String user =
RawServices.Instance().getAuthenticationComponent().getCurrentUserName(); RawServices.Instance().getAuthenticationContext().getCurrentUserName();
if (user == null) if (user == null)
{ {
user = RawServices.Instance().getAuthenticationComponent().getSystemUserName(); user = RawServices.Instance().getAuthenticationContext().getSystemUserName();
} }
fBasicAttributes = new BasicAttributesImpl(user, fBasicAttributes = new BasicAttributesImpl(user,
user, user,
@@ -332,10 +332,10 @@ public abstract class AVMNodeImpl implements AVMNode, Serializable
checkReadOnly(); checkReadOnly();
} }
String user = String user =
RawServices.Instance().getAuthenticationComponent().getCurrentUserName(); RawServices.Instance().getAuthenticationContext().getCurrentUserName();
if (user == null) if (user == null)
{ {
user = RawServices.Instance().getAuthenticationComponent().getSystemUserName(); user = RawServices.Instance().getAuthenticationContext().getSystemUserName();
} }
fBasicAttributes.setModDate(System.currentTimeMillis()); fBasicAttributes.setModDate(System.currentTimeMillis());
fBasicAttributes.setLastModifier(user); fBasicAttributes.setLastModifier(user);

File diff suppressed because it is too large Load Diff

View File

@@ -5,7 +5,7 @@ package org.alfresco.repo.avm.util;
import org.alfresco.repo.avm.LookupCache; import org.alfresco.repo.avm.LookupCache;
import org.alfresco.repo.content.ContentStore; import org.alfresco.repo.content.ContentStore;
import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.service.cmr.dictionary.DictionaryService; import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.repository.ContentService; import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.MimetypeService; import org.alfresco.service.cmr.repository.MimetypeService;
@@ -30,9 +30,9 @@ public class RawServices implements ApplicationContextAware
private ApplicationContext fContext; private ApplicationContext fContext;
/** /**
* The AuthenticationComponent. * The AuthenticationContext.
*/ */
private AuthenticationComponent fAuthenticationComponent; private AuthenticationContext fAuthenticationContext;
/** /**
* The Content Service. * The Content Service.
@@ -82,14 +82,14 @@ public class RawServices implements ApplicationContextAware
fContext = applicationContext; fContext = applicationContext;
} }
public AuthenticationComponent getAuthenticationComponent() public AuthenticationContext getAuthenticationContext()
{ {
if (fAuthenticationComponent == null) if (fAuthenticationContext == null)
{ {
fAuthenticationComponent = fAuthenticationContext =
(AuthenticationComponent)fContext.getBean("authenticationComponent"); (AuthenticationContext)fContext.getBean("authenticationContext");
} }
return fAuthenticationComponent; return fAuthenticationContext;
} }
public ContentService getContentService() public ContentService getContentService()

View File

@@ -1,260 +1,255 @@
/* /*
* Copyright (C) 2005-2007 Alfresco Software Limited. * Copyright (C) 2005-2007 Alfresco Software Limited.
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2 * as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. * of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* As a special exception to the terms and conditions of version 2.0 of * As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre * the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's * and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have recieved a copy of the text describing * FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here: * the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing" * http://www.alfresco.com/legal/licensing"
*/ */
package org.alfresco.repo.importer; package org.alfresco.repo.importer;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.Reader; import java.io.Reader;
import java.io.Writer; import java.io.Writer;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import javax.transaction.UserTransaction; import javax.transaction.UserTransaction;
import org.alfresco.repo.cache.SimpleCache; import org.alfresco.repo.cache.SimpleCache;
import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.SearchService; import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.view.ImporterBinding; import org.alfresco.service.cmr.view.ImporterBinding;
import org.alfresco.service.cmr.view.ImporterService; import org.alfresco.service.cmr.view.ImporterService;
import org.alfresco.service.cmr.view.Location; import org.alfresco.service.cmr.view.Location;
import org.alfresco.service.namespace.NamespacePrefixResolver; import org.alfresco.service.namespace.NamespacePrefixResolver;
import org.alfresco.service.namespace.QName; import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService; import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.TempFileProvider; import org.alfresco.util.TempFileProvider;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.dom4j.io.OutputFormat; import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter; import org.dom4j.io.XMLWriter;
public class ExportSourceImporter implements ImporterJobSPI public class ExportSourceImporter implements ImporterJobSPI
{ {
private static Log logger = LogFactory.getLog(ExportSourceImporter.class); private static Log logger = LogFactory.getLog(ExportSourceImporter.class);
private ImporterService importerService; private ImporterService importerService;
private ExportSource exportSource; private ExportSource exportSource;
private StoreRef storeRef; private StoreRef storeRef;
private String path; private String path;
private boolean clearAllChildren; private boolean clearAllChildren;
private NodeService nodeService; private NodeService nodeService;
private SearchService searchService; private SearchService searchService;
private NamespacePrefixResolver namespacePrefixResolver; private NamespacePrefixResolver namespacePrefixResolver;
private TransactionService transactionService; private TransactionService transactionService;
private Set<SimpleCache> caches; private Set<SimpleCache> caches;
public ExportSourceImporter() public ExportSourceImporter()
{ {
super(); super();
} }
public void setImporterService(ImporterService importerService) public void setImporterService(ImporterService importerService)
{ {
this.importerService = importerService; this.importerService = importerService;
} }
public void setExportSource(ExportSource exportSource) public void setExportSource(ExportSource exportSource)
{ {
this.exportSource = exportSource; this.exportSource = exportSource;
} }
public void setClearAllChildren(boolean clearAllChildren) public void setClearAllChildren(boolean clearAllChildren)
{ {
this.clearAllChildren = clearAllChildren; this.clearAllChildren = clearAllChildren;
} }
public void setPath(String path) public void setPath(String path)
{ {
this.path = path; this.path = path;
} }
public void setStoreRef(String storeRef) public void setStoreRef(String storeRef)
{ {
this.storeRef = new StoreRef(storeRef); this.storeRef = new StoreRef(storeRef);
} }
public void setTransactionService(TransactionService transactionService) public void setTransactionService(TransactionService transactionService)
{ {
this.transactionService = transactionService; this.transactionService = transactionService;
} }
public void setNamespacePrefixResolver(NamespacePrefixResolver namespacePrefixResolver) public void setNamespacePrefixResolver(NamespacePrefixResolver namespacePrefixResolver)
{ {
this.namespacePrefixResolver = namespacePrefixResolver; this.namespacePrefixResolver = namespacePrefixResolver;
} }
public void setNodeService(NodeService nodeService) public void setNodeService(NodeService nodeService)
{ {
this.nodeService = nodeService; this.nodeService = nodeService;
} }
public void setCaches(Set<SimpleCache> caches) public void setCaches(Set<SimpleCache> caches)
{ {
this.caches = caches; this.caches = caches;
} }
public void setAuthenticationComponent(AuthenticationComponent authenticationComponent) public void setSearchService(SearchService searchService)
{ {
logger.warn("Bearn property 'authenticationComponent' no longer used on 'ExportSourceImporter'."); this.searchService = searchService;
} }
public void setSearchService(SearchService searchService) @SuppressWarnings("unchecked")
{ public void doImport()
this.searchService = searchService; {
} UserTransaction userTransaction = null;
try
@SuppressWarnings("unchecked") {
public void doImport() AuthenticationUtil.pushAuthentication();
{ userTransaction = transactionService.getUserTransaction();
UserTransaction userTransaction = null; userTransaction.begin();
try AuthenticationUtil.setRunAsUserSystem();
{ if (clearAllChildren)
AuthenticationUtil.pushAuthentication(); {
userTransaction = transactionService.getUserTransaction(); List<NodeRef> refs = searchService.selectNodes(nodeService.getRootNode(storeRef), path, null,
userTransaction.begin(); namespacePrefixResolver, false);
AuthenticationUtil.setRunAsUserSystem(); for (NodeRef ref : refs)
if (clearAllChildren) {
{ for (ChildAssociationRef car : nodeService.getChildAssocs(ref))
List<NodeRef> refs = searchService.selectNodes(nodeService.getRootNode(storeRef), path, null, {
namespacePrefixResolver, false); nodeService.deleteNode(car.getChildRef());
for (NodeRef ref : refs) }
{ }
for (ChildAssociationRef car : nodeService.getChildAssocs(ref)) }
{
nodeService.deleteNode(car.getChildRef()); if (caches != null)
} {
} for (SimpleCache cache : caches)
} {
if (caches != null) cache.clear();
{ }
for (SimpleCache cache : caches) }
{
File tempFile = TempFileProvider.createTempFile("ExportSourceImporter-", ".xml");
cache.clear(); Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8"));
} XMLWriter xmlWriter = createXMLExporter(writer);
} exportSource.generateExport(xmlWriter);
xmlWriter.close();
File tempFile = TempFileProvider.createTempFile("ExportSourceImporter-", ".xml");
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8")); Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(tempFile), "UTF-8"));
XMLWriter xmlWriter = createXMLExporter(writer);
exportSource.generateExport(xmlWriter); Location location = new Location(storeRef);
xmlWriter.close(); location.setPath(path);
Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(tempFile), "UTF-8")); importerService.importView(reader, location, REPLACE_BINDING, null);
reader.close();
Location location = new Location(storeRef);
location.setPath(path); if (caches != null)
{
importerService.importView(reader, location, REPLACE_BINDING, null); for (SimpleCache cache : caches)
reader.close(); {
cache.clear();
if (caches != null) }
{ }
for (SimpleCache cache : caches)
{ userTransaction.commit();
cache.clear(); }
} catch (Throwable t)
} {
try
userTransaction.commit(); {
} if (userTransaction != null)
catch (Throwable t) {
{ userTransaction.rollback();
try }
{ }
if (userTransaction != null) catch (Exception ex)
{ {
userTransaction.rollback(); }
} throw new ExportSourceImporterException("Failed to import", t);
} }
catch (Exception ex) finally
{ {
} AuthenticationUtil.popAuthentication();
throw new ExportSourceImporterException("Failed to import", t); }
} }
finally
{ private XMLWriter createXMLExporter(Writer writer)
AuthenticationUtil.popAuthentication(); {
} // Define output format
} OutputFormat format = OutputFormat.createPrettyPrint();
format.setNewLineAfterDeclaration(false);
private XMLWriter createXMLExporter(Writer writer) format.setIndentSize(3);
{ format.setEncoding("UTF-8");
// Define output format
OutputFormat format = OutputFormat.createPrettyPrint(); // Construct an XML Exporter
format.setNewLineAfterDeclaration(false);
format.setIndentSize(3); XMLWriter xmlWriter = new XMLWriter(writer, format);
format.setEncoding("UTF-8"); return xmlWriter;
}
// Construct an XML Exporter
private static ImporterBinding REPLACE_BINDING = new ImporterBinding()
XMLWriter xmlWriter = new XMLWriter(writer, format); {
return xmlWriter;
} public UUID_BINDING getUUIDBinding()
{
private static ImporterBinding REPLACE_BINDING = new ImporterBinding() return UUID_BINDING.UPDATE_EXISTING;
{ }
public UUID_BINDING getUUIDBinding() public String getValue(String key)
{ {
return UUID_BINDING.UPDATE_EXISTING; return null;
} }
public String getValue(String key) public boolean allowReferenceWithinTransaction()
{ {
return null; return false;
} }
public boolean allowReferenceWithinTransaction() public QName[] getExcludedClasses()
{ {
return false; return null;
} }
public QName[] getExcludedClasses() };
{
return null; }
}
};
}

View File

@@ -1,242 +1,242 @@
/* /*
* Copyright (C) 2005-2007 Alfresco Software Limited. * Copyright (C) 2005-2007 Alfresco Software Limited.
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2 * as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. * of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* As a special exception to the terms and conditions of version 2.0 of * As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre * the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's * and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have recieved a copy of the text describing * FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here: * the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing" * http://www.alfresco.com/legal/licensing"
*/ */
package org.alfresco.repo.importer; package org.alfresco.repo.importer;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileReader; import java.io.FileReader;
import java.io.Reader; import java.io.Reader;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import javax.transaction.UserTransaction; import javax.transaction.UserTransaction;
import org.alfresco.repo.cache.SimpleCache; import org.alfresco.repo.cache.SimpleCache;
import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.repo.security.authentication.ldap.LDAPGroupExportSource; import org.alfresco.repo.security.authentication.ldap.LDAPGroupExportSource;
import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.SearchService; import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.view.ImporterBinding; import org.alfresco.service.cmr.view.ImporterBinding;
import org.alfresco.service.cmr.view.ImporterService; import org.alfresco.service.cmr.view.ImporterService;
import org.alfresco.service.cmr.view.Location; import org.alfresco.service.cmr.view.Location;
import org.alfresco.service.namespace.NamespacePrefixResolver; import org.alfresco.service.namespace.NamespacePrefixResolver;
import org.alfresco.service.namespace.QName; import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService; import org.alfresco.service.transaction.TransactionService;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
public class FileSourceImporter implements ImporterJobSPI public class FileSourceImporter implements ImporterJobSPI
{ {
private static Log s_logger = LogFactory.getLog(FileSourceImporter.class); private static Log s_logger = LogFactory.getLog(FileSourceImporter.class);
private ImporterService importerService; private ImporterService importerService;
private String fileLocation; private String fileLocation;
private AuthenticationComponent authenticationComponent; private AuthenticationContext authenticationContext;
private StoreRef storeRef; private StoreRef storeRef;
private String path; private String path;
private boolean clearAllChildren; private boolean clearAllChildren;
private NodeService nodeService; private NodeService nodeService;
private SearchService searchService; private SearchService searchService;
private NamespacePrefixResolver namespacePrefixResolver; private NamespacePrefixResolver namespacePrefixResolver;
private TransactionService transactionService; private TransactionService transactionService;
private Set<SimpleCache> caches; private Set<SimpleCache> caches;
public FileSourceImporter() public FileSourceImporter()
{ {
super(); super();
} }
public void setImporterService(ImporterService importerService) public void setImporterService(ImporterService importerService)
{ {
this.importerService = importerService; this.importerService = importerService;
} }
public void setFileLocation(String fileLocation) public void setFileLocation(String fileLocation)
{ {
this.fileLocation = fileLocation; this.fileLocation = fileLocation;
} }
public void setClearAllChildren(boolean clearAllChildren) public void setClearAllChildren(boolean clearAllChildren)
{ {
this.clearAllChildren = clearAllChildren; this.clearAllChildren = clearAllChildren;
} }
public void setPath(String path) public void setPath(String path)
{ {
this.path = path; this.path = path;
} }
public void setStoreRef(String storeRef) public void setStoreRef(String storeRef)
{ {
this.storeRef = new StoreRef(storeRef); this.storeRef = new StoreRef(storeRef);
} }
public void setTransactionService(TransactionService transactionService) public void setTransactionService(TransactionService transactionService)
{ {
this.transactionService = transactionService; this.transactionService = transactionService;
} }
public void setNamespacePrefixResolver(NamespacePrefixResolver namespacePrefixResolver) public void setNamespacePrefixResolver(NamespacePrefixResolver namespacePrefixResolver)
{ {
this.namespacePrefixResolver = namespacePrefixResolver; this.namespacePrefixResolver = namespacePrefixResolver;
} }
public void setNodeService(NodeService nodeService) public void setNodeService(NodeService nodeService)
{ {
this.nodeService = nodeService; this.nodeService = nodeService;
} }
public void setCaches(Set<SimpleCache> caches) public void setCaches(Set<SimpleCache> caches)
{ {
this.caches = caches; this.caches = caches;
} }
public void setAuthenticationComponent(AuthenticationComponent authenticationComponent) public void setAuthenticationContext(AuthenticationContext authenticationContext)
{ {
this.authenticationComponent = authenticationComponent; this.authenticationContext = authenticationContext;
} }
public void setSearchService(SearchService searchService) public void setSearchService(SearchService searchService)
{ {
this.searchService = searchService; this.searchService = searchService;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void doImport() public void doImport()
{ {
UserTransaction userTransaction = null; UserTransaction userTransaction = null;
try try
{ {
long start = System.nanoTime(); long start = System.nanoTime();
userTransaction = transactionService.getUserTransaction(); userTransaction = transactionService.getUserTransaction();
userTransaction.begin(); userTransaction.begin();
authenticationComponent.setSystemUserAsCurrentUser(); authenticationContext.setSystemUserAsCurrentUser();
if (clearAllChildren) if (clearAllChildren)
{ {
List<NodeRef> refs = searchService.selectNodes(nodeService.getRootNode(storeRef), path, null, List<NodeRef> refs = searchService.selectNodes(nodeService.getRootNode(storeRef), path, null,
namespacePrefixResolver, false); namespacePrefixResolver, false);
for (NodeRef ref : refs) for (NodeRef ref : refs)
{ {
for (ChildAssociationRef car : nodeService.getChildAssocs(ref)) for (ChildAssociationRef car : nodeService.getChildAssocs(ref))
{ {
nodeService.deleteNode(car.getChildRef()); nodeService.deleteNode(car.getChildRef());
} }
} }
} }
if (caches != null) if (caches != null)
{ {
for (SimpleCache cache : caches) for (SimpleCache cache : caches)
{ {
cache.clear(); cache.clear();
} }
} }
Reader reader = new BufferedReader(new FileReader(fileLocation)); Reader reader = new BufferedReader(new FileReader(fileLocation));
Location location = new Location(storeRef); Location location = new Location(storeRef);
location.setPath(path); location.setPath(path);
importerService.importView(reader, location, REPLACE_BINDING, null); importerService.importView(reader, location, REPLACE_BINDING, null);
reader.close(); reader.close();
if (caches != null) if (caches != null)
{ {
for (SimpleCache cache : caches) for (SimpleCache cache : caches)
{ {
cache.clear(); cache.clear();
} }
} }
userTransaction.commit(); userTransaction.commit();
long end = System.nanoTime(); long end = System.nanoTime();
s_logger.info("Imported "+fileLocation+ " in "+((end-start)/1e9f) + " seconds"); s_logger.info("Imported "+fileLocation+ " in "+((end-start)/1e9f) + " seconds");
} }
catch (Throwable t) catch (Throwable t)
{ {
try try
{ {
if (userTransaction != null) if (userTransaction != null)
{ {
userTransaction.rollback(); userTransaction.rollback();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
} }
try try
{ {
authenticationComponent.clearCurrentSecurityContext(); authenticationContext.clearCurrentSecurityContext();
} }
catch (Exception ex) catch (Exception ex)
{ {
} }
throw new ExportSourceImporterException("Failed to import", t); throw new ExportSourceImporterException("Failed to import", t);
} }
finally finally
{ {
authenticationComponent.clearCurrentSecurityContext(); authenticationContext.clearCurrentSecurityContext();
} }
} }
private static ImporterBinding REPLACE_BINDING = new ImporterBinding() private static ImporterBinding REPLACE_BINDING = new ImporterBinding()
{ {
public UUID_BINDING getUUIDBinding() public UUID_BINDING getUUIDBinding()
{ {
return UUID_BINDING.UPDATE_EXISTING; return UUID_BINDING.UPDATE_EXISTING;
} }
public String getValue(String key) public String getValue(String key)
{ {
return null; return null;
} }
public boolean allowReferenceWithinTransaction() public boolean allowReferenceWithinTransaction()
{ {
return false; return false;
} }
public QName[] getExcludedClasses() public QName[] getExcludedClasses()
{ {
return null; return null;
} }
}; };
} }

File diff suppressed because it is too large Load Diff

View File

@@ -29,7 +29,7 @@ import java.util.List;
import javax.transaction.UserTransaction; import javax.transaction.UserTransaction;
import org.alfresco.error.AlfrescoRuntimeException; import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.view.ImporterException; import org.alfresco.service.cmr.view.ImporterException;
@@ -48,7 +48,7 @@ public class SystemInfoBootstrap extends AbstractLifecycleBean
// dependencies // dependencies
private TransactionService transactionService; private TransactionService transactionService;
private NodeService nodeService; private NodeService nodeService;
private AuthenticationComponent authenticationComponent; private AuthenticationContext authenticationContext;
private SystemExporterImporter systemImporter; private SystemExporterImporter systemImporter;
private List<String> mustNotExistStoreUrls = null; private List<String> mustNotExistStoreUrls = null;
@@ -78,11 +78,11 @@ public class SystemInfoBootstrap extends AbstractLifecycleBean
/** /**
* Set the authentication component * Set the authentication component
* *
* @param authenticationComponent * @param authenticationContext
*/ */
public void setAuthenticationComponent(AuthenticationComponent authenticationComponent) public void setAuthenticationContext(AuthenticationContext authenticationContext)
{ {
this.authenticationComponent = authenticationComponent; this.authenticationContext = authenticationContext;
} }
/** /**
@@ -121,7 +121,7 @@ public class SystemInfoBootstrap extends AbstractLifecycleBean
public void bootstrap() public void bootstrap()
{ {
UserTransaction userTransaction = transactionService.getUserTransaction(); UserTransaction userTransaction = transactionService.getUserTransaction();
authenticationComponent.setSystemUserAsCurrentUser(); authenticationContext.setSystemUserAsCurrentUser();
try try
{ {
@@ -150,12 +150,12 @@ public class SystemInfoBootstrap extends AbstractLifecycleBean
{ {
// rollback the transaction // rollback the transaction
try { if (userTransaction != null) {userTransaction.rollback();} } catch (Exception ex) {} try { if (userTransaction != null) {userTransaction.rollback();} } catch (Exception ex) {}
try {authenticationComponent.clearCurrentSecurityContext(); } catch (Exception ex) {} try {authenticationContext.clearCurrentSecurityContext(); } catch (Exception ex) {}
throw new AlfrescoRuntimeException("System Info Bootstrap failed", e); throw new AlfrescoRuntimeException("System Info Bootstrap failed", e);
} }
finally finally
{ {
authenticationComponent.clearCurrentSecurityContext(); authenticationContext.clearCurrentSecurityContext();
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,214 +1,204 @@
/* /*
* Copyright (C) 2005-2008 Alfresco Software Limited. * Copyright (C) 2005-2008 Alfresco Software Limited.
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2 * as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. * of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* As a special exception to the terms and conditions of version 2.0 of * As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre * the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's * and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have recieved a copy of the text describing * FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here: * the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing" * http://www.alfresco.com/legal/licensing"
*/ */
package org.alfresco.repo.module; package org.alfresco.repo.module;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
import org.alfresco.error.AlfrescoRuntimeException; import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.admin.registry.RegistryService; import org.alfresco.repo.admin.registry.RegistryService;
import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.tenant.TenantAdminService;
import org.alfresco.repo.tenant.TenantAdminService; import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.module.ModuleDetails;
import org.alfresco.service.cmr.module.ModuleDetails; import org.alfresco.service.cmr.module.ModuleService;
import org.alfresco.service.cmr.module.ModuleService; import org.alfresco.service.descriptor.DescriptorService;
import org.alfresco.service.descriptor.DescriptorService; import org.apache.commons.logging.Log;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.LogFactory; import org.springframework.core.io.Resource;
import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
/**
/** * This component controls the execution of
* This component controls the execution of * {@link org.alfresco.repo.module.runtime.ModuleComponent module startup components}.
* {@link org.alfresco.repo.module.runtime.ModuleComponent module startup components}. * <p/>
* <p/> * All required startup executions are performed in a single transaction, so this
* All required startup executions are performed in a single transaction, so this * component guarantees that the module initialization is consistent. Module components are
* component guarantees that the module initialization is consistent. Module components are * executed in dependency order <i>only</i>. The version numbering is not to be used
* executed in dependency order <i>only</i>. The version numbering is not to be used * for ordering purposes.
* for ordering purposes. * <p/>
* <p/> * Afterwards, execution details are persisted in the
* Afterwards, execution details are persisted in the * {@link org.alfresco.repo.admin.registry.RegistryService service registry} to be used when the
* {@link org.alfresco.repo.admin.registry.RegistryService service registry} to be used when the * server starts up again.
* server starts up again. *
* * @author Roy Wetherall
* @author Roy Wetherall * @author Derek Hulley
* @author Derek Hulley * @since 2.0
* @since 2.0 */
*/ public class ModuleServiceImpl implements ModuleService
public class ModuleServiceImpl implements ModuleService {
{ /** Error messages **/
/** Error messages **/ private static final String ERR_UNABLE_TO_OPEN_MODULE_PROPETIES = "module.err.unable_to_open_module_properties";
private static final String ERR_UNABLE_TO_OPEN_MODULE_PROPETIES = "module.err.unable_to_open_module_properties";
/** The classpath search path for module properties */
/** The classpath search path for module properties */ private static final String MODULE_CONFIG_SEARCH_ALL = "classpath*:alfresco/module/*/module.properties";
private static final String MODULE_CONFIG_SEARCH_ALL = "classpath*:alfresco/module/*/module.properties";
private static Log logger = LogFactory.getLog(ModuleServiceImpl.class);
private static Log logger = LogFactory.getLog(ModuleServiceImpl.class);
private ServiceRegistry serviceRegistry;
private ServiceRegistry serviceRegistry; private ModuleComponentHelper moduleComponentHelper;
private ModuleComponentHelper moduleComponentHelper; /** A cache of module details by module ID */
/** A cache of module details by module ID */ private Map<String, ModuleDetails> moduleDetailsById;
private Map<String, ModuleDetails> moduleDetailsById;
/** Default constructor */
/** Default constructor */ public ModuleServiceImpl()
public ModuleServiceImpl() {
{ moduleComponentHelper = new ModuleComponentHelper();
moduleComponentHelper = new ModuleComponentHelper(); moduleComponentHelper.setModuleService(this);
moduleComponentHelper.setModuleService(this); }
}
public void setServiceRegistry(ServiceRegistry serviceRegistry)
public void setServiceRegistry(ServiceRegistry serviceRegistry) {
{ this.serviceRegistry = serviceRegistry;
this.serviceRegistry = serviceRegistry; this.moduleComponentHelper.setServiceRegistry(this.serviceRegistry);
this.moduleComponentHelper.setServiceRegistry(this.serviceRegistry); }
}
public void setDescriptorService(DescriptorService descriptorService)
public void setDescriptorService(DescriptorService descriptorService) {
{ this.moduleComponentHelper.setDescriptorService(descriptorService);
this.moduleComponentHelper.setDescriptorService(descriptorService); }
}
/**
/** * @param registryService the service used to persist component execution details.
* No longer used */
* @deprecated public void setRegistryService(RegistryService registryService)
*/ {
public void setAuthenticationComponent(AuthenticationComponent authenticationComponent) this.moduleComponentHelper.setRegistryService(registryService);
{ }
logger.warn("Bean property 'authenticationComponent' is no longer required for 'ModuleServiceImpl'.");
} public void setTenantAdminService(TenantAdminService tenantAdminService)
{
/** this.moduleComponentHelper.setTenantAdminService(tenantAdminService);
* @param registryService the service used to persist component execution details. }
*/
public void setRegistryService(RegistryService registryService) /**
{ * @see ModuleComponentHelper#registerComponent(ModuleComponent)
this.moduleComponentHelper.setRegistryService(registryService); */
} public void registerComponent(ModuleComponent component)
{
public void setTenantAdminService(TenantAdminService tenantAdminService) this.moduleComponentHelper.registerComponent(component);
{ }
this.moduleComponentHelper.setTenantAdminService(tenantAdminService);
} /**
* {@inheritDoc}
/** *
* @see ModuleComponentHelper#registerComponent(ModuleComponent) * @see ModuleComponentHelper#startModules()
*/ */
public void registerComponent(ModuleComponent component) public void startModules()
{ {
this.moduleComponentHelper.registerComponent(component); moduleComponentHelper.startModules();
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
* */
* @see ModuleComponentHelper#startModules() public ModuleDetails getModule(String moduleId)
*/ {
public void startModules() cacheModuleDetails();
{ // Get the details of the specific module
moduleComponentHelper.startModules(); ModuleDetails details = moduleDetailsById.get(moduleId);
} // Done
return details;
/** }
* {@inheritDoc}
*/ /**
public ModuleDetails getModule(String moduleId) * {@inheritDoc}
{ */
cacheModuleDetails(); public List<ModuleDetails> getAllModules()
// Get the details of the specific module {
ModuleDetails details = moduleDetailsById.get(moduleId); cacheModuleDetails();
// Done Collection<ModuleDetails> moduleDetails = moduleDetailsById.values();
return details; // Make a copy to avoid modification of cached data by clients (and to satisfy API)
} List<ModuleDetails> result = new ArrayList<ModuleDetails>(moduleDetails);
// Done
/** return result;
* {@inheritDoc} }
*/
public List<ModuleDetails> getAllModules() /**
{ * Ensure that the {@link #moduleDetailsById module details} are populated.
cacheModuleDetails(); * <p/>
Collection<ModuleDetails> moduleDetails = moduleDetailsById.values(); * TODO: We will have to avoid caching or add context listening if we support reloading
// Make a copy to avoid modification of cached data by clients (and to satisfy API) * of beans one day.
List<ModuleDetails> result = new ArrayList<ModuleDetails>(moduleDetails); */
// Done private synchronized void cacheModuleDetails()
return result; {
} if (moduleDetailsById != null)
{
/** // There is nothing to do
* Ensure that the {@link #moduleDetailsById module details} are populated. return;
* <p/> }
* TODO: We will have to avoid caching or add context listening if we support reloading try
* of beans one day. {
*/ moduleDetailsById = new HashMap<String, ModuleDetails>(13);
private synchronized void cacheModuleDetails()
{ PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
if (moduleDetailsById != null) Resource[] resources = resolver.getResources(MODULE_CONFIG_SEARCH_ALL);
{
// There is nothing to do // Read each resource
return; for (Resource resource : resources)
} {
try try
{ {
moduleDetailsById = new HashMap<String, ModuleDetails>(13); InputStream is = new BufferedInputStream(resource.getInputStream());
Properties properties = new Properties();
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); properties.load(is);
Resource[] resources = resolver.getResources(MODULE_CONFIG_SEARCH_ALL); ModuleDetails details = new ModuleDetailsImpl(properties);
moduleDetailsById.put(details.getId(), details);
// Read each resource }
for (Resource resource : resources) catch (Throwable e)
{ {
try throw AlfrescoRuntimeException.create(e, ERR_UNABLE_TO_OPEN_MODULE_PROPETIES, resource);
{ }
InputStream is = new BufferedInputStream(resource.getInputStream()); }
Properties properties = new Properties(); }
properties.load(is); catch (IOException e)
ModuleDetails details = new ModuleDetailsImpl(properties); {
moduleDetailsById.put(details.getId(), details); throw new AlfrescoRuntimeException("Failed to retrieve module information", e);
} }
catch (Throwable e) // Done
{ if (logger.isDebugEnabled())
throw AlfrescoRuntimeException.create(e, ERR_UNABLE_TO_OPEN_MODULE_PROPETIES, resource); {
} logger.debug(
} "Found " + moduleDetailsById.size() + " modules: \n" +
} " Modules: " + moduleDetailsById);
catch (IOException e) }
{ }
throw new AlfrescoRuntimeException("Failed to retrieve module information", e); }
}
// Done
if (logger.isDebugEnabled())
{
logger.debug(
"Found " + moduleDetailsById.size() + " modules: \n" +
" Modules: " + moduleDetailsById);
}
}
}

View File

@@ -1,369 +1,369 @@
/* /*
* Copyright (C) 2005-2007 Alfresco Software Limited. * Copyright (C) 2005-2007 Alfresco Software Limited.
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2 * as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. * of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* As a special exception to the terms and conditions of version 2.0 of * As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre * the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's * and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have recieved a copy of the text describing * FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here: * the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing" * http://www.alfresco.com/legal/licensing"
*/ */
package org.alfresco.repo.preference; package org.alfresco.repo.preference;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.alfresco.error.AlfrescoRuntimeException; import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel; import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap; import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.service.cmr.preference.PreferenceService; import org.alfresco.service.cmr.preference.PreferenceService;
import org.alfresco.service.cmr.repository.ContentReader; import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentService; import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter; import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.AccessStatus; import org.alfresco.service.cmr.security.AccessStatus;
import org.alfresco.service.cmr.security.PermissionService; import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.cmr.security.PersonService; import org.alfresco.service.cmr.security.PersonService;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/** /**
* Preference Service Implementation * Preference Service Implementation
* *
* @author Roy Wetherall * @author Roy Wetherall
*/ */
public class PreferenceServiceImpl implements PreferenceService public class PreferenceServiceImpl implements PreferenceService
{ {
/** Node service */ /** Node service */
private NodeService nodeService; private NodeService nodeService;
/** Content service */ /** Content service */
private ContentService contentService; private ContentService contentService;
/** Person service */ /** Person service */
private PersonService personService; private PersonService personService;
/** Permission Service */ /** Permission Service */
private PermissionService permissionService; private PermissionService permissionService;
/** Authentication Service */ /** Authentication Service */
private AuthenticationComponent authenticationComponent; private AuthenticationContext authenticationContext;
/** /**
* Set the node service * Set the node service
* *
* @param nodeService the node service * @param nodeService the node service
*/ */
public void setNodeService(NodeService nodeService) public void setNodeService(NodeService nodeService)
{ {
this.nodeService = nodeService; this.nodeService = nodeService;
} }
/** /**
* Set the content service * Set the content service
* *
* @param contentService the content service * @param contentService the content service
*/ */
public void setContentService(ContentService contentService) public void setContentService(ContentService contentService)
{ {
this.contentService = contentService; this.contentService = contentService;
} }
/** /**
* Set the person service * Set the person service
* *
* @param personService the person service * @param personService the person service
*/ */
public void setPersonService(PersonService personService) public void setPersonService(PersonService personService)
{ {
this.personService = personService; this.personService = personService;
} }
/** /**
* Set the permission service * Set the permission service
* *
* @param permissionService the permission service * @param permissionService the permission service
*/ */
public void setPermissionService(PermissionService permissionService) public void setPermissionService(PermissionService permissionService)
{ {
this.permissionService = permissionService; this.permissionService = permissionService;
} }
/** /**
* Set the authentication component * Set the authentication component
* *
* @param authenticationComponent the authentication component * @param authenticationContext the authentication component
*/ */
public void setAuthenticationComponent(AuthenticationComponent authenticationComponent) public void setAuthenticationContext(AuthenticationContext authenticationContext)
{ {
this.authenticationComponent = authenticationComponent; this.authenticationContext = authenticationContext;
} }
/** /**
* @see org.alfresco.service.cmr.preference.PreferenceService#getPreferences(java.lang.String) * @see org.alfresco.service.cmr.preference.PreferenceService#getPreferences(java.lang.String)
*/ */
public Map<String, Serializable> getPreferences(String userName) public Map<String, Serializable> getPreferences(String userName)
{ {
return getPreferences(userName, null); return getPreferences(userName, null);
} }
/** /**
* @see org.alfresco.repo.person.PersonService#getPreferences(java.lang.String, java.lang.String) * @see org.alfresco.repo.person.PersonService#getPreferences(java.lang.String, java.lang.String)
*/ */
public Map<String, Serializable> getPreferences(String userName, String preferenceFilter) public Map<String, Serializable> getPreferences(String userName, String preferenceFilter)
{ {
Map<String, Serializable> preferences = new HashMap<String, Serializable>(20); Map<String, Serializable> preferences = new HashMap<String, Serializable>(20);
// Get the user node reference // Get the user node reference
NodeRef personNodeRef = this.personService.getPerson(userName); NodeRef personNodeRef = this.personService.getPerson(userName);
if (personNodeRef == null) if (personNodeRef == null)
{ {
throw new AlfrescoRuntimeException("Can not get preferences for " + userName + " because he/she does not exist."); throw new AlfrescoRuntimeException("Can not get preferences for " + userName + " because he/she does not exist.");
} }
try try
{ {
// Check for preferences aspect // Check for preferences aspect
if (this.nodeService.hasAspect(personNodeRef, ContentModel.ASPECT_PREFERENCES) == true) if (this.nodeService.hasAspect(personNodeRef, ContentModel.ASPECT_PREFERENCES) == true)
{ {
// Get the preferences for this user // Get the preferences for this user
JSONObject jsonPrefs = new JSONObject(); JSONObject jsonPrefs = new JSONObject();
ContentReader reader = this.contentService.getReader(personNodeRef, ContentModel.PROP_PREFERENCE_VALUES); ContentReader reader = this.contentService.getReader(personNodeRef, ContentModel.PROP_PREFERENCE_VALUES);
if (reader != null) if (reader != null)
{ {
jsonPrefs = new JSONObject(reader.getContentString()); jsonPrefs = new JSONObject(reader.getContentString());
} }
// Build hash from preferences stored in the repository // Build hash from preferences stored in the repository
Iterator<String> keys = jsonPrefs.keys(); Iterator<String> keys = jsonPrefs.keys();
while (keys.hasNext()) while (keys.hasNext())
{ {
String key = (String)keys.next(); String key = (String)keys.next();
if (preferenceFilter == null || if (preferenceFilter == null ||
preferenceFilter.length() == 0 || preferenceFilter.length() == 0 ||
matchPreferenceNames(key, preferenceFilter) == true) matchPreferenceNames(key, preferenceFilter) == true)
{ {
preferences.put(key, (Serializable)jsonPrefs.get(key)); preferences.put(key, (Serializable)jsonPrefs.get(key));
} }
} }
} }
} }
catch (JSONException exception) catch (JSONException exception)
{ {
throw new AlfrescoRuntimeException("Can not get preferences for " + userName + " because there was an error pasing the JSON data.", exception); throw new AlfrescoRuntimeException("Can not get preferences for " + userName + " because there was an error pasing the JSON data.", exception);
} }
return preferences; return preferences;
} }
/** /**
* Matches the preference name to the partial preference name provided * Matches the preference name to the partial preference name provided
* *
* @param name preference name * @param name preference name
* @param matchTo match to the partial preference name provided * @param matchTo match to the partial preference name provided
* @return boolean true if matches, false otherwise * @return boolean true if matches, false otherwise
*/ */
private boolean matchPreferenceNames(String name, String matchTo) private boolean matchPreferenceNames(String name, String matchTo)
{ {
boolean result = true; boolean result = true;
// Split strings // Split strings
name = name.replace(".", "-"); name = name.replace(".", "-");
String[] nameArr = name.split("-"); String[] nameArr = name.split("-");
matchTo = matchTo.replace(".", "-"); matchTo = matchTo.replace(".", "-");
String[] matchToArr = matchTo.split("-"); String[] matchToArr = matchTo.split("-");
int index = 0; int index = 0;
for (String matchToElement : matchToArr) for (String matchToElement : matchToArr)
{ {
if (matchToElement.equals(nameArr[index]) == false) if (matchToElement.equals(nameArr[index]) == false)
{ {
result = false; result = false;
break; break;
} }
index ++; index ++;
} }
return result; return result;
} }
/** /**
* @see org.alfresco.repo.person.PersonService#setPreferences(java.lang.String, java.util.HashMap) * @see org.alfresco.repo.person.PersonService#setPreferences(java.lang.String, java.util.HashMap)
*/ */
public void setPreferences(final String userName, final Map<String, Serializable> preferences) public void setPreferences(final String userName, final Map<String, Serializable> preferences)
{ {
// Get the user node reference // Get the user node reference
final NodeRef personNodeRef = this.personService.getPerson(userName); final NodeRef personNodeRef = this.personService.getPerson(userName);
if (personNodeRef == null) if (personNodeRef == null)
{ {
throw new AlfrescoRuntimeException("Can not update preferences for " + userName + " because he/she does not exist."); throw new AlfrescoRuntimeException("Can not update preferences for " + userName + " because he/she does not exist.");
} }
// Can only set preferences if the currently logged in user matches the user name being updated or // Can only set preferences if the currently logged in user matches the user name being updated or
// the user already has write permissions on the person node // the user already has write permissions on the person node
String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser(); String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser();
if (authenticationComponent.isSystemUserName(currentUserName) == true || if (authenticationContext.isSystemUserName(currentUserName) == true ||
permissionService.hasPermission(personNodeRef, PermissionService.WRITE) == AccessStatus.ALLOWED || permissionService.hasPermission(personNodeRef, PermissionService.WRITE) == AccessStatus.ALLOWED ||
userName.equals(currentUserName) == true) userName.equals(currentUserName) == true)
{ {
AuthenticationUtil.runAs(new RunAsWork<Object>() AuthenticationUtil.runAs(new RunAsWork<Object>()
{ {
public Object doWork() throws Exception public Object doWork() throws Exception
{ {
// Apply the preferences aspect if required // Apply the preferences aspect if required
if (PreferenceServiceImpl.this.nodeService.hasAspect(personNodeRef, ContentModel.ASPECT_PREFERENCES) == false) if (PreferenceServiceImpl.this.nodeService.hasAspect(personNodeRef, ContentModel.ASPECT_PREFERENCES) == false)
{ {
PreferenceServiceImpl.this.nodeService.addAspect(personNodeRef, ContentModel.ASPECT_PREFERENCES, null); PreferenceServiceImpl.this.nodeService.addAspect(personNodeRef, ContentModel.ASPECT_PREFERENCES, null);
} }
try try
{ {
// Get the current preferences // Get the current preferences
JSONObject jsonPrefs = new JSONObject(); JSONObject jsonPrefs = new JSONObject();
ContentReader reader = PreferenceServiceImpl.this.contentService.getReader(personNodeRef, ContentModel.PROP_PREFERENCE_VALUES); ContentReader reader = PreferenceServiceImpl.this.contentService.getReader(personNodeRef, ContentModel.PROP_PREFERENCE_VALUES);
if (reader != null) if (reader != null)
{ {
jsonPrefs = new JSONObject(reader.getContentString()); jsonPrefs = new JSONObject(reader.getContentString());
} }
// Update with the new preference values // Update with the new preference values
for (Map.Entry<String, Serializable> entry : preferences.entrySet()) for (Map.Entry<String, Serializable> entry : preferences.entrySet())
{ {
jsonPrefs.put(entry.getKey(), entry.getValue()); jsonPrefs.put(entry.getKey(), entry.getValue());
} }
// Save the updated preferences // Save the updated preferences
ContentWriter contentWriter = PreferenceServiceImpl.this.contentService.getWriter(personNodeRef, ContentModel.PROP_PREFERENCE_VALUES, true); ContentWriter contentWriter = PreferenceServiceImpl.this.contentService.getWriter(personNodeRef, ContentModel.PROP_PREFERENCE_VALUES, true);
contentWriter.setEncoding("UTF-8"); contentWriter.setEncoding("UTF-8");
contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN); contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
contentWriter.putContent(jsonPrefs.toString()); contentWriter.putContent(jsonPrefs.toString());
} }
catch (JSONException exception) catch (JSONException exception)
{ {
throw new AlfrescoRuntimeException("Can not update preferences for " + userName + " because there was an error pasing the JSON data.", exception); throw new AlfrescoRuntimeException("Can not update preferences for " + userName + " because there was an error pasing the JSON data.", exception);
} }
return null; return null;
} }
}, AuthenticationUtil.SYSTEM_USER_NAME); }, AuthenticationUtil.SYSTEM_USER_NAME);
} }
else else
{ {
// The current user does not have sufficient permissions to update the preferences for this user // The current user does not have sufficient permissions to update the preferences for this user
throw new AlfrescoRuntimeException("The current user " + currentUserName + " does not have sufficient permissions to update the preferences of the user " + userName); throw new AlfrescoRuntimeException("The current user " + currentUserName + " does not have sufficient permissions to update the preferences of the user " + userName);
} }
} }
/** /**
* @see org.alfresco.service.cmr.preference.PreferenceService#clearPreferences(java.lang.String) * @see org.alfresco.service.cmr.preference.PreferenceService#clearPreferences(java.lang.String)
*/ */
public void clearPreferences(String userName) public void clearPreferences(String userName)
{ {
clearPreferences(userName, null); clearPreferences(userName, null);
} }
/** /**
* @see org.alfresco.repo.person.PersonService#clearPreferences(java.lang.String, java.lang.String) * @see org.alfresco.repo.person.PersonService#clearPreferences(java.lang.String, java.lang.String)
*/ */
public void clearPreferences(final String userName, final String preferenceFilter) public void clearPreferences(final String userName, final String preferenceFilter)
{ {
// Get the user node reference // Get the user node reference
final NodeRef personNodeRef = this.personService.getPerson(userName); final NodeRef personNodeRef = this.personService.getPerson(userName);
if (personNodeRef == null) if (personNodeRef == null)
{ {
throw new AlfrescoRuntimeException("Can not update preferences for " + userName + " because he/she does not exist."); throw new AlfrescoRuntimeException("Can not update preferences for " + userName + " because he/she does not exist.");
} }
// Can only set preferences if the currently logged in user matches the user name being updated or // Can only set preferences if the currently logged in user matches the user name being updated or
// the user already has write permissions on the person node // the user already has write permissions on the person node
String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser(); String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser();
if (authenticationComponent.isSystemUserName(currentUserName) == true || if (authenticationContext.isSystemUserName(currentUserName) == true ||
permissionService.hasPermission(personNodeRef, PermissionService.WRITE) == AccessStatus.ALLOWED || permissionService.hasPermission(personNodeRef, PermissionService.WRITE) == AccessStatus.ALLOWED ||
userName.equals(currentUserName) == true) userName.equals(currentUserName) == true)
{ {
AuthenticationUtil.runAs(new RunAsWork<Object>() AuthenticationUtil.runAs(new RunAsWork<Object>()
{ {
public Object doWork() throws Exception public Object doWork() throws Exception
{ {
if (PreferenceServiceImpl.this.nodeService.hasAspect(personNodeRef, ContentModel.ASPECT_PREFERENCES) == true) if (PreferenceServiceImpl.this.nodeService.hasAspect(personNodeRef, ContentModel.ASPECT_PREFERENCES) == true)
{ {
try try
{ {
JSONObject jsonPrefs = new JSONObject(); JSONObject jsonPrefs = new JSONObject();
if (preferenceFilter != null && preferenceFilter.length() != 0) if (preferenceFilter != null && preferenceFilter.length() != 0)
{ {
// Get the current preferences // Get the current preferences
ContentReader reader = PreferenceServiceImpl.this.contentService.getReader(personNodeRef, ContentModel.PROP_PREFERENCE_VALUES); ContentReader reader = PreferenceServiceImpl.this.contentService.getReader(personNodeRef, ContentModel.PROP_PREFERENCE_VALUES);
if (reader != null) if (reader != null)
{ {
jsonPrefs = new JSONObject(reader.getContentString()); jsonPrefs = new JSONObject(reader.getContentString());
} }
// Remove the prefs that match the filter // Remove the prefs that match the filter
List<String> removeKeys = new ArrayList<String>(10); List<String> removeKeys = new ArrayList<String>(10);
Iterator<String> keys = jsonPrefs.keys(); Iterator<String> keys = jsonPrefs.keys();
while (keys.hasNext()) while (keys.hasNext())
{ {
String key = (String)keys.next(); String key = (String)keys.next();
if (preferenceFilter == null || if (preferenceFilter == null ||
preferenceFilter.length() == 0 || preferenceFilter.length() == 0 ||
matchPreferenceNames(key, preferenceFilter) == true) matchPreferenceNames(key, preferenceFilter) == true)
{ {
removeKeys.add(key); removeKeys.add(key);
} }
} }
for (String removeKey : removeKeys) for (String removeKey : removeKeys)
{ {
jsonPrefs.remove(removeKey); jsonPrefs.remove(removeKey);
} }
} }
// Put the updated JSON back into the repo // Put the updated JSON back into the repo
ContentWriter contentWriter = PreferenceServiceImpl.this.contentService.getWriter(personNodeRef, ContentModel.PROP_PREFERENCE_VALUES, true); ContentWriter contentWriter = PreferenceServiceImpl.this.contentService.getWriter(personNodeRef, ContentModel.PROP_PREFERENCE_VALUES, true);
contentWriter.setEncoding("UTF-8"); contentWriter.setEncoding("UTF-8");
contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN); contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
contentWriter.putContent(jsonPrefs.toString()); contentWriter.putContent(jsonPrefs.toString());
} }
catch (JSONException exception) catch (JSONException exception)
{ {
throw new AlfrescoRuntimeException("Can not update preferences for " + userName + " because there was an error pasing the JSON data.", exception); throw new AlfrescoRuntimeException("Can not update preferences for " + userName + " because there was an error pasing the JSON data.", exception);
} }
} }
return null; return null;
} }
}, AuthenticationUtil.getAdminUserName()); }, AuthenticationUtil.getAdminUserName());
} }
else else
{ {
// The current user does not have sufficient permissions to update the preferences for this user // The current user does not have sufficient permissions to update the preferences for this user
throw new AlfrescoRuntimeException("The current user " + currentUserName + " does not have sufficient permissions to update the preferences of the user " + userName); throw new AlfrescoRuntimeException("The current user " + currentUserName + " does not have sufficient permissions to update the preferences of the user " + userName);
} }
} }
} }

View File

@@ -1,125 +1,123 @@
/* /*
* Copyright (C) 2005-2007 Alfresco Software Limited. * Copyright (C) 2005-2007 Alfresco Software Limited.
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2 * as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. * of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* As a special exception to the terms and conditions of version 2.0 of * As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre * the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's * and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have recieved a copy of the text describing * FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here: * the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing" * http://www.alfresco.com/legal/licensing"
*/ */
package org.alfresco.repo.security.authentication; package org.alfresco.repo.security.authentication;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Set; import java.util.Set;
import java.util.TreeSet; import java.util.TreeSet;
import net.sf.acegisecurity.Authentication; import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.GrantedAuthority; import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl; import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.UserDetails; import net.sf.acegisecurity.UserDetails;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken; import net.sf.acegisecurity.providers.dao.User;
import net.sf.acegisecurity.providers.dao.User;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.error.AlfrescoRuntimeException; import org.alfresco.model.ContentModel;
import org.alfresco.model.ContentModel; import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; import org.alfresco.repo.tenant.TenantService;
import org.alfresco.repo.tenant.TenantService; import org.alfresco.repo.transaction.AlfrescoTransactionSupport;
import org.alfresco.repo.transaction.AlfrescoTransactionSupport; import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper; import org.alfresco.repo.transaction.AlfrescoTransactionSupport.TxnReadState;
import org.alfresco.repo.transaction.AlfrescoTransactionSupport.TxnReadState; import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.security.AuthorityType;
import org.alfresco.service.cmr.security.AuthorityType; import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.cmr.security.PermissionService; import org.alfresco.service.transaction.TransactionService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.transaction.TransactionService; /**
* This class abstract the support required to set up and query the Acegi context for security enforcement. There are
/** * some simple default method implementations to support simple authentication.
* This class abstract the support required to set up and query the Acegi context for security enforcement. There are *
* some simple default method implementations to support simple authentication. * @author Andy Hind
* */
* @author Andy Hind public abstract class AbstractAuthenticationComponent implements AuthenticationComponent
*/ {
public abstract class AbstractAuthenticationComponent implements AuthenticationComponent /**
{ * The abstract class keeps track of support for guest login
/** */
* The abstract class keeps track of support for guest login private Boolean allowGuestLogin = null;
*/
private Boolean allowGuestLogin = null; private Set<String> defaultAdministratorUserNames = Collections.emptySet();
private TenantService tenantService; private boolean autoCreatePeopleOnLogin = true;
private PersonService personService; private AuthenticationContext authenticationContext;
private NodeService nodeService; private PersonService personService;
private TransactionService transactionService; private NodeService nodeService;
private Set<String> defaultAdministratorUserNames = Collections.emptySet(); private TransactionService transactionService;
private boolean autoCreatePeopleOnLogin = true; public AbstractAuthenticationComponent()
{
public AbstractAuthenticationComponent() super();
{ }
super();
} /**
* Set if guest login is supported.
/** *
* Set if guest login is supported. * @param allowGuestLogin
* */
* @param allowGuestLogin public void setAllowGuestLogin(Boolean allowGuestLogin)
*/ {
public void setAllowGuestLogin(Boolean allowGuestLogin) this.allowGuestLogin = allowGuestLogin;
{ }
this.allowGuestLogin = allowGuestLogin;
} public void setAuthenticationContext(AuthenticationContext authenticationContext)
{
public void setTenantService(TenantService tenantService) this.authenticationContext = authenticationContext;
{ }
this.tenantService = tenantService;
} public void setPersonService(PersonService personService)
{
public void setPersonService(PersonService personService) this.personService = personService;
{ }
this.personService = personService;
} public void setNodeService(NodeService nodeService)
{
public void setNodeService(NodeService nodeService) this.nodeService = nodeService;
{ }
this.nodeService = nodeService;
} public void setTransactionService(TransactionService transactionService)
{
public void setTransactionService(TransactionService transactionService) this.transactionService = transactionService;
{ }
this.transactionService = transactionService;
} public TransactionService getTransactionService()
{
public TransactionService getTransactionService() return transactionService;
{ }
return transactionService;
} public Boolean getAllowGuestLogin()
{
public Boolean getAllowGuestLogin() return allowGuestLogin;
{ }
return allowGuestLogin;
}
public NodeService getNodeService() public NodeService getNodeService()
{ {
return nodeService; return nodeService;
@@ -130,56 +128,56 @@ public abstract class AbstractAuthenticationComponent implements AuthenticationC
return personService; return personService;
} }
public boolean isAutoCreatePeopleOnLogin() public boolean isAutoCreatePeopleOnLogin()
{ {
return autoCreatePeopleOnLogin; return autoCreatePeopleOnLogin;
} }
public void setAutoCreatePeopleOnLogin(boolean autoCreatePeopleOnLogin) public void setAutoCreatePeopleOnLogin(boolean autoCreatePeopleOnLogin)
{ {
this.autoCreatePeopleOnLogin = autoCreatePeopleOnLogin; this.autoCreatePeopleOnLogin = autoCreatePeopleOnLogin;
} }
public void authenticate(String userName, char[] password) throws AuthenticationException public void authenticate(String userName, char[] password) throws AuthenticationException
{ {
// Support guest login from the login screen // Support guest login from the login screen
if (isGuestUserName(userName)) if (isGuestUserName(userName))
{ {
setGuestUserAsCurrentUser(tenantService.getUserDomain(userName)); setGuestUserAsCurrentUser(getUserDomain(userName));
} }
else else
{ {
authenticateImpl(userName, password); authenticateImpl(userName, password);
} }
} }
/** /**
* Default unsupported authentication implementation - as of 2.1 this is the best way to implement your own * Default unsupported authentication implementation - as of 2.1 this is the best way to implement your own
* authentication component as it will support guest login - prior to this direct over ride for authenticate(String , * authentication component as it will support guest login - prior to this direct over ride for authenticate(String ,
* char[]) was used. This will still work. * char[]) was used. This will still work.
* *
* @param userName * @param userName
* @param password * @param password
*/ */
protected void authenticateImpl(String userName, char[] password) protected void authenticateImpl(String userName, char[] password)
{ {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Authentication setCurrentUser(String userName, UserNameValidationMode validationMode) public Authentication setCurrentUser(String userName, UserNameValidationMode validationMode)
{ {
switch (validationMode) switch (validationMode)
{ {
case NONE: case NONE:
return setCurrentUserImpl(userName); return setCurrentUserImpl(userName);
case CHECK_AND_FIX: case CHECK_AND_FIX:
default: default:
return setCurrentUser(userName); return setCurrentUser(userName);
} }
} }
public Authentication setCurrentUser(final String userName) throws AuthenticationException public Authentication setCurrentUser(final String userName) throws AuthenticationException
{ {
if (isSystemUserName(userName)) if (isSystemUserName(userName))
{ {
return setCurrentUserImpl(userName); return setCurrentUserImpl(userName);
@@ -223,39 +221,29 @@ public abstract class AbstractAuthenticationComponent implements AuthenticationC
throw new AuthenticationException("Null user name"); throw new AuthenticationException("Null user name");
} }
if (isSystemUserName(userName))
{
return setSystemUserAsCurrentUser(getUserDomain(userName));
}
try try
{ {
UserDetails ud = null; UserDetails ud = null;
if (isSystemUserName(userName)) if (isGuestUserName(userName))
{
GrantedAuthority[] gas = new GrantedAuthority[1];
gas[0] = new GrantedAuthorityImpl("ROLE_SYSTEM");
ud = new User(userName, "", true, true, true, true, gas);
}
else if (isGuestUserName(userName))
{ {
GrantedAuthority[] gas = new GrantedAuthority[0]; GrantedAuthority[] gas = new GrantedAuthority[0];
ud = new User(getGuestUserName(tenantService.getUserDomain(userName)), "", true, true, true, true, gas); ud = new User(getGuestUserName(getUserDomain(userName)), "", true, true, true, true, gas);
} }
else else
{ {
ud = getUserDetails(userName); ud = getUserDetails(userName);
} }
return setUserDetails(ud);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(ud, "", ud.getAuthorities());
auth.setDetails(ud);
auth.setAuthenticated(true);
return setCurrentAuthentication(auth);
} }
catch (net.sf.acegisecurity.AuthenticationException ae) catch (net.sf.acegisecurity.AuthenticationException ae)
{ {
throw new AuthenticationException(ae.getMessage(), ae); throw new AuthenticationException(ae.getMessage(), ae);
} }
finally
{
// Support for logging tenantdomain / username (via log4j NDC)
AuthenticationUtil.logNDC(userName);
}
} }
/** /**
@@ -270,175 +258,177 @@ public abstract class AbstractAuthenticationComponent implements AuthenticationC
gas[0] = new GrantedAuthorityImpl("ROLE_AUTHENTICATED"); gas[0] = new GrantedAuthorityImpl("ROLE_AUTHENTICATED");
UserDetails ud = new User(userName, "", true, true, true, true, gas); UserDetails ud = new User(userName, "", true, true, true, true, gas);
return ud; return ud;
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public Authentication setCurrentAuthentication(Authentication authentication) public Authentication setCurrentAuthentication(Authentication authentication)
{ {
return AuthenticationUtil.setFullAuthentication(authentication); return this.authenticationContext.setCurrentAuthentication(authentication);
} }
/** /**
* Get the current authentication context * Get the current authentication context
* *
* @return Authentication * @return Authentication
* @throws AuthenticationException * @throws AuthenticationException
*/ */
public Authentication getCurrentAuthentication() throws AuthenticationException public Authentication getCurrentAuthentication() throws AuthenticationException
{ {
return AuthenticationUtil.getFullAuthentication(); return authenticationContext.getCurrentAuthentication();
} }
/** /**
* Get the current user name. * Get the current user name.
* *
* @return String * @return String
* @throws AuthenticationException * @throws AuthenticationException
*/ */
public String getCurrentUserName() throws AuthenticationException public String getCurrentUserName() throws AuthenticationException
{ {
return AuthenticationUtil.getFullyAuthenticatedUser(); return authenticationContext.getCurrentUserName();
} }
/** /**
* Set the system user as the current user note: for MT, will set to default domain only * Set the system user as the current user note: for MT, will set to default domain only
* *
* @return Authentication * @return Authentication
*/ */
public Authentication setSystemUserAsCurrentUser() public Authentication setSystemUserAsCurrentUser()
{ {
return setCurrentUser(AuthenticationUtil.SYSTEM_USER_NAME); return authenticationContext.setSystemUserAsCurrentUser();
} }
/** /**
* Get the name of the system user note: for MT, will get system for default domain only * Get the name of the system user note: for MT, will get system for default domain only
* *
* @return String * @return String
*/ */
public String getSystemUserName() public String getSystemUserName()
{ {
return AuthenticationUtil.SYSTEM_USER_NAME; return authenticationContext.getSystemUserName();
} }
/** /**
* Is this the system user ? * Is this the system user ?
* *
* @return boolean * @return boolean
*/ */
public boolean isSystemUserName(String userName) public boolean isSystemUserName(String userName)
{ {
return (getSystemUserName().equals(tenantService.getBaseNameUser(userName))); return authenticationContext.isSystemUserName(userName);
} }
/** /**
* Get the name of the Guest User note: for MT, will get guest for default domain only * Get the name of the Guest User note: for MT, will get guest for default domain only
* *
* @return String * @return String
*/ */
public String getGuestUserName() public String getGuestUserName()
{ {
return PermissionService.GUEST_AUTHORITY.toLowerCase(); return authenticationContext.getGuestUserName();
} }
private String getGuestUserName(String tenantDomain) public String getGuestUserName(String tenantDomain)
{ {
return tenantService.getDomainUser(getGuestUserName(), tenantDomain); return authenticationContext.getGuestUserName(tenantDomain);
} }
/** /**
* Set the guest user as the current user. note: for MT, will set to default domain only * Set the guest user as the current user. note: for MT, will set to default domain only
*/ */
public Authentication setGuestUserAsCurrentUser() throws AuthenticationException public Authentication setGuestUserAsCurrentUser() throws AuthenticationException
{ {
return setGuestUserAsCurrentUser(TenantService.DEFAULT_DOMAIN); return setGuestUserAsCurrentUser(TenantService.DEFAULT_DOMAIN);
} }
/** /**
* Set the guest user as the current user. * Set the guest user as the current user.
*/ */
private Authentication setGuestUserAsCurrentUser(String tenantDomain) throws AuthenticationException private Authentication setGuestUserAsCurrentUser(String tenantDomain) throws AuthenticationException
{ {
if (allowGuestLogin == null) if (allowGuestLogin == null)
{ {
if (implementationAllowsGuestLogin()) if (implementationAllowsGuestLogin())
{ {
return setCurrentUser(getGuestUserName(tenantDomain)); return setCurrentUser(getGuestUserName(tenantDomain));
} }
else else
{ {
throw new AuthenticationException("Guest authentication is not allowed"); throw new AuthenticationException("Guest authentication is not allowed");
} }
} }
else else
{ {
if (allowGuestLogin.booleanValue()) if (allowGuestLogin.booleanValue())
{ {
return setCurrentUser(getGuestUserName(tenantDomain)); return setCurrentUser(getGuestUserName(tenantDomain));
} }
else else
{ {
throw new AuthenticationException("Guest authentication is not allowed"); throw new AuthenticationException("Guest authentication is not allowed");
} }
} }
} }
private boolean isGuestUserName(String userName) public boolean isGuestUserName(String userName)
{ {
return (PermissionService.GUEST_AUTHORITY.equalsIgnoreCase(tenantService.getBaseNameUser(userName))); return authenticationContext.isGuestUserName(userName);
} }
protected abstract boolean implementationAllowsGuestLogin();
protected abstract boolean implementationAllowsGuestLogin();
/**
* @return true if Guest user authentication is allowed, false otherwise
*/ /**
public boolean guestUserAuthenticationAllowed() * @return true if Guest user authentication is allowed, false otherwise
{ */
if (allowGuestLogin == null) public boolean guestUserAuthenticationAllowed()
{ {
return (implementationAllowsGuestLogin()); if (allowGuestLogin == null)
} {
else return (implementationAllowsGuestLogin());
{ }
return (allowGuestLogin.booleanValue()); else
} {
} return (allowGuestLogin.booleanValue());
}
/** }
* Remove the current security information
*/ /**
public void clearCurrentSecurityContext() * Remove the current security information
{ */
AuthenticationUtil.clearCurrentSecurityContext(); public void clearCurrentSecurityContext()
} {
authenticationContext.clearCurrentSecurityContext();
/** }
* The default is not to support Authentication token base authentication
*/ /**
public Authentication authenticate(Authentication token) throws AuthenticationException * The default is not to support Authentication token base authentication
{ */
throw new AlfrescoRuntimeException("Authentication via token not supported"); public Authentication authenticate(Authentication token) throws AuthenticationException
} {
throw new AlfrescoRuntimeException("Authentication via token not supported");
/** }
* The should only be supported if getNTLMMode() is NTLMMode.MD4_PROVIDER.
*/ /**
public String getMD4HashedPassword(String userName) * The should only be supported if getNTLMMode() is NTLMMode.MD4_PROVIDER.
{ */
throw new UnsupportedOperationException(); public String getMD4HashedPassword(String userName)
} {
throw new UnsupportedOperationException();
/** }
* Get the NTML mode - none - supports MD4 hash to integrate - or it can asct as an NTLM authentication
*/ /**
public NTLMMode getNTLMMode() * Get the NTML mode - none - supports MD4 hash to integrate - or it can asct as an NTLM authentication
{ */
return NTLMMode.NONE; public NTLMMode getNTLMMode()
} {
return NTLMMode.NONE;
}
class SetCurrentUserCallback implements RetryingTransactionHelper.RetryingTransactionCallback<Authentication> class SetCurrentUserCallback implements RetryingTransactionHelper.RetryingTransactionCallback<Authentication>
{ {
AuthenticationException ae = null; AuthenticationException ae = null;
@@ -490,7 +480,7 @@ public abstract class AbstractAuthenticationComponent implements AuthenticationC
return userName; return userName;
} }
} }
}, tenantService.getDomainUser(AuthenticationUtil.getSystemUserName(), tenantService.getUserDomain(userName))); }, getSystemUserName(getUserDomain(userName)));
return setCurrentUserImpl(name); return setCurrentUserImpl(name);
} }
@@ -502,38 +492,58 @@ public abstract class AbstractAuthenticationComponent implements AuthenticationC
} }
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see org.alfresco.repo.security.authentication.AuthenticationComponent#getDefaultAdministratorUserNames() * @see org.alfresco.repo.security.authentication.AuthenticationComponent#getDefaultAdministratorUserNames()
*/ */
public Set<String> getDefaultAdministratorUserNames() public Set<String> getDefaultAdministratorUserNames()
{ {
return this.defaultAdministratorUserNames; return this.defaultAdministratorUserNames;
} }
/** /**
* Sets the user names who for this particular authentication system should be considered administrators by default. * Sets the user names who for this particular authentication system should be considered administrators by default.
* *
* @param defaultAdministratorUserNames * @param defaultAdministratorUserNames
* a set of user names * a set of user names
*/ */
public void setDefaultAdministratorUserNames(Set<String> defaultAdministratorUserNames) public void setDefaultAdministratorUserNames(Set<String> defaultAdministratorUserNames)
{ {
this.defaultAdministratorUserNames = defaultAdministratorUserNames; this.defaultAdministratorUserNames = defaultAdministratorUserNames;
} }
/** /**
* Convenience method to allow the administrator user names to be specified as a comma separated list * Convenience method to allow the administrator user names to be specified as a comma separated list
* *
* @param defaultAdministratorUserNames * @param defaultAdministratorUserNames
*/ */
public void setDefaultAdministratorUserNames(String defaultAdministratorUserNames) public void setDefaultAdministratorUserNames(String defaultAdministratorUserNames)
{ {
Set<String> nameSet = new TreeSet<String>(); Set<String> nameSet = new TreeSet<String>();
if (defaultAdministratorUserNames.length() > 0) if (defaultAdministratorUserNames.length() > 0)
{ {
nameSet.addAll(Arrays.asList(defaultAdministratorUserNames.split(","))); nameSet.addAll(Arrays.asList(defaultAdministratorUserNames.split(",")));
} }
setDefaultAdministratorUserNames(nameSet); setDefaultAdministratorUserNames(nameSet);
} }
}
public String getSystemUserName(String tenantDomain)
{
return authenticationContext.getSystemUserName(tenantDomain);
}
public String getUserDomain(String userName)
{
return authenticationContext.getUserDomain(userName);
}
public Authentication setSystemUserAsCurrentUser(String tenantDomain)
{
return authenticationContext.setSystemUserAsCurrentUser(tenantDomain);
}
public Authentication setUserDetails(UserDetails ud)
{
return authenticationContext.setUserDetails(ud);
}
}

View File

@@ -28,9 +28,8 @@ import java.util.Set;
import net.sf.acegisecurity.Authentication; import net.sf.acegisecurity.Authentication;
public interface AuthenticationComponent public interface AuthenticationComponent extends AuthenticationContext
{ {
public enum UserNameValidationMode public enum UserNameValidationMode
{ {
NONE, CHECK_AND_FIX; NONE, CHECK_AND_FIX;
@@ -65,33 +64,6 @@ public interface AuthenticationComponent
public Authentication setCurrentUser(String userName, UserNameValidationMode validationMode); public Authentication setCurrentUser(String userName, UserNameValidationMode validationMode);
/**
* Remove the current security information
*
*/
public void clearCurrentSecurityContext();
/**
* Explicitly set the current suthentication. If the authentication is <tt>null</tt> the
* the current authentication is {@link #clearCurrentSecurityContext() cleared}.
*
* @param authentication the current authentication (may be <tt>null</tt>).
*
* @return Returns the modified authentication instance or <tt>null</tt> if it was cleared.
*/
public Authentication setCurrentAuthentication(Authentication authentication);
/**
*
* @throws AuthenticationException
*/
public Authentication getCurrentAuthentication() throws AuthenticationException;
/**
* Set the system user as the current user.
*/
public Authentication setSystemUserAsCurrentUser();
/** /**
* Set the guest user as the current user. * Set the guest user as the current user.
@@ -104,29 +76,6 @@ public interface AuthenticationComponent
*/ */
public boolean guestUserAuthenticationAllowed(); public boolean guestUserAuthenticationAllowed();
/**
* Get the name of the system user
*/
public String getSystemUserName();
/**
* True if this is the System user ?
*/
public boolean isSystemUserName(String userName);
/**
* Get the name of the guest user
*/
public String getGuestUserName();
/**
* Get the current user name.
*
* @throws AuthenticationException
*/
public String getCurrentUserName() throws AuthenticationException;
/** /**
* Get the enum that describes NTLM integration * Get the enum that describes NTLM integration
*/ */

View File

@@ -0,0 +1,122 @@
/*
* Copyright (C) 2005-2007 Alfresco Software Limited.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing"
*/
package org.alfresco.repo.security.authentication;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.UserDetails;
/**
* Low-level interface allowing control and retrieval of the authentication information held for the current thread.
*
* @author dward
*/
public interface AuthenticationContext
{
/**
* Remove the current security information
*/
public void clearCurrentSecurityContext();
/**
* Explicitly set the current suthentication. If the authentication is <tt>null</tt> the the current authentication
* is {@link #clearCurrentSecurityContext() cleared}.
*
* @param authentication
* the current authentication (may be <tt>null</tt>).
* @return Returns the modified authentication instance or <tt>null</tt> if it was cleared.
*/
public Authentication setCurrentAuthentication(Authentication authentication);
/**
* Explicitly set the given validated user details to be authenticated.
*
* @param ud
* the User Details
* @return Authentication
*/
public Authentication setUserDetails(UserDetails ud);
/**
* @throws AuthenticationException
*/
public Authentication getCurrentAuthentication() throws AuthenticationException;
/**
* Set the system user as the current user.
*/
public Authentication setSystemUserAsCurrentUser();
/**
* Set the system user as the current user.
*/
public Authentication setSystemUserAsCurrentUser(String tenantDomain);
/**
* Get the name of the system user. Note: for MT, will get system for default domain only
*/
public String getSystemUserName();
/**
* Get the name of the system user
*/
public String getSystemUserName(String tenantDomain);
/**
* True if this is the System user ?
*/
public boolean isSystemUserName(String userName);
/**
* Get the name of the Guest User. Note: for MT, will get guest for default domain only
*/
public String getGuestUserName();
/**
* Get the name of the guest user
*/
public String getGuestUserName(String tenantDomain);
/**
* True if this is a guest user ?
*/
public boolean isGuestUserName(String userName);
/**
* Get the current user name.
*
* @throws AuthenticationException
*/
public String getCurrentUserName() throws AuthenticationException;
/**
* Extracts the tenant domain name from a user name
*
* @param userName
* a user name
* @return a tenant domain name
*/
public String getUserDomain(String userName);
}

View File

@@ -0,0 +1,144 @@
/*
* Copyright (C) 2005-2009 Alfresco Software Limited.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing"
*/
package org.alfresco.repo.security.authentication;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.UserDetails;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import net.sf.acegisecurity.providers.dao.User;
import org.alfresco.repo.tenant.TenantService;
import org.alfresco.service.cmr.security.PermissionService;
/**
* @author Andy Hind
* @author dward
*/
public class AuthenticationContextImpl implements AuthenticationContext
{
private TenantService tenantService;
public void setTenantService(TenantService tenantService)
{
this.tenantService = tenantService;
}
/**
* Explicitly set the given validated user details to be authenticated.
*
* @param ud
* the User Details
* @return Authentication
*/
public Authentication setUserDetails(UserDetails ud)
{
try
{
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(ud, "", ud
.getAuthorities());
auth.setDetails(ud);
auth.setAuthenticated(true);
return setCurrentAuthentication(auth);
}
catch (net.sf.acegisecurity.AuthenticationException ae)
{
throw new AuthenticationException(ae.getMessage(), ae);
}
finally
{
// Support for logging tenantdomain / username (via log4j NDC)
AuthenticationUtil.logNDC(ud.getUsername());
}
}
public Authentication setSystemUserAsCurrentUser()
{
return setSystemUserAsCurrentUser(TenantService.DEFAULT_DOMAIN);
}
public Authentication setSystemUserAsCurrentUser(String tenantDomain)
{
GrantedAuthority[] gas = new GrantedAuthority[1];
gas[0] = new GrantedAuthorityImpl("ROLE_SYSTEM");
return setUserDetails(new User(getSystemUserName(tenantDomain), "", true, true, true, true, gas));
}
public String getSystemUserName()
{
return AuthenticationUtil.SYSTEM_USER_NAME;
}
public String getSystemUserName(String tenantDomain)
{
return this.tenantService.getDomainUser(getSystemUserName(), tenantDomain);
}
public boolean isSystemUserName(String userName)
{
return getSystemUserName().equals(this.tenantService.getBaseNameUser(userName));
}
public String getGuestUserName(String tenantDomain)
{
return this.tenantService.getDomainUser(getGuestUserName(), tenantDomain);
}
public String getGuestUserName()
{
return PermissionService.GUEST_AUTHORITY.toLowerCase();
}
public boolean isGuestUserName(String userName)
{
return PermissionService.GUEST_AUTHORITY.equalsIgnoreCase(this.tenantService.getBaseNameUser(userName));
}
public Authentication setCurrentAuthentication(Authentication authentication)
{
return AuthenticationUtil.setFullAuthentication(authentication);
}
public Authentication getCurrentAuthentication() throws AuthenticationException
{
return AuthenticationUtil.getFullAuthentication();
}
public String getCurrentUserName() throws AuthenticationException
{
return AuthenticationUtil.getFullyAuthenticatedUser();
}
public void clearCurrentSecurityContext()
{
AuthenticationUtil.clearCurrentSecurityContext();
}
public String getUserDomain(String userName)
{
return this.tenantService.getUserDomain(userName);
}
}

View File

@@ -26,13 +26,10 @@ package org.alfresco.repo.security.authentication;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import net.sf.acegisecurity.Authentication; import net.sf.acegisecurity.Authentication;
import org.alfresco.service.Managed; import org.alfresco.service.Managed;
import org.alfresco.service.cmr.security.PermissionService;
/** /**
* A chaining authentication component is required for all the beans that qire up an authentication component and not an * A chaining authentication component is required for all the beans that qire up an authentication component and not an
@@ -41,7 +38,7 @@ import org.alfresco.service.cmr.security.PermissionService;
* *
* @author andyh * @author andyh
*/ */
public class ChainingAuthenticationComponentImpl implements AuthenticationComponent public class ChainingAuthenticationComponentImpl extends AbstractAuthenticationComponent
{ {
/** /**
* NLTM authentication mode - if unset - finds the first component that supports NTLM - if set - finds the first * NLTM authentication mode - if unset - finds the first component that supports NTLM - if set - finds the first
@@ -67,7 +64,7 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
*/ */
public List<AuthenticationComponent> getAuthenticationComponents() public List<AuthenticationComponent> getAuthenticationComponents()
{ {
return authenticationComponents; return this.authenticationComponents;
} }
/** /**
@@ -75,7 +72,7 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
* *
* @param authenticationComponents * @param authenticationComponents
*/ */
@Managed(category="Security") @Managed(category = "Security")
public void setAuthenticationComponents(List<AuthenticationComponent> authenticationComponents) public void setAuthenticationComponents(List<AuthenticationComponent> authenticationComponents)
{ {
this.authenticationComponents = authenticationComponents; this.authenticationComponents = authenticationComponents;
@@ -88,7 +85,7 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
*/ */
public AuthenticationComponent getMutableAuthenticationComponent() public AuthenticationComponent getMutableAuthenticationComponent()
{ {
return mutableAuthenticationComponent; return this.mutableAuthenticationComponent;
} }
/** /**
@@ -96,15 +93,13 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
* *
* @param mutableAuthenticationComponent * @param mutableAuthenticationComponent
*/ */
@Managed(category="Security") @Managed(category = "Security")
public void setMutableAuthenticationComponent(AuthenticationComponent mutableAuthenticationComponent) public void setMutableAuthenticationComponent(AuthenticationComponent mutableAuthenticationComponent)
{ {
this.mutableAuthenticationComponent = mutableAuthenticationComponent; this.mutableAuthenticationComponent = mutableAuthenticationComponent;
} }
@Managed(category = "Security")
@Managed(category="Security")
public void setNtlmMode(NTLMMode ntlmMode) public void setNtlmMode(NTLMMode ntlmMode)
{ {
this.ntlmMode = ntlmMode; this.ntlmMode = ntlmMode;
@@ -113,7 +108,8 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
/** /**
* Chain authentication with user name and password - tries all in order until one works, or fails. * Chain authentication with user name and password - tries all in order until one works, or fails.
*/ */
public void authenticate(String userName, char[] password) throws AuthenticationException @Override
protected void authenticateImpl(String userName, char[] password)
{ {
for (AuthenticationComponent authComponent : getUsableAuthenticationComponents()) for (AuthenticationComponent authComponent : getUsableAuthenticationComponents())
{ {
@@ -134,11 +130,12 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
* NTLM passthrough authentication - if a mode is defined - the first PASS_THROUGH provider is used - if not, the * NTLM passthrough authentication - if a mode is defined - the first PASS_THROUGH provider is used - if not, the
* first component that supports NTLM is used if it supports PASS_THROUGH * first component that supports NTLM is used if it supports PASS_THROUGH
*/ */
@Override
public Authentication authenticate(Authentication token) throws AuthenticationException public Authentication authenticate(Authentication token) throws AuthenticationException
{ {
if (ntlmMode != null) if (this.ntlmMode != null)
{ {
switch (ntlmMode) switch (this.ntlmMode)
{ {
case NONE: case NONE:
throw new AuthenticationException("NTLM is not supported"); throw new AuthenticationException("NTLM is not supported");
@@ -169,7 +166,8 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
} }
else else
{ {
throw new AuthenticationException("The first authentication component to support NTLM supports MD4 hashing"); throw new AuthenticationException(
"The first authentication component to support NTLM supports MD4 hashing");
} }
} }
} }
@@ -178,46 +176,15 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
} }
/**
* Clear the security context
*/
public void clearCurrentSecurityContext()
{
AuthenticationUtil.clearCurrentSecurityContext();
}
/**
* Get the current authentication
*/
public Authentication getCurrentAuthentication() throws AuthenticationException
{
return AuthenticationUtil.getFullAuthentication();
}
/**
* Get the current user name
*/
public String getCurrentUserName() throws AuthenticationException
{
return AuthenticationUtil.getFullyAuthenticatedUser();
}
/**
* Get the guest user name
*/
public String getGuestUserName()
{
return PermissionService.GUEST_AUTHORITY.toLowerCase();
}
/** /**
* Get the MD4 password hash * Get the MD4 password hash
*/ */
@Override
public String getMD4HashedPassword(String userName) public String getMD4HashedPassword(String userName)
{ {
if (ntlmMode != null) if (this.ntlmMode != null)
{ {
switch (ntlmMode) switch (this.ntlmMode)
{ {
case NONE: case NONE:
throw new AuthenticationException("NTLM is not supported"); throw new AuthenticationException("NTLM is not supported");
@@ -244,7 +211,8 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
{ {
if (authComponent.getNTLMMode() == NTLMMode.PASS_THROUGH) if (authComponent.getNTLMMode() == NTLMMode.PASS_THROUGH)
{ {
throw new AuthenticationException("The first authentication component to support NTLM supports passthrough"); throw new AuthenticationException(
"The first authentication component to support NTLM supports passthrough");
} }
else else
{ {
@@ -260,11 +228,12 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
/** /**
* Get the NTLM mode - this is only what is set if one of the implementations provides support for that mode. * Get the NTLM mode - this is only what is set if one of the implementations provides support for that mode.
*/ */
@Override
public NTLMMode getNTLMMode() public NTLMMode getNTLMMode()
{ {
if (ntlmMode != null) if (this.ntlmMode != null)
{ {
switch (ntlmMode) switch (this.ntlmMode)
{ {
case NONE: case NONE:
return NTLMMode.NONE; return NTLMMode.NONE;
@@ -303,33 +272,11 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
} }
} }
/**
* Get the system user name
*/
public String getSystemUserName()
{
return AuthenticationUtil.SYSTEM_USER_NAME;
}
/**
* If any implementation supports System then System is allowed
*/
public boolean isSystemUserName(String userName)
{
for (AuthenticationComponent authComponent : getUsableAuthenticationComponents())
{
if (authComponent.isSystemUserName(userName))
{
return true;
}
}
return false;
}
/** /**
* If any implementation supports guest then guest is allowed * If any implementation supports guest then guest is allowed
*/ */
public boolean guestUserAuthenticationAllowed() @Override
protected boolean implementationAllowsGuestLogin()
{ {
for (AuthenticationComponent authComponent : getUsableAuthenticationComponents()) for (AuthenticationComponent authComponent : getUsableAuthenticationComponents())
{ {
@@ -341,16 +288,7 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
return false; return false;
} }
/** @Override
* Ste the current authentication
*/
public Authentication setCurrentAuthentication(Authentication authentication)
{
return AuthenticationUtil.setFullAuthentication(authentication);
}
public Authentication setCurrentUser(String userName, UserNameValidationMode validationMode) public Authentication setCurrentUser(String userName, UserNameValidationMode validationMode)
{ {
for (AuthenticationComponent authComponent : getUsableAuthenticationComponents()) for (AuthenticationComponent authComponent : getUsableAuthenticationComponents())
@@ -370,6 +308,7 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
/** /**
* Set the current user - try all implementations - as some may check the user exists * Set the current user - try all implementations - as some may check the user exists
*/ */
@Override
public Authentication setCurrentUser(String userName) public Authentication setCurrentUser(String userName)
{ {
for (AuthenticationComponent authComponent : getUsableAuthenticationComponents()) for (AuthenticationComponent authComponent : getUsableAuthenticationComponents())
@@ -386,33 +325,6 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
throw new AuthenticationException("Failed to set current user " + userName); throw new AuthenticationException("Failed to set current user " + userName);
} }
/**
* Authenticate as guest - try all in the cahin
*/
public Authentication setGuestUserAsCurrentUser()
{
for (AuthenticationComponent authComponent : getUsableAuthenticationComponents())
{
try
{
return authComponent.setGuestUserAsCurrentUser();
}
catch (AuthenticationException e)
{
// Ignore and chain
}
}
throw new AuthenticationException("Guest authentication is not allowed");
}
/**
* Set the system user
*/
public Authentication setSystemUserAsCurrentUser()
{
return setCurrentUser(getSystemUserName());
}
/** /**
* Helper to get authentication components * Helper to get authentication components
* *
@@ -420,33 +332,20 @@ public class ChainingAuthenticationComponentImpl implements AuthenticationCompon
*/ */
private List<AuthenticationComponent> getUsableAuthenticationComponents() private List<AuthenticationComponent> getUsableAuthenticationComponents()
{ {
if (mutableAuthenticationComponent == null) if (this.mutableAuthenticationComponent == null)
{ {
return authenticationComponents; return this.authenticationComponents;
} }
else else
{ {
ArrayList<AuthenticationComponent> services = new ArrayList<AuthenticationComponent>(authenticationComponents == null ? 1 : (authenticationComponents.size() + 1)); ArrayList<AuthenticationComponent> services = new ArrayList<AuthenticationComponent>(
services.add(mutableAuthenticationComponent); this.authenticationComponents == null ? 1 : this.authenticationComponents.size() + 1);
if (authenticationComponents != null) services.add(this.mutableAuthenticationComponent);
if (this.authenticationComponents != null)
{ {
services.addAll(authenticationComponents); services.addAll(this.authenticationComponents);
} }
return services; return services;
} }
} }
/*
* (non-Javadoc)
* @see org.alfresco.repo.security.authentication.AuthenticationComponent#getDefaultAdministratorUserNames()
*/
public Set<String> getDefaultAdministratorUserNames()
{
Set<String> defaultAdministratorUserNames = new TreeSet<String>();
for (AuthenticationComponent authComponent : getUsableAuthenticationComponents())
{
defaultAdministratorUserNames.addAll(authComponent.getDefaultAdministratorUserNames());
}
return defaultAdministratorUserNames;
}
} }

View File

@@ -1,387 +1,381 @@
/* /*
* Copyright (C) 2005-2007 Alfresco Software Limited. * Copyright (C) 2005-2007 Alfresco Software Limited.
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2 * as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. * of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* As a special exception to the terms and conditions of version 2.0 of * As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre * the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's * and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have recieved a copy of the text describing * FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here: * the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing" * http://www.alfresco.com/legal/licensing"
*/ */
package org.alfresco.repo.security.authority; package org.alfresco.repo.security.authority;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.alfresco.model.ContentModel; import org.alfresco.model.ContentModel;
import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.permissions.PermissionServiceSPI;
import org.alfresco.repo.security.permissions.PermissionServiceSPI; import org.alfresco.repo.tenant.TenantService;
import org.alfresco.repo.tenant.TenantService; import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter;
import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.service.cmr.security.AuthenticationService; import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.AuthorityService; import org.alfresco.service.cmr.security.AuthorityType;
import org.alfresco.service.cmr.security.AuthorityType; import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.cmr.security.PermissionService; import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.cmr.security.PersonService; import org.apache.commons.logging.Log;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.InitializingBean;
/**
/** * The default implementation of the authority service.
* The default implementation of the authority service. *
* * @author Andy Hind
* @author Andy Hind */
*/ public class AuthorityServiceImpl implements AuthorityService, InitializingBean
public class AuthorityServiceImpl implements AuthorityService, InitializingBean {
{ private static Log logger = LogFactory.getLog(AuthorityServiceImpl.class);
private static Log logger = LogFactory.getLog(AuthorityServiceImpl.class);
private PersonService personService;
private PersonService personService;
private NodeService nodeService;
private NodeService nodeService;
private TenantService tenantService;
private TenantService tenantService;
private AuthorityDAO authorityDAO;
private AuthorityDAO authorityDAO;
private AuthenticationService authenticationService;
private AuthenticationService authenticationService;
private PermissionServiceSPI permissionServiceSPI;
private PermissionServiceSPI permissionServiceSPI;
private Set<String> adminSet = Collections.singleton(PermissionService.ADMINISTRATOR_AUTHORITY);
private Set<String> adminSet = Collections.singleton(PermissionService.ADMINISTRATOR_AUTHORITY);
private Set<String> guestSet = Collections.singleton(PermissionService.GUEST_AUTHORITY);
private Set<String> guestSet = Collections.singleton(PermissionService.GUEST_AUTHORITY);
private Set<String> allSet = Collections.singleton(PermissionService.ALL_AUTHORITIES);
private Set<String> allSet = Collections.singleton(PermissionService.ALL_AUTHORITIES);
private Set<String> adminGroups = Collections.emptySet();
private Set<String> adminGroups = Collections.emptySet();
public AuthorityServiceImpl()
public AuthorityServiceImpl() {
{ super();
super(); }
}
public void setNodeService(NodeService nodeService)
public void setNodeService(NodeService nodeService) {
{ this.nodeService = nodeService;
this.nodeService = nodeService; }
}
public void setTenantService(TenantService tenantService)
public void setTenantService(TenantService tenantService) {
{ this.tenantService = tenantService;
this.tenantService = tenantService; }
}
public void setPersonService(PersonService personService)
public void setPersonService(PersonService personService) {
{ this.personService = personService;
this.personService = personService; }
}
public void setAuthorityDAO(AuthorityDAO authorityDAO)
public void setAuthorityDAO(AuthorityDAO authorityDAO) {
{ this.authorityDAO = authorityDAO;
this.authorityDAO = authorityDAO; }
}
public void setAuthenticationService(AuthenticationService authenticationService)
public void setAuthenticationService(AuthenticationService authenticationService) {
{ this.authenticationService = authenticationService;
this.authenticationService = authenticationService; }
}
public void setPermissionServiceSPI(PermissionServiceSPI permissionServiceSPI)
public void setPermissionServiceSPI(PermissionServiceSPI permissionServiceSPI) {
{ this.permissionServiceSPI = permissionServiceSPI;
this.permissionServiceSPI = permissionServiceSPI; }
}
public void setAdminGroups(Set<String> adminGroups)
public void setAuthenticationComponent(AuthenticationComponent authenticationComponent) {
{ this.adminGroups = adminGroups;
logger.warn("Bean property 'authenticationService' no longer required on 'AuthorityServiceImpl'."); }
}
/* (non-Javadoc)
public void setAdminGroups(Set<String> adminGroups) * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
{ */
this.adminGroups = adminGroups; public void afterPropertiesSet() throws Exception
} {
// Fully qualify the admin group names
/* (non-Javadoc) if (!this.adminGroups.isEmpty())
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() {
*/ Set<String> adminGroups = new HashSet<String>(this.adminGroups.size());
public void afterPropertiesSet() throws Exception for (String group : this.adminGroups)
{ {
// Fully qualify the admin group names adminGroups.add(getName(AuthorityType.GROUP, group));
if (!this.adminGroups.isEmpty()) }
{ this.adminGroups = adminGroups;
Set<String> adminGroups = new HashSet<String>(this.adminGroups.size()); }
for (String group : this.adminGroups) }
{
adminGroups.add(getName(AuthorityType.GROUP, group)); public boolean hasAdminAuthority()
} {
this.adminGroups = adminGroups; String currentUserName = AuthenticationUtil.getRunAsUser();
}
} // Determine whether the administrator role is mapped to this user or one of their groups
return ((currentUserName != null) && getAuthoritiesForUser(currentUserName).contains(PermissionService.ADMINISTRATOR_AUTHORITY));
public boolean hasAdminAuthority() }
{
String currentUserName = AuthenticationUtil.getRunAsUser(); public boolean isAdminAuthority(String authorityName)
{
// Determine whether the administrator role is mapped to this user or one of their groups String canonicalName = personService.getUserIdentifier(authorityName);
return ((currentUserName != null) && getAuthoritiesForUser(currentUserName).contains(PermissionService.ADMINISTRATOR_AUTHORITY)); if (canonicalName == null)
} {
canonicalName = authorityName;
public boolean isAdminAuthority(String authorityName) }
{
String canonicalName = personService.getUserIdentifier(authorityName); // Determine whether the administrator role is mapped to this user or one of their groups
if (canonicalName == null) return getAuthoritiesForUser(canonicalName).contains(PermissionService.ADMINISTRATOR_AUTHORITY);
{ }
canonicalName = authorityName;
} public Set<String> getAuthorities()
{
// Determine whether the administrator role is mapped to this user or one of their groups String currentUserName = AuthenticationUtil.getRunAsUser();
return getAuthoritiesForUser(canonicalName).contains(PermissionService.ADMINISTRATOR_AUTHORITY); return getAuthoritiesForUser(currentUserName);
} }
public Set<String> getAuthorities() public Set<String> getAuthoritiesForUser(String currentUserName)
{ {
String currentUserName = AuthenticationUtil.getRunAsUser(); Set<String> authorities = new HashSet<String>();
return getAuthoritiesForUser(currentUserName);
} authorities.addAll(getContainingAuthorities(null, currentUserName, false));
public Set<String> getAuthoritiesForUser(String currentUserName) // Work out mapped roles
{
Set<String> authorities = new HashSet<String>(); // Check named admin users
Set<String> adminUsers = this.authenticationService.getDefaultAdministratorUserNames();
authorities.addAll(getContainingAuthorities(null, currentUserName, false));
// note: for multi-tenancy, this currently relies on a naming convention which assumes that all tenant admins will
// Work out mapped roles // have the same base name as the default non-tenant specific admin. Typically "admin" is the default required admin user,
// although, if for example "bob" is also listed as an admin then all tenant-specific bob's will also have admin authority
// Check named admin users String currentUserBaseName = tenantService.getBaseNameUser(currentUserName);
Set<String> adminUsers = this.authenticationService.getDefaultAdministratorUserNames(); boolean isAdminUser = (adminUsers.contains(currentUserName) || adminUsers.contains(currentUserBaseName));
// note: for multi-tenancy, this currently relies on a naming convention which assumes that all tenant admins will // Check named admin groups
// have the same base name as the default non-tenant specific admin. Typically "admin" is the default required admin user, if (!isAdminUser && !adminGroups.isEmpty())
// although, if for example "bob" is also listed as an admin then all tenant-specific bob's will also have admin authority {
String currentUserBaseName = tenantService.getBaseNameUser(currentUserName); for (String authority : authorities)
boolean isAdminUser = (adminUsers.contains(currentUserName) || adminUsers.contains(currentUserBaseName)); {
if (adminGroups.contains(authority) || adminGroups.contains(tenantService.getBaseNameUser(authority)))
// Check named admin groups {
if (!isAdminUser && !adminGroups.isEmpty()) isAdminUser = true;
{ break;
for (String authority : authorities) }
{ }
if (adminGroups.contains(authority) || adminGroups.contains(tenantService.getBaseNameUser(authority))) }
{
isAdminUser = true; if (isAdminUser)
break; {
} authorities.addAll(adminSet);
} }
} if (AuthorityType.getAuthorityType(currentUserBaseName) != AuthorityType.GUEST)
{
if (isAdminUser) authorities.addAll(allSet);
{ }
authorities.addAll(adminSet); return authorities;
} }
if (AuthorityType.getAuthorityType(currentUserBaseName) != AuthorityType.GUEST)
{ public Set<String> getAllAuthorities(AuthorityType type)
authorities.addAll(allSet); {
} Set<String> authorities = new HashSet<String>();
return authorities; switch (type)
} {
case ADMIN:
public Set<String> getAllAuthorities(AuthorityType type) authorities.addAll(adminSet);
{ break;
Set<String> authorities = new HashSet<String>(); case EVERYONE:
switch (type) authorities.addAll(allSet);
{ break;
case ADMIN: case GUEST:
authorities.addAll(adminSet); authorities.addAll(guestSet);
break; break;
case EVERYONE: case GROUP:
authorities.addAll(allSet); authorities.addAll(authorityDAO.getAllAuthorities(type));
break; break;
case GUEST: case OWNER:
authorities.addAll(guestSet); break;
break; case ROLE:
case GROUP: authorities.addAll(authorityDAO.getAllAuthorities(type));
authorities.addAll(authorityDAO.getAllAuthorities(type)); break;
break; case USER:
case OWNER: for (NodeRef personRef : personService.getAllPeople())
break; {
case ROLE: authorities.add(DefaultTypeConverter.INSTANCE.convert(String.class, nodeService.getProperty(personRef,
authorities.addAll(authorityDAO.getAllAuthorities(type)); ContentModel.PROP_USERNAME)));
break; }
case USER: break;
for (NodeRef personRef : personService.getAllPeople()) default:
{ break;
authorities.add(DefaultTypeConverter.INSTANCE.convert(String.class, nodeService.getProperty(personRef, }
ContentModel.PROP_USERNAME))); return authorities;
} }
break;
default:
break;
} public Set<String> findAuthorities(AuthorityType type, String namePattern)
return authorities; {
} Set<String> authorities = new HashSet<String>();
switch (type)
{
case ADMIN:
public Set<String> findAuthorities(AuthorityType type, String namePattern) case EVERYONE:
{ case GUEST:
Set<String> authorities = new HashSet<String>(); throw new UnsupportedOperationException();
switch (type) case GROUP:
{ authorities.addAll(authorityDAO.findAuthorities(type, namePattern));
case ADMIN: break;
case EVERYONE: case OWNER:
case GUEST: case ROLE:
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
case GROUP: case USER:
authorities.addAll(authorityDAO.findAuthorities(type, namePattern)); throw new UnsupportedOperationException();
break; default:
case OWNER: break;
case ROLE: }
throw new UnsupportedOperationException(); return authorities;
case USER: }
throw new UnsupportedOperationException();
default: public void addAuthority(String parentName, String childName)
break; {
} if (AuthorityType.getAuthorityType(childName).equals(AuthorityType.USER))
return authorities; {
} if(!personService.personExists(childName))
{
public void addAuthority(String parentName, String childName) throw new AuthorityException("The person "+childName+" does not exist and can not be added to a group");
{ }
if (AuthorityType.getAuthorityType(childName).equals(AuthorityType.USER)) }
{ authorityDAO.addAuthority(parentName, childName);
if(!personService.personExists(childName)) }
{
throw new AuthorityException("The person "+childName+" does not exist and can not be added to a group"); private void checkTypeIsMutable(AuthorityType type)
} {
} if((type == AuthorityType.GROUP) || (type == AuthorityType.ROLE))
authorityDAO.addAuthority(parentName, childName); {
} return;
}
private void checkTypeIsMutable(AuthorityType type) else
{ {
if((type == AuthorityType.GROUP) || (type == AuthorityType.ROLE)) throw new AuthorityException("Trying to modify a fixed authority");
{ }
return; }
}
else public String createAuthority(AuthorityType type, String parentName, String shortName)
{ {
throw new AuthorityException("Trying to modify a fixed authority"); return createAuthority(type, parentName, shortName, shortName);
} }
}
public void deleteAuthority(String name)
public String createAuthority(AuthorityType type, String parentName, String shortName) {
{ AuthorityType type = AuthorityType.getAuthorityType(name);
return createAuthority(type, parentName, shortName, shortName); checkTypeIsMutable(type);
} authorityDAO.deleteAuthority(name);
permissionServiceSPI.deletePermissions(name);
public void deleteAuthority(String name) }
{
AuthorityType type = AuthorityType.getAuthorityType(name); public Set<String> getAllRootAuthorities(AuthorityType type)
checkTypeIsMutable(type); {
authorityDAO.deleteAuthority(name); return authorityDAO.getAllRootAuthorities(type);
permissionServiceSPI.deletePermissions(name); }
}
public Set<String> getContainedAuthorities(AuthorityType type, String name, boolean immediate)
public Set<String> getAllRootAuthorities(AuthorityType type) {
{ return authorityDAO.getContainedAuthorities(type, name, immediate);
return authorityDAO.getAllRootAuthorities(type); }
}
public Set<String> getContainingAuthorities(AuthorityType type, String name, boolean immediate)
public Set<String> getContainedAuthorities(AuthorityType type, String name, boolean immediate) {
{ return authorityDAO.getContainingAuthorities(type, name, immediate);
return authorityDAO.getContainedAuthorities(type, name, immediate); }
}
public String getName(AuthorityType type, String shortName)
public Set<String> getContainingAuthorities(AuthorityType type, String name, boolean immediate) {
{ if (type.isFixedString())
return authorityDAO.getContainingAuthorities(type, name, immediate); {
} return type.getFixedString();
}
public String getName(AuthorityType type, String shortName) else if (type.isPrefixed())
{ {
if (type.isFixedString()) return type.getPrefixString() + shortName;
{ }
return type.getFixedString(); else
} {
else if (type.isPrefixed()) return shortName;
{ }
return type.getPrefixString() + shortName; }
}
else public String getShortName(String name)
{ {
return shortName; AuthorityType type = AuthorityType.getAuthorityType(name);
} if (type.isFixedString())
} {
return "";
public String getShortName(String name) }
{ else if (type.isPrefixed())
AuthorityType type = AuthorityType.getAuthorityType(name); {
if (type.isFixedString()) return name.substring(type.getPrefixString().length());
{ }
return ""; else
} {
else if (type.isPrefixed()) return name;
{ }
return name.substring(type.getPrefixString().length());
} }
else
{ public void removeAuthority(String parentName, String childName)
return name; {
} authorityDAO.removeAuthority(parentName, childName);
}
}
public boolean authorityExists(String name)
public void removeAuthority(String parentName, String childName) {
{ return authorityDAO.authorityExists(name);
authorityDAO.removeAuthority(parentName, childName); }
}
public String createAuthority(AuthorityType type, String parentName, String shortName, String authorityDisplayName)
public boolean authorityExists(String name) {
{ checkTypeIsMutable(type);
return authorityDAO.authorityExists(name); String name = getName(type, shortName);
} authorityDAO.createAuthority(parentName, name, authorityDisplayName);
return name;
public String createAuthority(AuthorityType type, String parentName, String shortName, String authorityDisplayName) }
{
checkTypeIsMutable(type); public String getAuthorityDisplayName(String name)
String name = getName(type, shortName); {
authorityDAO.createAuthority(parentName, name, authorityDisplayName); String displayName = authorityDAO.getAuthorityDisplayName(name);
return name; if(displayName == null)
} {
displayName = getShortName(name);
public String getAuthorityDisplayName(String name) }
{ return displayName;
String displayName = authorityDAO.getAuthorityDisplayName(name); }
if(displayName == null)
{ public void setAuthorityDisplayName(String authorityName, String authorityDisplayName)
displayName = getShortName(name); {
} AuthorityType type = AuthorityType.getAuthorityType(authorityName);
return displayName; checkTypeIsMutable(type);
} authorityDAO.setAuthorityDisplayName(authorityName, authorityDisplayName);
}
public void setAuthorityDisplayName(String authorityName, String authorityDisplayName)
{ }
AuthorityType type = AuthorityType.getAuthorityType(authorityName);
checkTypeIsMutable(type);
authorityDAO.setAuthorityDisplayName(authorityName, authorityDisplayName);
}
}

View File

@@ -1,287 +1,287 @@
/* /*
* Copyright (C) 2005-2007 Alfresco Software Limited. * Copyright (C) 2005-2007 Alfresco Software Limited.
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2 * as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. * of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* As a special exception to the terms and conditions of version 2.0 of * As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre * the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's * and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have recieved a copy of the text describing * FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here: * the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing" * http://www.alfresco.com/legal/licensing"
*/ */
package org.alfresco.repo.security.authority; package org.alfresco.repo.security.authority;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.alfresco.model.ContentModel; import org.alfresco.model.ContentModel;
import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.repo.tenant.TenantService; import org.alfresco.repo.tenant.TenantService;
import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter;
import org.alfresco.service.cmr.security.AuthorityService; import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.AuthorityType; import org.alfresco.service.cmr.security.AuthorityType;
import org.alfresco.service.cmr.security.PermissionService; import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.cmr.security.PersonService; import org.alfresco.service.cmr.security.PersonService;
/** /**
* The default implementation of the authority service. * The default implementation of the authority service.
* *
* @author Andy Hind * @author Andy Hind
*/ */
public class SimpleAuthorityServiceImpl implements AuthorityService public class SimpleAuthorityServiceImpl implements AuthorityService
{ {
private PersonService personService; private PersonService personService;
private NodeService nodeService; private NodeService nodeService;
private Set<String> adminSet = Collections.singleton(PermissionService.ADMINISTRATOR_AUTHORITY); private Set<String> adminSet = Collections.singleton(PermissionService.ADMINISTRATOR_AUTHORITY);
private Set<String> guestSet = Collections.singleton(PermissionService.GUEST_AUTHORITY); private Set<String> guestSet = Collections.singleton(PermissionService.GUEST_AUTHORITY);
private Set<String> allSet = Collections.singleton(PermissionService.ALL_AUTHORITIES); private Set<String> allSet = Collections.singleton(PermissionService.ALL_AUTHORITIES);
private Set<String> adminUsers; private Set<String> adminUsers;
private AuthenticationComponent authenticationComponent; private AuthenticationContext authenticationContext;
private TenantService tenantService; private TenantService tenantService;
public SimpleAuthorityServiceImpl() public SimpleAuthorityServiceImpl()
{ {
super(); super();
} }
public void setNodeService(NodeService nodeService) public void setNodeService(NodeService nodeService)
{ {
this.nodeService = nodeService; this.nodeService = nodeService;
} }
public void setPersonService(PersonService personService) public void setPersonService(PersonService personService)
{ {
this.personService = personService; this.personService = personService;
} }
public void setTenantService(TenantService tenantService) public void setTenantService(TenantService tenantService)
{ {
this.tenantService = tenantService; this.tenantService = tenantService;
} }
/** /**
* Currently the admin authority is granted only to the ALFRESCO_ADMIN_USER * Currently the admin authority is granted only to the ALFRESCO_ADMIN_USER
* user. * user.
*/ */
public boolean hasAdminAuthority() public boolean hasAdminAuthority()
{ {
String currentUserName = authenticationComponent.getCurrentUserName(); String currentUserName = authenticationContext.getCurrentUserName();
// note: for MT, this currently relies on a naming convention which assumes that all tenant admins will // note: for MT, this currently relies on a naming convention which assumes that all tenant admins will
// have the same base name as the default non-tenant specific admin. Typically "admin" is the default required admin user, // have the same base name as the default non-tenant specific admin. Typically "admin" is the default required admin user,
// although, if for example "bob" is also listed as an admin then all tenant-specific bob's will also have admin authority // although, if for example "bob" is also listed as an admin then all tenant-specific bob's will also have admin authority
return ((currentUserName != null) && (adminUsers.contains(currentUserName) || adminUsers.contains(tenantService.getBaseNameUser(currentUserName)))); return ((currentUserName != null) && (adminUsers.contains(currentUserName) || adminUsers.contains(tenantService.getBaseNameUser(currentUserName))));
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.alfresco.service.cmr.security.AuthorityService#isAdminAuthority(java.lang.String) * @see org.alfresco.service.cmr.security.AuthorityService#isAdminAuthority(java.lang.String)
*/ */
public boolean isAdminAuthority(String authorityName) public boolean isAdminAuthority(String authorityName)
{ {
String canonicalName = personService.getUserIdentifier(authorityName); String canonicalName = personService.getUserIdentifier(authorityName);
if (canonicalName == null) if (canonicalName == null)
{ {
canonicalName = authorityName; canonicalName = authorityName;
} }
return adminUsers.contains(canonicalName); return adminUsers.contains(canonicalName);
} }
// IOC // IOC
public void setAuthenticationComponent(AuthenticationComponent authenticationComponent) public void setAuthenticationContext(AuthenticationContext authenticationContext)
{ {
this.authenticationComponent = authenticationComponent; this.authenticationContext = authenticationContext;
} }
public void setAdminUsers(Set<String> adminUsers) public void setAdminUsers(Set<String> adminUsers)
{ {
this.adminUsers = adminUsers; this.adminUsers = adminUsers;
} }
public Set<String> getAuthorities() public Set<String> getAuthorities()
{ {
Set<String> authorities = new HashSet<String>(); Set<String> authorities = new HashSet<String>();
String currentUserName = authenticationComponent.getCurrentUserName(); String currentUserName = authenticationContext.getCurrentUserName();
if (adminUsers.contains(currentUserName)) if (adminUsers.contains(currentUserName))
{ {
authorities.addAll(adminSet); authorities.addAll(adminSet);
} }
if(AuthorityType.getAuthorityType(currentUserName) != AuthorityType.GUEST) if(AuthorityType.getAuthorityType(currentUserName) != AuthorityType.GUEST)
{ {
authorities.addAll(allSet); authorities.addAll(allSet);
} }
return authorities; return authorities;
} }
public Set<String> getAllAuthorities(AuthorityType type) public Set<String> getAllAuthorities(AuthorityType type)
{ {
Set<String> authorities = new HashSet<String>(); Set<String> authorities = new HashSet<String>();
switch (type) switch (type)
{ {
case ADMIN: case ADMIN:
authorities.addAll(adminSet); authorities.addAll(adminSet);
break; break;
case EVERYONE: case EVERYONE:
authorities.addAll(allSet); authorities.addAll(allSet);
break; break;
case GUEST: case GUEST:
authorities.addAll(guestSet); authorities.addAll(guestSet);
break; break;
case GROUP: case GROUP:
authorities.addAll(allSet); authorities.addAll(allSet);
break; break;
case OWNER: case OWNER:
break; break;
case ROLE: case ROLE:
break; break;
case USER: case USER:
for (NodeRef personRef : personService.getAllPeople()) for (NodeRef personRef : personService.getAllPeople())
{ {
authorities.add(DefaultTypeConverter.INSTANCE.convert(String.class, nodeService.getProperty(personRef, authorities.add(DefaultTypeConverter.INSTANCE.convert(String.class, nodeService.getProperty(personRef,
ContentModel.PROP_USERNAME))); ContentModel.PROP_USERNAME)));
} }
break; break;
default: default:
break; break;
} }
return authorities; return authorities;
} }
public Set<String> findAuthorities(AuthorityType type, String namePattern) public Set<String> findAuthorities(AuthorityType type, String namePattern)
{ {
return Collections.<String>emptySet(); return Collections.<String>emptySet();
} }
public void addAuthority(String parentName, String childName) public void addAuthority(String parentName, String childName)
{ {
} }
public String createAuthority(AuthorityType type, String parentName, String shortName) public String createAuthority(AuthorityType type, String parentName, String shortName)
{ {
return ""; return "";
} }
public void deleteAuthority(String name) public void deleteAuthority(String name)
{ {
} }
public Set<String> getAllRootAuthorities(AuthorityType type) public Set<String> getAllRootAuthorities(AuthorityType type)
{ {
return getAllAuthorities(type); return getAllAuthorities(type);
} }
public Set<String> getContainedAuthorities(AuthorityType type, String name, boolean immediate) public Set<String> getContainedAuthorities(AuthorityType type, String name, boolean immediate)
{ {
return Collections.<String>emptySet(); return Collections.<String>emptySet();
} }
public Set<String> getContainingAuthorities(AuthorityType type, String name, boolean immediate) public Set<String> getContainingAuthorities(AuthorityType type, String name, boolean immediate)
{ {
return Collections.<String>emptySet(); return Collections.<String>emptySet();
} }
public String getName(AuthorityType type, String shortName) public String getName(AuthorityType type, String shortName)
{ {
if (type.isFixedString()) if (type.isFixedString())
{ {
return type.getFixedString(); return type.getFixedString();
} }
else if (type.isPrefixed()) else if (type.isPrefixed())
{ {
return type.getPrefixString() + shortName; return type.getPrefixString() + shortName;
} }
else else
{ {
return shortName; return shortName;
} }
} }
public String getShortName(String name) public String getShortName(String name)
{ {
AuthorityType type = AuthorityType.getAuthorityType(name); AuthorityType type = AuthorityType.getAuthorityType(name);
if (type.isFixedString()) if (type.isFixedString())
{ {
return ""; return "";
} }
else if (type.isPrefixed()) else if (type.isPrefixed())
{ {
return name.substring(type.getPrefixString().length()); return name.substring(type.getPrefixString().length());
} }
else else
{ {
return name; return name;
} }
} }
public void removeAuthority(String parentName, String childName) public void removeAuthority(String parentName, String childName)
{ {
} }
public boolean authorityExists(String name) public boolean authorityExists(String name)
{ {
return false; return false;
} }
public Set<String> getAuthoritiesForUser(String currentUserName) public Set<String> getAuthoritiesForUser(String currentUserName)
{ {
Set<String> authorities = new HashSet<String>(); Set<String> authorities = new HashSet<String>();
if (adminUsers.contains(currentUserName)) if (adminUsers.contains(currentUserName))
{ {
authorities.addAll(adminSet); authorities.addAll(adminSet);
} }
if(AuthorityType.getAuthorityType(currentUserName) != AuthorityType.GUEST) if(AuthorityType.getAuthorityType(currentUserName) != AuthorityType.GUEST)
{ {
authorities.addAll(allSet); authorities.addAll(allSet);
} }
return authorities; return authorities;
} }
public String createAuthority(AuthorityType type, String parentName, String shortName, String authorityDisplayName) public String createAuthority(AuthorityType type, String parentName, String shortName, String authorityDisplayName)
{ {
return ""; return "";
} }
public String getAuthorityDisplayName(String name) public String getAuthorityDisplayName(String name)
{ {
return ""; return "";
} }
public void setAuthorityDisplayName(String authorityName, String authorityDisplayName) public void setAuthorityDisplayName(String authorityName, String authorityDisplayName)
{ {
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -34,7 +34,7 @@ import org.alfresco.model.ContentModel;
import org.alfresco.repo.node.NodeServicePolicies; import org.alfresco.repo.node.NodeServicePolicies;
import org.alfresco.repo.policy.JavaBehaviour; import org.alfresco.repo.policy.JavaBehaviour;
import org.alfresco.repo.policy.PolicyComponent; import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.repo.tenant.TenantService; import org.alfresco.repo.tenant.TenantService;
import org.alfresco.repo.transaction.AlfrescoTransactionSupport; import org.alfresco.repo.transaction.AlfrescoTransactionSupport;
import org.alfresco.service.cmr.repository.ContentData; import org.alfresco.service.cmr.repository.ContentData;
@@ -73,7 +73,7 @@ public class ContentUsageImpl implements ContentUsageService,
private PersonService personService; private PersonService personService;
private PolicyComponent policyComponent; private PolicyComponent policyComponent;
private UsageService usageService; private UsageService usageService;
private AuthenticationComponent authenticationComponent; private AuthenticationContext authenticationContext;
private TenantService tenantService; private TenantService tenantService;
private boolean enabled = true; private boolean enabled = true;
@@ -100,9 +100,9 @@ public class ContentUsageImpl implements ContentUsageService,
this.policyComponent = policyComponent; this.policyComponent = policyComponent;
} }
public void setAuthenticationComponent(AuthenticationComponent authenticationComponent) public void setAuthenticationContext(AuthenticationContext authenticationContext)
{ {
this.authenticationComponent = authenticationComponent; this.authenticationContext = authenticationContext;
} }
public void setTenantService(TenantService tenantService) public void setTenantService(TenantService tenantService)
@@ -344,7 +344,7 @@ public class ContentUsageImpl implements ContentUsageService,
private void incrementUserUsage(String userName, long contentSize, NodeRef contentNodeRef) private void incrementUserUsage(String userName, long contentSize, NodeRef contentNodeRef)
{ {
if (! authenticationComponent.isSystemUserName(userName)) if (! authenticationContext.isSystemUserName(userName))
{ {
// increment usage - add positive delta // increment usage - add positive delta
if (logger.isDebugEnabled()) logger.debug("incrementUserUsage: username="+userName+", contentSize="+contentSize+", contentNodeRef="+contentNodeRef); if (logger.isDebugEnabled()) logger.debug("incrementUserUsage: username="+userName+", contentSize="+contentSize+", contentNodeRef="+contentNodeRef);
@@ -376,7 +376,7 @@ public class ContentUsageImpl implements ContentUsageService,
private void decrementUserUsage(String userName, long contentSize, NodeRef contentNodeRef) private void decrementUserUsage(String userName, long contentSize, NodeRef contentNodeRef)
{ {
if (! authenticationComponent.isSystemUserName(userName)) if (! authenticationContext.isSystemUserName(userName))
{ {
// decrement usage - add negative delta // decrement usage - add negative delta
if (logger.isDebugEnabled()) logger.debug("decrementUserUsage: username="+userName+", contentSize="+contentSize+", contentNodeRef="+contentNodeRef); if (logger.isDebugEnabled()) logger.debug("decrementUserUsage: username="+userName+", contentSize="+contentSize+", contentNodeRef="+contentNodeRef);

View File

@@ -37,7 +37,7 @@ import org.alfresco.model.ContentModel;
import org.alfresco.repo.dictionary.DictionaryBootstrap; import org.alfresco.repo.dictionary.DictionaryBootstrap;
import org.alfresco.repo.dictionary.DictionaryDAO; import org.alfresco.repo.dictionary.DictionaryDAO;
import org.alfresco.repo.dictionary.RepositoryLocation; import org.alfresco.repo.dictionary.RepositoryLocation;
import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.tenant.TenantAdminService; import org.alfresco.repo.tenant.TenantAdminService;
@@ -81,7 +81,7 @@ public class WorkflowDeployer extends AbstractLifecycleBean
private boolean allowWrite = true; private boolean allowWrite = true;
private TransactionService transactionService; private TransactionService transactionService;
private WorkflowService workflowService; private WorkflowService workflowService;
private AuthenticationComponent authenticationComponent; private AuthenticationContext authenticationContext;
private DictionaryDAO dictionaryDAO; private DictionaryDAO dictionaryDAO;
private List<Properties> workflowDefinitions; private List<Properties> workflowDefinitions;
private List<String> models = new ArrayList<String>(); private List<String> models = new ArrayList<String>();
@@ -130,11 +130,11 @@ public class WorkflowDeployer extends AbstractLifecycleBean
/** /**
* Set the authentication component * Set the authentication component
* *
* @param authenticationComponent * @param authenticationContext
*/ */
public void setAuthenticationComponent(AuthenticationComponent authenticationComponent) public void setAuthenticationContext(AuthenticationContext authenticationContext)
{ {
this.authenticationComponent = authenticationComponent; this.authenticationContext = authenticationContext;
} }
/** /**
@@ -234,7 +234,7 @@ public class WorkflowDeployer extends AbstractLifecycleBean
{ {
throw new ImporterException("Transaction Service must be provided"); throw new ImporterException("Transaction Service must be provided");
} }
if (authenticationComponent == null) if (authenticationContext == null)
{ {
throw new ImporterException("Authentication Component must be provided"); throw new ImporterException("Authentication Component must be provided");
} }
@@ -243,10 +243,10 @@ public class WorkflowDeployer extends AbstractLifecycleBean
throw new ImporterException("Workflow Service must be provided"); throw new ImporterException("Workflow Service must be provided");
} }
String currentUser = authenticationComponent.getCurrentUserName(); String currentUser = authenticationContext.getCurrentUserName();
if (currentUser == null) if (currentUser == null)
{ {
authenticationComponent.setCurrentUser(authenticationComponent.getSystemUserName()); authenticationContext.setSystemUserAsCurrentUser();
} }
UserTransaction userTransaction = transactionService.getUserTransaction(); UserTransaction userTransaction = transactionService.getUserTransaction();
@@ -339,7 +339,7 @@ public class WorkflowDeployer extends AbstractLifecycleBean
{ {
if (currentUser == null) if (currentUser == null)
{ {
authenticationComponent.clearCurrentSecurityContext(); authenticationContext.clearCurrentSecurityContext();
} }
} }
} }