Java Code Examples for org.alfresco.repo.security.authentication.AuthenticationUtil#getAdminUserName()

The following examples show how to use org.alfresco.repo.security.authentication.AuthenticationUtil#getAdminUserName() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
public  void initContextAndCreateUser()
{
    appContext = ApplicationContextHelper.getApplicationContext();

    authenticationService = (MutableAuthenticationService) appContext.getBean("AuthenticationService");
    contentService = (ContentService) appContext.getBean("ContentService");
    nodeService = (NodeService) appContext.getBean("NodeService");
    permissionService = (PermissionService) appContext.getBean("PermissionService");
    personService = (PersonService) appContext.getBean("PersonService");
    renditionService = (RenditionService) appContext.getBean("RenditionService");
    repositoryHelper = (Repository) appContext.getBean("repositoryHelper");
    transactionService = (TransactionService) appContext.getBean("TransactionService");
    txnHelper = transactionService.getRetryingTransactionHelper();
    ownableService = (OwnableService) appContext.getBean("ownableService");

    ADMIN_USER = AuthenticationUtil.getAdminUserName();
    
    // Create a nonAdminUser
    createUser(NON_ADMIN_USER);

}
 
Example 2
@Before public void createTestSites() throws Exception
{
    ADMIN = AuthenticationUtil.getAdminUserName();
    
    final String guid = GUID.generate();
    
    // admin creates the test sites. This is how this test case was before refactoring. TODO Probably better to have a non-admin user create the sites.
    publicSite   = testSites.createSite("sitePreset", "pub" + guid,   "", "", SiteVisibility.PUBLIC,  ADMIN);
    privateSite1 = testSites.createSite("sitePreset", "priv1" + guid, "", "", SiteVisibility.PRIVATE, ADMIN);
    privateSite2 = testSites.createSite("sitePreset", "priv2" + guid, "", "", SiteVisibility.PRIVATE, ADMIN);
    modSite1     = testSites.createSite("sitePreset", "mod1" + guid,  "", "", SiteVisibility.MODERATED, ADMIN);
    modSite2     = testSites.createSite("sitePreset", "mod2" + guid, "", "",  SiteVisibility.MODERATED, ADMIN);
    log.debug("Created some test sites...");
    
    AuthenticationUtil.clearCurrentSecurityContext();
    // test site cleanup is handled automatically by the JUnit Rule.
}
 
Example 3
@Before
public void setUp()
{
    appCtx = ApplicationContextHelper.getApplicationContext();
    // The user that will create locks, this should be different from the user that queries them (ALF-19465)
    lockOwner = "jbloggs";
    // The 'current' user.
    userName = AuthenticationUtil.getAdminUserName();
    AuthenticationUtil.setFullyAuthenticatedUser(userName);
    transactionService = (TransactionService) appCtx.getBean("TransactionService");
    nodeService = (NodeService) appCtx.getBean("NodeService");
    rawNodeService = (NodeService) appCtx.getBean("dbNodeService");
    lockStore = (LockStore) appCtx.getBean("lockStore");
    rootNode = nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    interceptor = (LockableAspectInterceptor) appCtx.getBean("lockableAspectInterceptor");
    lockService = (LockService)appCtx.getBean("lockService");
    fileFolderService = (FileFolderService) appCtx.getBean("FileFolderService");
    actionService = (ActionService) appCtx.getBean("ActionService");
}
 
Example 4
@Override
protected void setUp() throws Exception
{
    super.setUp();
    ctx = getServer().getApplicationContext();

    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    transactionService = serviceRegistry.getTransactionService();
    nodeService = serviceRegistry.getNodeService();
    fileFolderService = serviceRegistry.getFileFolderService();
    namespaceService = serviceRegistry.getNamespaceService();
    txnHelper = transactionService.getRetryingTransactionHelper();
    nodeDAO = (NodeDAO)ctx.getBean("nodeDAO");
    solrTrackingComponent = (SOLRTrackingComponent) ctx.getBean("solrTrackingComponent");

    admin = AuthenticationUtil.getAdminUserName();

    AuthenticationUtil.setFullyAuthenticatedUser(admin);
    
    storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, getName() + ".1." + System.currentTimeMillis());
    rootNodeRef = nodeService.getRootNode(storeRef);
}
 
