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

The following examples show how to use org.alfresco.repo.security.authentication.AuthenticationUtil#setRunAsUserSystem() . 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
private Object runAsSystem(MethodInvocation invocation) throws Throwable
{
    Object ret = null;

    // We're creating in enhanced mode and have a matching filename or path. Switch to
    // the system user to do the operation.

    AuthenticationUtil.pushAuthentication();
    try
    {
        AuthenticationUtil.setRunAsUserSystem();
        ret = invocation.proceed();
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
    
    return ret;
}
 
Example 2
@Override
protected void setUp() throws Exception
{
    applicationContext = ApplicationContextHelper.getApplicationContext();
    nodeService = (NodeService)applicationContext.getBean("nodeService");
    repositoryHelper = (Repository)this.applicationContext.getBean("repositoryHelper");
    transactionService = (TransactionService)applicationContext.getBean("transactionService");
    
    ChildApplicationContextFactory fileServersSubSystem = (ChildApplicationContextFactory) applicationContext.getBean("fileServers");
    assertNotNull("fileServers subsystem is null", fileServersSubSystem);
    lockKeeper =  (LockKeeper)fileServersSubSystem.getApplicationContext().getBean("lockKeeper");
    
	assertNotNull("nodeService is null", nodeService);
	assertNotNull("lockKeeper is null", lockKeeper);
	assertNotNull("transactionService is null", transactionService);

    
    AuthenticationUtil.setRunAsUserSystem();
    AuthenticationUtil.setFullyAuthenticatedUser("bugsBunny");
}
 
Example 3
/**
 * Main entry point.
 */
public static void main(String[] args)
{
    try
    {
        TestWebScriptServer testServer = getTestServer();
        AuthenticationUtil.setRunAsUserSystem();
        testServer.rep();
    }
    catch(Throwable e)
    {
        StringWriter strWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(strWriter);
        e.printStackTrace(printWriter);
        System.out.println(strWriter.toString());
    }
    finally
    {
        System.exit(0);
    }
}
 
Example 4
@Override
protected void setUp() throws Exception
{
    ctx = ApplicationContextHelper.getApplicationContext();
    if (AlfrescoTransactionSupport.isActualTransactionActive())
    {
        fail("Test started with transaction in progress");
    }
    
    transactionService = (TransactionService) ctx.getBean("transactionComponent");
    repoUsageComponent = (RepoUsageComponent) ctx.getBean("repoUsageComponent");
    jobLockService = (JobLockService) ctx.getBean("jobLockService");
    
    AuthenticationUtil.setRunAsUserSystem();
    
    txn = transactionService.getUserTransaction();
    txn.begin();
    
    restrictionsBefore = repoUsageComponent.getRestrictions();
}
 
Example 5
@AfterClass
public static void tearDownAfterClass() throws Exception
{
    AuthenticationUtil.setRunAsUserSystem();

    System.out.println(NodeStoreInspector.dumpNodeStore(nodeService, storeRef));
    
    nodeService.deleteStore(storeRef);
    
    try
    {
        authenticationComponent.clearCurrentSecurityContext();
    }
    catch (Throwable e)
    {
        // ignore
    }
    
    properties = null;
    auditor = null;
}
 
Example 6
@Override
public void setUp() throws Exception
{
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    // Set the services
    this.transactionService = serviceRegistry.getTransactionService();
    this.nodeService = serviceRegistry.getNodeService();
    this.contentService = serviceRegistry.getContentService();
    this.behaviourFilter = (BehaviourFilter) ctx.getBean("policyBehaviourFilter");
    
    AuthenticationUtil.setRunAsUserSystem();
    
    // Create the store and get the root node reference
    this.storeRef = this.nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
    this.rootNodeRef = this.nodeService.getRootNode(storeRef);
}
 
Example 7
public void onBootstrap()
{
    if (!enabled)
    {
        return;
    }
    
    nodesCache.clear();
    
    AuthenticationUtil.setRunAsUserSystem();
    try
    {
        StoreRef storeRef = new StoreRef(storeName);

        if (nodeService.exists(storeRef) == false)
        {
            throw new RuntimeException("No store for path: " + storeName);
        }

        NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);

        List<NodeRef> nodeRefs = getSearchService().selectNodes(storeRootNodeRef, rootPath, null, getNamespaceService(), false);

        if (nodeRefs.size() > 1)
        {
            throw new RuntimeException("Multiple possible children for : \n" + "   path: " + rootPath + "\n" + "   results: " + nodeRefs);
        }
        else if (nodeRefs.size() == 0)
        {
            throw new RuntimeException("Node is not found for : \n" + "   root path: " + rootPath);
        }

        defaultNode = nodeRefs.get(0);
    }
    finally
    {
        AuthenticationUtil.clearCurrentSecurityContext();
    }
}
 