Example 5
@Override
protected String applyInternal() throws Exception {

    StringBuilder result = new StringBuilder(I18NUtil.getMessage(MSG_START));

    //If there's no RepositoryAuthenticationDao then there's no need for this patch to run
    if (authenticationDao != null)
    {
        final String adminUsername = AuthenticationUtil.getAdminUserName();
        final NodeRef userNodeRef  = authenticationDao.getUserOrNull(adminUsername);

        if (userNodeRef!= null)
        {
            Map<QName, Serializable> userProperties = nodeService.getProperties(userNodeRef);
            String sha256 = (String) userProperties.get(ContentModel.PROP_PASSWORD_SHA256);
            if (DEFAULT_SHA.equals(sha256))
            {
                // I am not going to disable any behaviours because authenticationDao.onUpdateUserProperties fires
                // that removes Authentication from the cache

                if (logger.isDebugEnabled())
                {
                    logger.debug("Removing password sha256 hash for user: " + adminUsername);
                }

                // The SHA256 is set to the default (i.e. admin) so i will remove it
                nodeService.removeProperty(userNodeRef, ContentModel.PROP_PASSWORD_SHA256);

                result.append(I18NUtil.getMessage(MSG_RESULT,adminUsername));

            }
        }
    }

    return result.toString();
}
 
Example 6
public static void runMain(ApplicationContext context, String beanName)
{
    BaseInterpreter console = getConsoleBean(context, beanName);

    console.username = AuthenticationUtil.getAdminUserName();
    console.rep();
    System.exit(0);
}
 
Example 7
public String getBaseAdminUsername()
{
    if (baseAdminUsername != null)
    {
        return baseAdminUsername;
    }
    return AuthenticationUtil.getAdminUserName();
}
 
Example 8
@Test
public void testGetDeploymentsEmpty() throws Exception
{
    // Create a new test-network, not added to the test-fixture to prevent being used
    // in other tests
    String networkName = AbstractTestFixture.TEST_DOMAIN_PREFIX + "999";
    final TestNetwork testNetwork = repoService.createNetworkWithAlias(networkName, true);
    transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        @SuppressWarnings("synthetic-access")
        public Void execute() throws Throwable
        {
            AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

            testNetwork.create();

            return null;
        }
    }, false, true);
    
    // Delete all deployments in the network
    List<org.activiti.engine.repository.Deployment> deployments = activitiProcessEngine.getRepositoryService()
        .createDeploymentQuery()
        .processDefinitionKeyLike("@" + testNetwork.getId() + "@%")
        .list();
    
    for(org.activiti.engine.repository.Deployment deployment : deployments) 
    {
        activitiProcessEngine.getRepositoryService().deleteDeployment(deployment.getId(), true);
    }
    
    // Fetch deployments using tenant-admin
    String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + testNetwork.getId();
    publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), tenantAdmin));

    DeploymentsClient deploymentsClient = publicApiClient.deploymentsClient();

    ListResponse<Deployment> deploymentResponse = deploymentsClient.getDeployments();
    assertEquals(0, deploymentResponse.getList().size());
}
 