Example 8
public void execute(final JobExecutionContext jobContext)
{
   // Do all this work as system
   // TODO - See if we can pinch some bits from the existing scheduled
   //  actions around who to run as
   AuthenticationUtil.setRunAsUserSystem();
   
   transactionService.getRetryingTransactionHelper().doInTransaction(
      new RetryingTransactionCallback<Void>() {
        public Void execute() throws Throwable {
           // Update the last run time on the schedule
           NodeRef scheduleNodeRef = new NodeRef(
                 jobContext.getMergedJobDataMap().getString(JOB_SCHEDULE_NODEREF)
           );
           nodeService.setProperty(
                  scheduleNodeRef, 
                  ActionModel.PROP_LAST_EXECUTED_AT, 
                  new Date()
           );
           
           // Create the action object
           NodeRef actionNodeRef = new NodeRef(
                 jobContext.getMergedJobDataMap().getString(JOB_ACTION_NODEREF)
           );
           Action action = runtimeActionService.createAction(
                 actionNodeRef
           );
           
           // Have it executed asynchronously
           actionService.executeAction(
                 action, (NodeRef)null,
                 false, true
           );
           
           // Real work starts when the transaction completes
           return null;
        }
      }, false, true
   );
}
 
Example 9
public void setUp() throws Exception
{
    ctx = ApplicationContextHelper.getApplicationContext();
    serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    transactionService = serviceRegistry.getTransactionService();
    AuthenticationUtil.setRunAsUserSystem();
}
 
Example 10
@Override
public void setUp() throws Exception
{
    AuthenticationUtil.setRunAsUserSystem();

    serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry");
    contentService = serviceRegistry.getContentService();
    fileContentStore = (AbstractTenantRoutingContentStore) ctx.getBean("fileContentStore");
}
 
Example 11
@Before
public void setUp() throws Exception
{
    ctx = ApplicationContextHelper.getApplicationContext();
    JobLockService jobLockService = (JobLockService) ctx.getBean("JobLockService");
    PolicyComponent policyComponent = (PolicyComponent) ctx.getBean("policyComponent");
    NodeService nodeService = (NodeService) ctx.getBean("NodeService");

    siteService = (SiteService) ctx.getBean("SiteService");
    personService = (PersonService) ctx.getBean("PersonService");
    feedDAO = (ActivityFeedDAO) ctx.getBean("feedDAO");
    transactionHelper = (RetryingTransactionHelper)ctx.getBean("retryingTransactionHelper");
    nodeArchiveService = (NodeArchiveService)ctx.getBean("nodeArchiveService");
    
    // Let's shut down the scheduler so that we aren't competing with the scheduled versions of jobs (ie. feed cleaner)
    Scheduler scheduler = (Scheduler) ctx.getBean("schedulerFactory");
    scheduler.shutdown();
    
    tearDown();
    
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    for (int i = 1; i <= 7; i++)
    {
        siteService.createSite("myPreset", "testSite"+i, null, null, SiteVisibility.PUBLIC);
    }
    
    AuthenticationUtil.setRunAsUserSystem();
    
    // construct the test cleaner
    cleaner = new FeedCleaner();
    cleaner.setFeedDAO(feedDAO);
    cleaner.setPolicyComponent(policyComponent);
    cleaner.setJobLockService(jobLockService);
    cleaner.setNodeService(nodeService);
}
 
Example 12
public void doTestBasicWriteOperations(ApplicationContext ctx) throws Exception
{
    // Grab the beans we need
    serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    transactionService = serviceRegistry.getTransactionService();
   
    // So we can write test nodes
    AuthenticationUtil.setRunAsUserSystem();
    
    // Check it looks fine
    assertFalse("The transaction is read-only - further unit tests are pointless.", transactionService.isReadOnly());
    
    // A basic write operation on a node
    RetryingTransactionCallback<Void> addPropertyCallback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            NodeService nodeService = serviceRegistry.getNodeService();
            NodeRef rootNodeRef = nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
            nodeService.setProperty(rootNodeRef, ContentModel.PROP_NAME, "SanityCheck");
            writeTestWorked = true;
            return null;
        }
    };
    
    // Now do a write operation, and ensure it worked
    writeTestWorked = false;
    transactionService.getRetryingTransactionHelper().doInTransaction(addPropertyCallback, false, true);
    assertTrue("The Node Write didn't occur or failed with an error", writeTestWorked);
}
 
Example 13
@Before
public void setup() throws SystemException, NotSupportedException
{
   	transactionService = (TransactionService)ctx.getBean("transactionService");
   	keyStoreChecker = (KeyStoreChecker)ctx.getBean("keyStoreChecker");
   	encryptionKeysRegistry = (EncryptionKeysRegistry)ctx.getBean("encryptionKeysRegistry");
   	keyResourceLoader = (KeyResourceLoader)ctx.getBean("springKeyResourceLoader");
       backupEncryptor = (DefaultEncryptor)ctx.getBean("backupEncryptor");

   	toDelete = new ArrayList<String>(10);

       AuthenticationUtil.setRunAsUserSystem();
	UserTransaction txn = transactionService.getUserTransaction();
	txn.begin();
}
 
Example 14
@Override
    public void setUp() throws Exception
    {
        ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
        transactionService = serviceRegistry.getTransactionService();
//        txnHelper = transactionService.getRetryingTransactionHelper();
        metadataEncryptor = (MetadataEncryptor)ctx.getBean("metadataEncryptor");
        nodeService = serviceRegistry.getNodeService();
        tenantService = (TenantService)ctx.getBean("tenantService");
        dictionaryDAO = (DictionaryDAO)ctx.getBean("dictionaryDAO");

        AuthenticationUtil.setRunAsUserSystem();
        
        DictionaryBootstrap bootstrap = new DictionaryBootstrap();
        List<String> bootstrapModels = new ArrayList<String>();
        bootstrapModels.add("alfresco/model/dictionaryModel.xml");
        bootstrapModels.add(TEST_MODEL);
//        List<String> labels = new ArrayList<String>();
//        labels.add(TEST_BUNDLE);
        bootstrap.setModels(bootstrapModels);
//        bootstrap.setLabels(labels);
        bootstrap.setDictionaryDAO(dictionaryDAO);
        bootstrap.setTenantService(tenantService);
        bootstrap.bootstrap();
        
        // create a first store directly
        RetryingTransactionCallback<NodeRef> createStoreWork = new RetryingTransactionCallback<NodeRef>()
        {
            public NodeRef execute()
            {
                StoreRef storeRef = nodeService.createStore(
                        StoreRef.PROTOCOL_WORKSPACE,
                        "Test_" + System.nanoTime());
                return nodeService.getRootNode(storeRef);
            }
        };
        rootNodeRef = transactionService.getRetryingTransactionHelper().doInTransaction(createStoreWork);
    }
 
Example 15
/**
 * Post Commit Event queue processing
 */
public void run() {
	
	// Clear the shutdown flag
	
	m_shutdown = false;
	
       // Use the system user as the authenticated context for the node monitor
       
       AuthenticationUtil.setRunAsUserSystem();

	// Loop until shutdown
	
	while ( m_shutdown == false)
	{
		try
		{
            // Wait for an event to process
			
		    final NodeEvent nodeEvent = m_eventQueue.removeEvent();

		    if ( logger.isDebugEnabled())
               {
                   logger.debug("Processing event " + nodeEvent);
               }
               
               // Check for a shutdown
               
               if ( m_shutdown == true)
                   continue;
               
               RetryingTransactionCallback<Object> processEventCallback = new RetryingTransactionCallback<Object>()
               {
                   public Object execute() throws Throwable
                   {
                       // Process the event
                   	
                       if (nodeEvent == null)
                       {
                           return null;
                       }
                       
                       // check for a node delete
                       
                       if ( nodeEvent instanceof DeleteNodeEvent) 
                       {
                           // Node deleted   
                           processDeleteNode((DeleteNodeEvent) nodeEvent);
                       }
        
                       // Process the node event, for an existing node
                       else if ( nodeEvent instanceof CreateNodeEvent) 
                       {    
                           // Node created
                           processCreateNode((CreateNodeEvent) nodeEvent);
                       }
                       else if ( nodeEvent instanceof MoveNodeEvent) 
                       {
                           // Node moved        
                           processMoveNode((MoveNodeEvent) nodeEvent);
                       }
                       else if ( nodeEvent instanceof LockNodeEvent) 
                       {
                           // Node locked/unlocked   
                           processLockNode(( LockNodeEvent) nodeEvent);
                       }
                       
                       // Done
                       
                       return null;
                   }
               };
               
               // Execute in a read-only transaction
               
               m_transService.getRetryingTransactionHelper().doInTransaction(processEventCallback, true, true);
		}
		catch ( InterruptedException ex)
		{
		}
		catch (Throwable e)
		{
		    logger.error("Throwable in NodeMonitor thread", e);
		}
	}
}
 