Example 9
@BeforeClass public static void initStaticData() throws Exception
{
    AUTHORITY_SERVICE         = APP_CONTEXT_INIT.getApplicationContext().getBean("AuthorityService", AuthorityService.class);
    NAMESPACE_SERVICE         = APP_CONTEXT_INIT.getApplicationContext().getBean("namespaceService", NamespaceService.class);
    NODE_SERVICE              = APP_CONTEXT_INIT.getApplicationContext().getBean("NodeService", NodeService.class);
    NODE_ARCHIVE_SERVICE      = APP_CONTEXT_INIT.getApplicationContext().getBean("nodeArchiveService", NodeArchiveService.class);
    SITE_SERVICE              = APP_CONTEXT_INIT.getApplicationContext().getBean("siteService", SiteService.class);
    COCI_SERVICE              = APP_CONTEXT_INIT.getApplicationContext().getBean("checkOutCheckInService", CheckOutCheckInService.class);
    TRANSACTION_HELPER        = APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    PERMISSION_SERVICE        = APP_CONTEXT_INIT.getApplicationContext().getBean("permissionServiceImpl", PermissionService.class);
    AUTHENTICATION_SERVICE    = APP_CONTEXT_INIT.getApplicationContext().getBean("authenticationService", MutableAuthenticationService.class);
    PERSON_SERVICE            = APP_CONTEXT_INIT.getApplicationContext().getBean("PersonService", PersonService.class);
    FILE_FOLDER_SERVICE       = APP_CONTEXT_INIT.getApplicationContext().getBean("FileFolderService",FileFolderService.class);
    AUTHENTICATION_COMPONENT  = APP_CONTEXT_INIT.getApplicationContext().getBean("authenticationComponent",AuthenticationComponent.class);
    LOCK_SERVICE              = APP_CONTEXT_INIT.getApplicationContext().getBean("lockService",LockService.class);
    
    // We'll create this test content as admin.
    final String admin = AuthenticationUtil.getAdminUserName();
    
    TEST_SITE_NAME = GUID.generate();
    TEST_SUB_SITE_NAME = GUID.generate();
    
    final QName subSiteType = QName.createQName("testsite", "testSubsite", NAMESPACE_SERVICE);
    
    STATIC_TEST_SITES.createSite("sitePreset", TEST_SITE_NAME, "siteTitle", "siteDescription", SiteVisibility.PUBLIC, admin);
    STATIC_TEST_SITES.createSite("sitePreset", TEST_SUB_SITE_NAME, "siteTitle", "siteDescription", SiteVisibility.PUBLIC, subSiteType, admin);
    
    TEST_SITE_WITH_MEMBERS = STATIC_TEST_SITES.createTestSiteWithUserPerRole(SiteServiceImplMoreTest.class.getSimpleName(), "sitePreset", SiteVisibility.PUBLIC, admin);
}
 
Example 10
@Test
public void testGetProcessDefinitionById() throws Exception
{
    RequestContext requestContext = initApiClientWithTestUser();
    
    String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + requestContext.getNetworkId();
    RequestContext adminContext = new RequestContext(requestContext.getNetworkId(), tenantAdmin);

    String adhocKey = createProcessDefinitionKey("activitiAdhoc", requestContext);
    org.activiti.engine.repository.ProcessDefinition activitiDefinition = activitiProcessEngine.getRepositoryService()
        .createProcessDefinitionQuery()
        .processDefinitionKey(adhocKey)
        .singleResult();

    assertNotNull(activitiDefinition);

    // Get a single process definitions
    ProcessDefinitionsClient processDefinitionsClient = publicApiClient.processDefinitionsClient();
    ProcessDefinition adhocDefinition = processDefinitionsClient.findProcessDefinitionById(activitiDefinition.getId());
    assertNotNull(adhocDefinition);
    
    // Check fields of a resulting process-definition
    assertEquals(activitiDefinition.getId(), adhocDefinition.getId());
    assertEquals("activitiAdhoc", adhocDefinition.getKey());
    assertEquals(activitiDefinition.getDeploymentId(), adhocDefinition.getDeploymentId());
    assertEquals(activitiDefinition.getCategory(), adhocDefinition.getCategory());
    assertEquals(activitiDefinition.getName(), adhocDefinition.getName());
    assertEquals(activitiDefinition.getVersion(), adhocDefinition.getVersion());
    assertEquals(((ProcessDefinitionEntity) activitiDefinition).isGraphicalNotationDefined(), adhocDefinition.isGraphicNotationDefined());
    assertEquals("wf:submitAdhocTask", adhocDefinition.getStartFormResourceKey());
    
    // get process definition with admin
    publicApiClient.setRequestContext(adminContext);
    adhocDefinition = processDefinitionsClient.findProcessDefinitionById(activitiDefinition.getId());
    assertNotNull(adhocDefinition);
    
    // Check fields of a resulting process-definition
    assertEquals(activitiDefinition.getId(), adhocDefinition.getId());
    assertEquals("activitiAdhoc", adhocDefinition.getKey());
}
 
Example 11
@BeforeClass public static void initTestsContext() throws Exception
{
    testContext = ApplicationContextHelper.getApplicationContext();
    AUTHENTICATION_SERVICE = (MutableAuthenticationService)testContext.getBean("authenticationService");
    BEHAVIOUR_FILTER       = (BehaviourFilter)testContext.getBean("policyBehaviourFilter");
    DISCUSSION_SERVICE     = (DiscussionService)testContext.getBean("DiscussionService");
    NODE_SERVICE           = (NodeService)testContext.getBean("nodeService");
    PUBLIC_NODE_SERVICE    = (NodeService)testContext.getBean("NodeService");
    PERSON_SERVICE         = (PersonService)testContext.getBean("personService");
    TRANSACTION_HELPER     = (RetryingTransactionHelper)testContext.getBean("retryingTransactionHelper");
    PERMISSION_SERVICE     = (PermissionService)testContext.getBean("permissionService");
    SITE_SERVICE           = (SiteService)testContext.getBean("SiteService");
    TENANT_ADMIN_SERVICE   = testContext.getBean("tenantAdminService", TenantAdminService.class);

    ADMIN_USER = AuthenticationUtil.getAdminUserName() + "@" + TENANT_DOMAIN;

    createTenant();
    
    // Do the setup as admin
    AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER);
    TenantContextHolder.setTenantDomain(TENANT_DOMAIN);
    createUser(TEST_USER);
    
    // We need to create the test site as the test user so that they can contribute content to it in tests below.
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER);
    TenantContextHolder.setTenantDomain(TENANT_DOMAIN);
    createTestSites();
}
 
Example 12
@Override
protected void setUp() throws Exception
{
    super.setUp();
    ctx = getServer().getApplicationContext();
    repoAdminService = (RepoAdminService) ctx.getBean("RepoAdminService");
    descriptorService = (DescriptorService) ctx.getBean("DescriptorService");
    admin = AuthenticationUtil.getAdminUserName();
    guest = AuthenticationUtil.getGuestUserName();

    AuthenticationUtil.setFullyAuthenticatedUser(admin);
}
 
Example 13
@Override
protected void setUp() throws Exception
{
    super.setCustomContext(CONFIG_LOCATION);
    super.setUp();
    getServer().getApplicationContext();
    admin = AuthenticationUtil.getAdminUserName();
    AuthenticationUtil.setFullyAuthenticatedUser(admin);
}
 
Example 14
/**
 * Get default user name
 */
protected String getDefaultUserName()
{
    return AuthenticationUtil.getAdminUserName();
}
 