Example 16
private void setUp(boolean deleteEmptyDirs)
{
    AuthenticationUtil.setRunAsUserSystem();
    store.setDeleteEmptyDirs(deleteEmptyDirs);
    deletedUrls = 0;
}
 
Example 17
/**
 * Create the test content
 */
@Before public void createContent()
{
    allEntries = new TreeSet<String>();
    
    AuthenticationUtil.setRunAsUserSystem();
    
    Repository repositoryHelper = (Repository) APP_CONTEXT_INIT.getApplicationContext().getBean("repositoryHelper");
    NodeRef COMPANY_HOME = repositoryHelper.getCompanyHome();
    
    // Create some static test content
   rootFolder = testNodes.createNode(COMPANY_HOME, "rootFolder", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());
   allEntries.add("rootFolder/");

   rootFile = testNodes.createNodeWithTextContent(COMPANY_HOME, "rootFile.txt", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName(), "Root file content");
   allEntries.add("rootFile.txt");
   
   testNodes.createNodeWithTextContent(rootFolder, "level1File.txt", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName(), "Level 1 file content");
   allEntries.add("rootFolder/level1File.txt");
   
   level1Folder1 = testNodes.createNode(rootFolder, "level1Folder1", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());
   allEntries.add("rootFolder/level1Folder1/");
   
   level1Folder2 = testNodes.createNode(rootFolder, "level1Folder2", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());
   allEntries.add("rootFolder/level1Folder2/");
   
   testNodes.createNode(rootFolder, "level1EmptyFolder", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());
   allEntries.add("rootFolder/level1EmptyFolder/");
   
   testNodes.createNodeWithTextContent(level1Folder1, "level2File.txt", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName(), "Level 2 file content");
   allEntries.add("rootFolder/level1Folder1/level2File.txt");

   testNodes.createNodeWithTextContent(level1Folder2, "level2File.txt", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName(), "Level 2 file content");
   allEntries.add("rootFolder/level1Folder2/level2File.txt");
   
   secondaryNode = testNodes.createNodeWithTextContent(COMPANY_HOME, "secondaryNodeFile.txt", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName(), "Secondary node");
   ChildAssociationRef assoc = NODE_SERVICE.addChild(rootFolder, secondaryNode, ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS);
   Assert.assertFalse(assoc.isPrimary());
   allEntries.add("rootFolder/secondaryNodeFile.txt");
   
   fileToCheckout = testNodes.createNodeWithTextContent(level1Folder2, "fileToCheckout.txt", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName(), "Level 2 file content");
   // Add the lock and version aspects to the created node
   NODE_SERVICE.addAspect(fileToCheckout, ContentModel.ASPECT_VERSIONABLE, null);
   NODE_SERVICE.addAspect(fileToCheckout, ContentModel.ASPECT_LOCKABLE, null);
   
   allEntries.add("rootFolder/level1Folder2/fileToCheckout.txt");
   PERMISSION_SERVICE.setPermission(level1Folder2, TEST_USER.getUsername(), PermissionService.ALL_PERMISSIONS, true);
   PERMISSION_SERVICE.setPermission(fileToCheckout, TEST_USER.getUsername(), PermissionService.ALL_PERMISSIONS, true);
}
 
Example 18
/**
 * Test for MNT-10070 and MNT-14136
 */