Example 15
public void setUp() throws Exception
{
    if (AlfrescoTransactionSupport.getTransactionReadState() != TxnReadState.TXN_NONE)
    {
        throw new AlfrescoRuntimeException(
                "A previous tests did not clean up transaction: " +
                AlfrescoTransactionSupport.getTransactionId());
    }
    
    authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
    authenticationService = (MutableAuthenticationService) ctx.getBean("authenticationService");
    authorityService = (AuthorityService) ctx.getBean("authorityService");
    pubAuthorityService = (AuthorityService) ctx.getBean("AuthorityService");
    personService = (PersonService) ctx.getBean("personService");
    authenticationDAO = (MutableAuthenticationDao) ctx.getBean("authenticationDao");
    aclDaoComponent = (AclDAO) ctx.getBean("aclDAO");
    nodeService = (NodeService) ctx.getBean("nodeService");
    authorityBridgeTableCache = (AuthorityBridgeTableAsynchronouslyRefreshedCache) ctx.getBean("authorityBridgeTableCache");
    nodeArchiveService = (NodeArchiveService) ctx.getBean("nodeArchiveService");
    policyComponent = (PolicyComponent) ctx.getBean("policyComponent");
    transactionService = (TransactionService) ctx.getBean(ServiceRegistry.TRANSACTION_SERVICE.getLocalName());
    authorityDAO = ctx.getBean("authorityDAO", AuthorityDAO.class);
    
    String defaultAdminUser = AuthenticationUtil.getAdminUserName();
    AuthenticationUtil.setFullyAuthenticatedUser(defaultAdminUser);
    
    // cleanup trashcan
    nodeArchiveService.purgeAllArchivedNodes(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    
    // note: currently depends on any existing (and/or bootstrap) group data - eg. default site "swsdp" (Sample Web Site Design Project)
    SiteService siteService = (SiteService) ctx.getBean("SiteService");
    SITE_CNT = siteService.listSites(defaultAdminUser).size();
    GRP_CNT = DEFAULT_GRP_CNT + (DEFAULT_SITE_GRP_CNT * SITE_CNT);
    ROOT_GRP_CNT = DEFAULT_GRP_CNT + (DEFAULT_SITE_ROOT_GRP_CNT * SITE_CNT);
    
    tx = transactionService.getUserTransaction();
    tx.begin();
    for (String user : getAllAuthorities(AuthorityType.USER))
    {
        if (user.equals(AuthenticationUtil.getGuestUserName()))
        {
            continue;
        }
        else if (user.equals(AuthenticationUtil.getAdminUserName()))
        {
            continue;
        }
        else
        {
            if (personService.personExists(user))
            {
                NodeRef person = personService.getPerson(user);
                NodeRef hf = DefaultTypeConverter.INSTANCE.convert(NodeRef.class, nodeService.getProperty(person, ContentModel.PROP_HOMEFOLDER));
                if (hf != null)
                {
                    nodeService.deleteNode(hf);
                }
                aclDaoComponent.deleteAccessControlEntries(user);
                personService.deletePerson(user);
            }
            if (authenticationDAO.userExists(user))
            {
                authenticationDAO.deleteUser(user);
            }
        }

    }
    tx.commit();

    tx = transactionService.getUserTransaction();
    tx.begin();

    if (!authenticationDAO.userExists("andy"))
    {
        authenticationService.createAuthentication("andy", "andy".toCharArray());
    }

    if (!authenticationDAO.userExists(AuthenticationUtil.getAdminUserName()))
    {
        authenticationService.createAuthentication(AuthenticationUtil.getAdminUserName(), "admin".toCharArray());
    }

    if (!authenticationDAO.userExists("administrator"))
    {
        authenticationService.createAuthentication("administrator", "administrator".toCharArray());
    }

}
 
Example 16
@Test
@SuppressWarnings("unchecked")
public void testCreateProcessInstanceFromOtherNetwork() throws Exception
{
    final RequestContext requestContext = initApiClientWithTestUser();
    
    org.activiti.engine.repository.ProcessDefinition processDefinition = activitiProcessEngine
            .getRepositoryService()
            .createProcessDefinitionQuery()
            .processDefinitionKey("@" + requestContext.getNetworkId() + "@activitiAdhoc")
            .singleResult();

    TestNetwork anotherNetwork = getOtherNetwork(requestContext.getNetworkId());
    String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + anotherNetwork.getId();
    RequestContext otherContext = new RequestContext(anotherNetwork.getId(), tenantAdmin);
    publicApiClient.setRequestContext(otherContext);
    
    ProcessesClient processesClient = publicApiClient.processesClient();
    
    JSONObject createProcessObject = new JSONObject();
    createProcessObject.put("processDefinitionId", processDefinition.getId());
    final JSONObject variablesObject = new JSONObject();
    variablesObject.put("bpm_dueDate", ISO8601DateFormat.format(new Date()));
    variablesObject.put("bpm_priority", 1);
    variablesObject.put("bpm_description", "test description");
    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            variablesObject.put("bpm_assignee", requestContext.getRunAsUser());
            return null;
        }
    }, requestContext.getRunAsUser(), requestContext.getNetworkId());
    
    
    createProcessObject.put("variables", variablesObject);
    
    try
    {
        processesClient.createProcess(createProcessObject.toJSONString());
    }
    catch (PublicApiException e)
    {
        assertEquals(HttpStatus.BAD_REQUEST.value(), e.getHttpResponse().getStatusCode());
    }
}
 