public void testApplication() throws Exception
{
    // Register the test model
    URL testModelUrl = ResourceUtils.getURL("classpath:alfresco/testaudit/alfresco-audit-test-mnt-10070.xml");
    auditModelRegistry.registerModel(testModelUrl);
    auditModelRegistry.loadAuditModels();
    
    auditModelRegistry.setProperty("audit.enabled", "true");

    auditModelRegistry.setProperty("audit.app1.enabled", "true");
    auditModelRegistry.setProperty("audit.filter.app1.default.enabled", "true");
    auditModelRegistry.setProperty("audit.filter.app1.login.user", "~System;~null;.*");

    auditModelRegistry.setProperty("audit.app2.enabled", "true");
    auditModelRegistry.setProperty("audit.filter.app2.default.enabled", "true");
    auditModelRegistry.setProperty("audit.filter.app2.login.user", "~System;~null;~admin;.*");

    auditModelRegistry.setProperty("audit.app3.enabled", "true");
    auditModelRegistry.setProperty("audit.filter.app3.default.enabled", "true");
    auditModelRegistry.setProperty("audit.filter.app3.login.user", "~System;~null;.*");
    
    auditModelRegistry.afterPropertiesSet();  
    
    AuthenticationUtil.setRunAsUserSystem();
    AuditApplication applicationOne = auditModelRegistry.getAuditApplicationByName(APPLICATION_ONE);
    assertNotNull("Application 'app1' dosn't exist", applicationOne);
    AuditApplication applicationTwo = auditModelRegistry.getAuditApplicationByName(APPLICATION_TWO);
    assertNotNull("Application 'app2' dosn't exist", applicationTwo);
    AuditApplication applicationThree = auditModelRegistry.getAuditApplicationByName(APPLICATION_THREE);
    assertNotNull("Application 'app3' dosn't exist", applicationThree);

    // auditComponent
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    PropertyAuditFilter filter = new PropertyAuditFilter();
    Properties properties = new Properties();
    properties.put("audit.enabled", "true");

    properties.put("audit.app1.enabled", "true");
    properties.put("audit.filter.app1.default.enabled", "true");
    properties.put("audit.filter.app1.default.user", "~System;~null;.*");

    properties.put("audit.app2.enabled", "true");
    properties.put("audit.filter.app2.default.enabled", "true");
    properties.put("audit.filter.app2.default.user", "~System;~null;~admin;.*");

    properties.put("audit.app3.enabled", "true");
    properties.put("audit.filter.app3.default.enabled", "true");
    properties.put("audit.filter.app3.default.user", "~System;~null;.*");

    filter.setProperties(properties);
    auditComponent.setAuditFilter(filter);

    Map<String, Serializable> auditMap = new HashMap<String, Serializable>();
    auditMap.put("/transaction/user", AuthenticationUtil.getFullyAuthenticatedUser());
    auditMap.put("/transaction/action", "CREATE");
    auditMap.put("/transaction/type", "cm:content");

    Map<String, Serializable> recordedAuditMap = auditComponent.recordAuditValues("/alfresco-access", auditMap);

    assertFalse("Audit values is empty.", recordedAuditMap.isEmpty());

    Map<String, Serializable> expected = new HashMap<String, Serializable>();
    // There should not be app2
    expected.put("/" + APPLICATION_ONE + "/transaction/action", "CREATE");
    expected.put("/" + APPLICATION_THREE + "/transaction/type", "cm:content");

    String failure = EqualsHelper.getMapDifferenceReport(recordedAuditMap, expected);
    if (failure != null)
    {
        fail(failure);
    }
}
 