Example 17
public void test16DeleteArchiveAndRestoreContent()
{
    logger.info("test delete/archive & restore content");
    
    // note: CLOUD-1349 - ownership is based on fully authenticated user (else restoreNode fails for non-Admin user)
    AuthenticationUtil.clearCurrentSecurityContext();
    
    final String superAdmin = AuthenticationUtil.getAdminUserName();
    
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        public Void doWork() throws Exception
        {
            // super tenant - admin user
            deleteArchiveAndRestoreContent(superAdmin, TenantService.DEFAULT_DOMAIN);
            return null;
        }
        
    }, superAdmin);
    
    final String superAnoUser = "superAnoUser";
    
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        public Void doWork() throws Exception
        {
            createUser(superAnoUser, TenantService.DEFAULT_DOMAIN, superAnoUser);
            return null;
        }
    }, superAdmin);
    
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        public Void doWork() throws Exception
        {
            // super tenant - ano user
            deleteArchiveAndRestoreContent(superAnoUser, TenantService.DEFAULT_DOMAIN);
            
            return null;
        }
    }, superAnoUser);
    
    for (final String tenantDomain : tenants)
    {
        final String tenantUserName = tenantService.getDomainUser(TEST_USER1, tenantDomain);
        
        TenantUtil.runAsUserTenant(new TenantRunAsWork<Object>()
        {
            public Object doWork() throws Exception
            {
                deleteArchiveAndRestoreContent(tenantUserName, tenantDomain);
                
                return null;
            }
        }, tenantUserName, tenantDomain);
    }
}
 
Example 18
/**
 * @param path      cm:name based root relative path
 *                  example: /alfresco/site-data/pages/customise-user-dashboard.xml
 *                           /alfresco/site-data/components
 * @param pattern   optional pattern that is used as part of the match to aquire the surf-config
 *                  folder under the appropriate sites or user location.
 * @param create    if true create the config and folder dirs for the given path returning
 *                  the FileInfo for the last parent in the path, if false only attempt to
 *                  resolve the folder path if it exists returning the last element.
 * @param isFolder  True if the path is for a folder, false if it ends in a filename
 * 
 * @return FileInfo representing the file/folder at the specified path location (see create
 *         parameter above) or null if the supplied path does not exist in the store.
 */
private FileInfo resolveNodePath(final String path, final String pattern, final boolean create, final boolean isFolder)
{
    if (logger.isDebugEnabled())
        logger.debug("Resolving path: " + path);

    final String adminUserName = AuthenticationUtil.getAdminUserName();

    FileInfo result = null;
    if (path != null)
    {
        // break down the path into its component elements
        List<String> pathElements = new ArrayList<String>(4);
        final StringTokenizer t = new StringTokenizer(path, "/");
        // the store requires paths of the form /alfresco/site-data/<objecttype>[/<folder>]/<file>.xml
        if (t.countTokens() >= 3)
        {
            t.nextToken();  // skip /alfresco
            t.nextToken();  // skip /site-data
            // collect remaining folder path (and file)
            while (t.hasMoreTokens())
            {
                pathElements.add(t.nextToken());
            }
            
            NodeRef surfConfigRef = aquireSurfConfigRef(path + (pattern != null ? ("/" + pattern) : ""), create);
            try
            {
                if (surfConfigRef != null)
                {
                    if (create)
                    {
                        List<String> folders = isFolder ? pathElements : pathElements.subList(0, pathElements.size() - 1);
                        
                        List<FileFolderUtil.PathElementDetails> folderDetails = new ArrayList<>(pathElements.size());
                        Map<QName, Serializable> prop = new HashMap<>(2);
                        prop.put(ContentModel.PROP_IS_INDEXED, false);
                        prop.put(ContentModel.PROP_IS_CONTENT_INDEXED, false);
                        for (String element : folders)
                        {
                            Map<QName, Map<QName, Serializable>> aspects = Collections.singletonMap(ContentModel.ASPECT_INDEX_CONTROL, prop);
                            folderDetails.add(new FileFolderUtil.PathElementDetails(element, aspects));
                        }
                        // ensure folders exist down to the specified parent
                        // ALF-17729 / ALF-17796 - disable auditable on parent folders
                        Set<NodeRef> allCreatedFolders = new LinkedHashSet<>();
                        result = FileFolderUtil.makeFolders(
                                this.fileFolderService,nodeService,
                                surfConfigRef,
                                folderDetails,
                                ContentModel.TYPE_FOLDER,
                                behaviourFilter,
                                new HashSet<QName>(Arrays.asList(new QName[]{ContentModel.ASPECT_AUDITABLE})), allCreatedFolders);

                        // MNT-16371: Revoke ownership privileges for surf-config folder, to tighten access for former SiteManagers.
                        for(NodeRef nodeRef : allCreatedFolders)
                        {
                            ownableService.setOwner(nodeRef, adminUserName);
                        }
                    }
                    else
                    {
                        // perform the cm:name path lookup against our config root node
                        result = this.fileFolderService.resolveNamePath(surfConfigRef, pathElements);
                    }
                }
            }
            catch (FileNotFoundException fnfErr)
            {
                // this is a valid condition - we return null to indicate failed lookup
            }
        }
    }
    return result;
}
 
Example 19
@Override
protected void setUp() throws Exception
{
    super.setUp();
    ctx = getServer().getApplicationContext();
    //MNT-10807 : Auditing does not take into account audit.filter.alfresco-access.transaction.user
    UserAuditFilter userAuditFilter = new UserAuditFilter();
    userAuditFilter.setUserFilterPattern("System;.*");
    userAuditFilter.afterPropertiesSet();
    AuditComponent auditComponent = (AuditComponent) ctx.getBean("auditComponent");
    auditComponent.setUserAuditFilter(userAuditFilter);
    AuditServiceImpl auditServiceImpl = (AuditServiceImpl) ctx.getBean("auditService");
    auditServiceImpl.setAuditComponent(auditComponent);
    authenticationService = (AuthenticationService) ctx.getBean("AuthenticationService");
    auditService = (AuditService) ctx.getBean("AuditService");
    searchService = (SearchService) ctx.getBean("SearchService");
    repositoryHelper = (Repository)getServer().getApplicationContext().getBean("repositoryHelper");
    fileFolderService = (FileFolderService)getServer().getApplicationContext().getBean("FileFolderService");
    admin = AuthenticationUtil.getAdminUserName();

    // Register the test models
    AuditModelRegistryImpl auditModelRegistry = (AuditModelRegistryImpl) ctx.getBean("auditModel.modelRegistry");
    URL testModelUrl = ResourceUtils.getURL("classpath:alfresco/testaudit/alfresco-audit-test-repository.xml");
    URL testModelUrl1 = ResourceUtils.getURL("classpath:alfresco/testaudit/alfresco-audit-test-mnt-16748.xml");
    auditModelRegistry.registerModel(testModelUrl);
    auditModelRegistry.registerModel(testModelUrl1);
    auditModelRegistry.loadAuditModels();
    
    AuthenticationUtil.setFullyAuthenticatedUser(admin);
    
    wasGloballyEnabled = auditService.isAuditEnabled();
    wasRepoEnabled = auditService.isAuditEnabled(APP_REPOTEST_NAME, APP_REPOTEST_PATH);
    wasSearchEnabled = auditService.isAuditEnabled(APP_SEARCHTEST_NAME, APP_SEARCHTEST_PATH);
    // Only enable if required
    if (!wasGloballyEnabled)
    {
        auditService.setAuditEnabled(true);
        wasGloballyEnabled = auditService.isAuditEnabled();
        if (!wasGloballyEnabled)
        {
            fail("Failed to enable global audit for test");
        }
    }
    if (!wasRepoEnabled)
    {
        auditService.enableAudit(APP_REPOTEST_NAME, APP_REPOTEST_PATH);
        wasRepoEnabled = auditService.isAuditEnabled(APP_REPOTEST_NAME, APP_REPOTEST_PATH);
        if (!wasRepoEnabled)
        {
            fail("Failed to enable repo audit for test");
        }
    }
    if (!wasSearchEnabled)
    {
        auditService.enableAudit(APP_SEARCHTEST_NAME, APP_SEARCHTEST_PATH);
        wasSearchEnabled = auditService.isAuditEnabled(APP_SEARCHTEST_NAME, APP_SEARCHTEST_PATH);
        if (!wasSearchEnabled)
        {
            fail("Failed to enable search audit for test");
        }
    }
}
 