Example 19
@SuppressWarnings("unchecked")
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
    AuthenticationUtil.setRunAsUserSystem();
    
    storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
    NodeRef rootNodeRef = nodeService.getRootNode(storeRef);
    
    homeFolder = nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "homeFolder"),
            ContentModel.TYPE_FOLDER).getChildRef();

    folder0 = newFolder(homeFolder, "folder0");
    folder1 = newFolder(homeFolder, "folder1");
    folder2 = newFolder(homeFolder, "folder2");
    folder3 = newFolder(homeFolder, "folder3");
    
    content0 = newContent(folder0, "content0");
    content1 = newContent(folder1, "content1");
    content2 = newContent(folder2, "content2");
    content3 = newContent(folder3, "content3");

    System.out.println(NodeStoreInspector.dumpNodeStore(nodeService, storeRef));

    try
    {
        authenticationComponent.clearCurrentSecurityContext();
    }
    catch (Throwable e)
    {
        // ignore
    }

    // Mock up an auditComponent to see the results of our tests
    AuditComponent auditComponent = mock(AuditComponent.class);
    when(auditComponent.areAuditValuesRequired(anyString())).thenReturn(true);
    when(auditComponent.recordAuditValues(anyString(), anyMap())).thenAnswer(new Answer<Map<String, Serializable>>()
            {
                public Map<String, Serializable> answer(InvocationOnMock invocation) throws Throwable
                {
                    Object[] args = invocation.getArguments();
                    Map<String, Serializable> auditMap = (Map<String, Serializable>)args[1];
                    if ("/alfresco-access/transaction".equals(args[0]))
                    {
                        auditMapList.add(auditMap);
                    }
                    return auditMap;
                }
            });

    // Create our own properties object for use by the auditor
    properties = new Properties();
    properties.put("audit.alfresco-access.sub-actions.enabled", "false");

    // Set properties
    auditor = new AccessAuditor();
    auditor.setTransactionService(transactionService);
    auditor.setNamespaceService(namespaceService);
    auditor.setNodeInfoFactory(new NodeInfoFactory(nodeService, namespaceService));
    auditor.setPolicyComponent(policyComponent);
    auditor.setProperties(properties);
    auditor.setAuditComponent(auditComponent);
    
    // Simulate spring call after properties set
    auditor.afterPropertiesSet();    
}
 
Example 20
/**
 * Test for MNT-12420
 * 
 * @throws Exception 
 */
public void testMoveViaAppendAndDelete() throws Exception
{
    AlfrescoImapUser poweredUser = new AlfrescoImapUser((USER_NAME + "@alfresco.com"), USER_NAME, USER_PASSWORD);
    String fileName = "testfile" + GUID.generate();
    String destinationName = "testFolder" + GUID.generate();
    String destinationPath = IMAP_ROOT + AlfrescoImapConst.HIERARCHY_DELIMITER + destinationName;
    String nodeContent = "test content";
    NodeRef root = findCompanyHomeNodeRef();
    AuthenticationUtil.setRunAsUserSystem();

    // Create node and destination folder
    FileInfo origFile = fileFolderService.create(root, fileName, ContentModel.TYPE_CONTENT);
    ContentWriter contentWriter = contentService.getWriter(origFile.getNodeRef(), ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype("text/plain");
    contentWriter.setEncoding("UTF-8");
    contentWriter.putContent(nodeContent);

    FileInfo destinationNode = fileFolderService.create(root, destinationName, ContentModel.TYPE_FOLDER);
    nodeService.addAspect(origFile.getNodeRef(), ImapModel.ASPECT_IMAP_CONTENT, null);
    nodeService.addAspect(origFile.getNodeRef(), ContentModel.ASPECT_TAGGABLE, null);

    // Save the message and set X-Alfresco-NodeRef-ID header
    SimpleStoredMessage origMessage = imapService.getMessage(origFile);
    origMessage.getMimeMessage().addHeader(AlfrescoImapConst.X_ALF_NODEREF_ID, origFile.getNodeRef().getId());
    origMessage.getMimeMessage().saveChanges();

    // Append the message to destination
    AlfrescoImapFolder destinationMailbox = imapService.getOrCreateMailbox(poweredUser, destinationPath, true, false);
    long uuid = destinationMailbox.appendMessage(origMessage.getMimeMessage(), flags, null);
    
    // Delete the node
    imapService.setFlag(origFile, Flags.Flag.DELETED, true);
    imapService.expungeMessage(origFile);

    // Check the destination has copy of original file and only this file
    FileInfo copiedNode = fileFolderService.getFileInfo(nodeService.getNodeRef(uuid));
    assertNotNull("The file should exist.", copiedNode);
    assertEquals("The file name should not change.", fileName, copiedNode.getName());
    NodeRef copiedParentNodeRef = nodeService.getPrimaryParent(copiedNode.getNodeRef()).getParentRef();
    assertEquals("The parent should change to destination.", destinationNode.getNodeRef(), copiedParentNodeRef);
    assertEquals("There should be only one node in the destination folder", 1, nodeService.getChildAssocs(destinationNode.getNodeRef()).size());
    assertTrue("New node should have original node aspects", nodeService.hasAspect(copiedNode.getNodeRef(), ContentModel.ASPECT_TAGGABLE));
}