Example 20
public void testCreateTakeOwnershipAcrossTx() throws Exception
{
    if(!contentUsageImpl.getEnabled())
    {
        return;
    }
    
    runAs(TEST_USER);
    
    assertEquals(0, contentUsageImpl.getUserUsage(TEST_USER));
    
    // Create a folder
    Map<QName, Serializable> folderProps = new HashMap<QName, Serializable>(1);
    folderProps.put(ContentModel.PROP_NAME, "testFolder");
    NodeRef folder = this.nodeService.createNode(
            this.rootNodeRef, 
            ContentModel.ASSOC_CHILDREN, 
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "testFolder"),
            ContentModel.TYPE_FOLDER).getChildRef();
    
    // add content (in this case, some "panagrams")
    
    NodeRef content1 = addTextContent(folder, "text1.txt", "The quick brown fox jumps over the lazy dog"); // + 43
    assertEquals(43, contentUsageImpl.getUserUsage(TEST_USER));
    
    NodeRef content2 = addTextContent(folder, "text2.txt", "Amazingly few discotheques provide jukeboxes", true); // + 44
    assertEquals(87, contentUsageImpl.getUserUsage(TEST_USER));
    
    NodeRef content3 = addTextContent(folder, "text3.txt", "All questions asked by five watch experts amazed the judge"); // + 58
    assertEquals(145, contentUsageImpl.getUserUsage(TEST_USER));
    
    testTX.commit();
    
    String ADMIN = AuthenticationUtil.getAdminUserName();
    
    testTX = transactionService.getUserTransaction();
    testTX.begin();
    
    runAs(ADMIN);
    
    long before = contentUsageImpl.getUserUsage(ADMIN);
    
    takeOwnership(content1); // +/- 43 (test user -> admin)
    
    assertEquals(102, contentUsageImpl.getUserUsage(TEST_USER));
    assertEquals(before+43, contentUsageImpl.getUserUsage(ADMIN));
    
    takeOwnership(content2); // +/- 44 (test user -> admin)
    
    assertEquals(58, contentUsageImpl.getUserUsage(TEST_USER));
    assertEquals(before+87, contentUsageImpl.getUserUsage(ADMIN));
    
    testTX.commit();
    
    testTX = transactionService.getUserTransaction();
    testTX.begin();
    
    runAs(TEST_USER);
    
    takeOwnership(content1); // +/- 43 (admin -> test user)
    
    assertEquals(101, contentUsageImpl.getUserUsage(TEST_USER));
    assertEquals(before+44, contentUsageImpl.getUserUsage(ADMIN));
    
    takeOwnership(content3); // note: already the creator
    
    assertEquals(101, contentUsageImpl.getUserUsage(TEST_USER));
    assertEquals(before+44, contentUsageImpl.getUserUsage(ADMIN));
    
    // delete folder to cleanup
    delete(folder);
}