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

The following examples show how to use org.alfresco.repo.security.authentication.AuthenticationUtil#setAdminUserAsFullyAuthenticatedUser() . 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 check out the related API usage on the sidebar.
Example 1
Source File: LinksRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testCommentLink() throws Exception
{
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    JSONObject link = createLink(LINK_TITLE_ONE, "commented link", LINK_URL_ONE, false, Status.STATUS_OK);
    postLookup.execute();
    feedGenerator.execute();
    int activityNumStart = activityService.getSiteFeedEntries(SITE_SHORT_NAME_LINKS).size();
    String name = getNameFromLink(link);
    link = getLink(name, Status.STATUS_OK);
    String nodeRef = link.getString("nodeRef");
    JSONObject commentOne = createComment(nodeRef, "comment", "content", 200);
    postLookup.execute();
    feedGenerator.execute();
    int activityNumNext = activityService.getSiteFeedEntries(SITE_SHORT_NAME_LINKS).size();
    assertEquals("The activity feeds were not generated after adding a comment", activityNumStart + 1, activityNumNext);
    activityNumStart = activityNumNext;
    NodeRef commentNodeRef = new NodeRef(commentOne.getString("nodeRef"));
    sendRequest(new DeleteRequest(getDeleteCommentUrl(commentNodeRef)), 200);
    postLookup.execute();
    feedGenerator.execute();
    activityNumNext = activityService.getSiteFeedEntries(SITE_SHORT_NAME_LINKS).size();
    assertEquals("The activity feeds were not generated after deleting a comment", activityNumStart + 1, activityNumNext);
}
 
Example 2
Source File: FullTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void canGuessMimeType()
{
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    
    ContentService contentService = (ContentService) ctx.getBean("ContentService");
    NodeService nodeService = (NodeService) ctx.getBean("NodeService");
    StoreRef storeRef = nodeService.createStore("workspace", getClass().getName()+UUID.randomUUID());
    NodeRef rootNodeRef = nodeService.getRootNode(storeRef);
    NodeRef nodeRef = nodeService.createNode(
                rootNodeRef,
                ContentModel.ASSOC_CHILDREN,
                QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, getClass().getSimpleName()),
                ContentModel.TYPE_CONTENT).getChildRef();

    ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    // Pre-condition of test is that we're testing with a potentially problematic BackingStoreAwareCacheWriter
    // rather than a FileContentWriter, which we would expect to work.
    assertTrue(writer instanceof BackingStoreAwareCacheWriter);
    
    String content = "This is some content";
    writer.putContent(content);
    writer.guessMimetype("myfile.txt");
    
    assertEquals("text/plain", writer.getMimetype());
}
 
Example 3
Source File: GetPeopleCannedQueryTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Before
public void before()
{
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    // cleanup all existing people, the test is sensitive to the user names
    transactionService.getRetryingTransactionHelper().doInTransaction(() -> {
        for (NodeRef nodeRef : personService.getAllPeople())
        {
            String uid = DefaultTypeConverter.INSTANCE.convert(String.class, nodeService.getProperty(nodeRef, ContentModel.PROP_USERNAME));
            if (!uid.equals(AuthenticationUtil.getAdminUserName()) && !uid.equals(AuthenticationUtil.getGuestUserName()))
            {
                personService.deletePerson(nodeRef);
            }
        }
        return null;
    });

}
 
Example 4
Source File: FileFolderLoaderTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 100 files; 10 per txn
 */
@Test
public void testLoad_02() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
        int created = fileFolderLoader.createFiles(
                writeFolderPath,
                100, 10, 1024L, 1024L, Long.MAX_VALUE, false,
                10, 256L);
        assertEquals("Incorrect number of files generated.", 100, created);
        // Count
        assertEquals(100, nodeService.countChildAssocs(writeFolderNodeRef, true));
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 5
Source File: FileFolderLoaderTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Zero files
 */
@Test
public void testLoad_ZeroFiles() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
        int created = fileFolderLoader.createFiles(
                writeFolderPath,
                0, 256, 1024L, 1024L, Long.MAX_VALUE, false,
                10, 256L);
        assertEquals("Incorrect number of files generated.", 0, created);
        // Count
        assertEquals(0, nodeService.countChildAssocs(writeFolderNodeRef, true));
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 6
Source File: FileFolderLoaderTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testFolderMissing() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
        fileFolderLoader.createFiles(
                sharedHomePath + "/Missing",
                0, 256, 1024L, 1024L, Long.MAX_VALUE, false,
                10, 256L);
        fail("Folder does not exist");
    }
    catch (AlfrescoRuntimeException e)
    {
        // Expected
        assertTrue(e.getCause() instanceof FileNotFoundException);
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 7
Source File: CronScheduledQueryBasedTemplateActionDefinitionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Before
@Override
public void setUp() throws Exception
{
    applicationContext = ApplicationContextHelper.getApplicationContext();
    this.registry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY);

    initializeScheduler();

    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    transaction = registry.getTransactionService().getUserTransaction(false);
    transaction.begin();

    createTestContent();
}
 
Example 8
Source File: AbstractContextAwareRepoEvent.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Before
public void setUp() throws Exception
{
    if (!isCamelConfigured)
    {
        dataFormat = new JacksonDataFormat(event2ObjectMapper, RepoEvent.class);
        configRoute();
        isCamelConfigured = true;
    }

    // authenticate as admin
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    this.rootNodeRef = retryingTransactionHelper.doInTransaction(() -> {
        // create a store and get the root node
        StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE,
            this.getClass().getName());
        if (!nodeService.exists(storeRef))
        {
            storeRef = nodeService.createStore(storeRef.getProtocol(),
                storeRef.getIdentifier());
        }
        return nodeService.getRootNode(storeRef);
    });
}
 
Example 9
Source File: AuditMethodInterceptorTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Test for <a href="https://issues.alfresco.com/jira/browse/MNT-16748">MNT-16748</a> <br>
 * Use {@link SearchService#query(SearchParameters)} to perform a query.
 */
public void testAuditSearchServiceSearchParametersQuery() throws Exception
{
    // Run as admin
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    // Create SearchParameters to be used in query
    SearchParameters sp = new SearchParameters();
    sp.setLanguage(SearchService.LANGUAGE_XPATH);
    sp.setQuery("/app:company_home/app:dictionary");
    sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);

    // Perform a search
    @SuppressWarnings("unused")
    ResultSet rs = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<ResultSet>()
    {
        @Override
        public ResultSet execute() throws Throwable
        {
            return searchService.query(sp);
        }

    }, true, false);

    // Check the audit entries
    checkAuditEntries(APPLICATION_NAME_MNT_16748, SearchService.LANGUAGE_XPATH, "/app:company_home/app:dictionary", 1);
}
 
Example 10
Source File: FileFolderLoaderTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * One file
 */
@Test
public void testLoad_OneFile() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
        int created = fileFolderLoader.createFiles(
                writeFolderPath,
                1, 256, 1024L, 1024L, Long.MAX_VALUE, false,
                10, 256L);
        assertEquals("Incorrect number of files generated.", 1, created);
        // Check the descriptions
        RetryingTransactionCallback<Void> checkCallback = new RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {
                MLPropertyInterceptor.setMLAware(true);
                List<ChildAssociationRef> childAssocs = nodeService.getChildAssocs(writeFolderNodeRef);
                // Count
                assertEquals(1, childAssocs.size());
                NodeRef fileNodeRef = childAssocs.get(0).getChildRef();
                MLText descriptions = (MLText) nodeService.getProperty(fileNodeRef, ContentModel.PROP_DESCRIPTION);
                assertNotNull("No descriptions added", descriptions);
                assertEquals("Incorrect number of unique descriptions added: ", 10, descriptions.size());
                assertTrue("Expect the default language to be present. ",
                        descriptions.containsKey(new Locale(Locale.getDefault().getLanguage())));
                return null;
            }
        };
        transactionService.getRetryingTransactionHelper().doInTransaction(checkCallback, true);
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 11
Source File: ArchiveAndRestoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * <a href="https://issues.alfresco.com/jira/browse/MNT-2777">MNT-2777</a>
 */
public void testALF17554ArchiveAndRestoreCheckPermission() throws Exception
{
    permissionService.setInheritParentPermissions(a, false);
    // Set the permission for the node for user USER_C
    AuthenticationUtil.setFullyAuthenticatedUser(USER_C);
    assertTrue(
            "The user should not have the permission set on the node yet.",
            permissionService.hasPermission(a, PermissionService.COORDINATOR) == AccessStatus.DENIED);
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    permissionService.setPermission(a, USER_C, PermissionService.COORDINATOR, true);
    assertTrue(
            "The user should have the permission set on the node.",
            permissionService.hasPermission(a, PermissionService.COORDINATOR) == AccessStatus.ALLOWED);
    commitAndBeginNewTransaction();
    nodeService.deleteNode(a);
    verifyNodeExistence(a, false);
    nodeService.restoreNode(a_, null, null, null);
    // Check the permission
    AuthenticationUtil.setFullyAuthenticatedUser(USER_C);
    assertTrue(
            "The user should have the same permission after restoring the node.",
            permissionService.hasPermission(a, PermissionService.COORDINATOR) == AccessStatus.ALLOWED);
    assertFalse(
            "The node should have InheritParentPermissions set to false.",
            permissionService.getInheritParentPermissions(a));
}
 
Example 12
Source File: ScriptNodeTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** See ALF-15010 */
@Test public void findNode_ALF15010() throws Exception
{
    // Set the READ permission for the USER_TWO to false, so he cannot access the node
    // created by USER_ONE
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    PERMISSION_SERVICE.setPermission(USER_ONES_TEST_FILE, USER_TWO_NAME, PermissionService.READ, false);
    
    // Now that USER_TWO doesn't have the READ permission, we should get
    // null rather than AccessDeniedException.
    // Note: AccessDeniedException was thrown upon retrieving a property of the node
    AuthenticationUtil.setFullyAuthenticatedUser(USER_TWO_NAME);
    ScriptNode scriptNode = SEARCH_SCRIPT.findNode(USER_ONES_TEST_FILE);
    assertNull(scriptNode);
    
    // USER_ONE is the node creator, so he can access the node
    AuthenticationUtil.setFullyAuthenticatedUser(USER_ONE_NAME);
    scriptNode = SEARCH_SCRIPT.findNode(USER_ONES_TEST_FILE);
    assertNotNull(scriptNode);

    // Give USER_TWO READ permission
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    PERMISSION_SERVICE.setPermission(USER_ONES_TEST_FILE, USER_TWO_NAME, PermissionService.READ, true);

    // Now USER_TWO can access the node created by USER_ONE
    AuthenticationUtil.setFullyAuthenticatedUser(USER_TWO_NAME);
    scriptNode = SEARCH_SCRIPT.findNode(USER_ONES_TEST_FILE);
    assertNotNull(scriptNode);
    
    // cleanup
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    PERMISSION_SERVICE.clearPermission(USER_ONES_TEST_FILE, USER_TWO_NAME);
}
 
Example 13
Source File: DictionaryRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception 
{ 
	super.setUp();
	getServer();
	AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
}
 
Example 14
Source File: RemoteAlfrescoTicketServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void tearDown() throws Exception
{
    super.tearDown();
    
    // Admin user required to delete user
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    
    // Delete the users, which also zaps their credentials
    if(personService.personExists(USER_ONE))
    {
       personService.deletePerson(USER_ONE);
    }
    if(this.authenticationService.authenticationExists(USER_ONE))
    {
       this.authenticationService.deleteAuthentication(USER_ONE);
    }
    
    if(personService.personExists(USER_TWO))
    {
       personService.deletePerson(USER_TWO);
    }
    if(this.authenticationService.authenticationExists(USER_TWO))
    {
       this.authenticationService.deleteAuthentication(USER_TWO);
    }
    
    // Unregister the system
    remoteAlfrescoTicketService.registerRemoteSystem(TEST_REMOTE_SYSTEM_ID, null, null);
}
 
Example 15
Source File: RemoteFileFolderLoaderTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    
    this.repositoryHelper = (Repository)getServer().getApplicationContext().getBean("repositoryHelper");
    this.nodeService = (NodeService)getServer().getApplicationContext().getBean("nodeService");
    this.transactionService = (TransactionService) getServer().getApplicationContext().getBean("TransactionService");
    this.fileFolderService = (FileFolderService) getServer().getApplicationContext().getBean("FileFolderService");

    // Get the path of the shared folder home
    final NodeRef companyHomeNodeRef = repositoryHelper.getCompanyHome();
    final NodeRef sharedHomeNodeRef = repositoryHelper.getSharedHome();
    RetryingTransactionCallback<NodeRef> createFolderWork = new RetryingTransactionCallback<NodeRef>()
    {
        @Override
        public NodeRef execute() throws Throwable
        {
            List<FileInfo> sharedHomeFileInfos = fileFolderService.getNamePath(companyHomeNodeRef, sharedHomeNodeRef);
            sharedHomePath = "/" + sharedHomeFileInfos.get(0).getName();

            String folderName = UUID.randomUUID().toString();
            // Create a folder
            FileInfo folderInfo = fileFolderService.create(sharedHomeNodeRef, folderName, ContentModel.TYPE_FOLDER);
            loadHomePath = sharedHomePath + "/" + folderName;
            // Done
            return folderInfo.getNodeRef();
        }
    };
    AuthenticationUtil.pushAuthentication();            // Will be cleared later
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    loadHomeNodeRef = transactionService.getRetryingTransactionHelper().doInTransaction(createFolderWork);
}
 
Example 16
Source File: LockableAspectInterceptorTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testEnableDisableForThread() throws InterruptedException, ExecutionException
{
    QName nodeName = QName.createQName("http://www.alfresco.org/test/" + getClass().getSimpleName(), "testNode");
    final NodeRef nodeRef = nodeService.createNode(
                rootNode,
                ContentModel.ASSOC_CHILDREN,
                nodeName,
                ContentModel.TYPE_BASE).getChildRef();
    
    assertFalse("Node should not be reported as lockable",
                nodeService.hasAspect(nodeRef, ContentModel.ASPECT_LOCKABLE));
    
    lockStore.set(nodeRef,
                LockState.createLock(nodeRef, LockType.WRITE_LOCK, lockOwner, null, Lifetime.EPHEMERAL, null));
    
    // Interceptor enabled by default for current thread.
    assertTrue("Node should be reported as lockable",
                nodeService.hasAspect(nodeRef, ContentModel.ASPECT_LOCKABLE));

    // Interceptor can be disabled for current thread.
    interceptor.disableForThread();
    assertFalse("Node should NOT be reported as lockable",
                nodeService.hasAspect(nodeRef, ContentModel.ASPECT_LOCKABLE));
    
    // Interceptor can be re-enabled for current thread.
    interceptor.enableForThread();
    assertTrue("Node should be reported as lockable",
                nodeService.hasAspect(nodeRef, ContentModel.ASPECT_LOCKABLE));
    
    Callable<Boolean> callable = new Callable<Boolean>()
    {
        @Override
        public Boolean call() throws Exception
        {
            AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
            // Disable for the 'other' thread
            interceptor.disableForThread();
            return nodeService.hasAspect(nodeRef, ContentModel.ASPECT_LOCKABLE);
        }   
    };
    
    ExecutorService executor = Executors.newSingleThreadExecutor();  
    Future<Boolean> future = executor.submit(callable);
    
    // The 'other' thread should not spoof the aspect as the interceptor is disabled. 
    assertFalse("Node should be reported as lockable (new thread)", future.get());
    
    // The interceptor is still enabled in the primary thread though.
    assertTrue("Node should be reported as lockable (main thread)",
                nodeService.hasAspect(nodeRef, ContentModel.ASPECT_LOCKABLE));
    
    executor.shutdown();
}
 
Example 17
Source File: ArchiveAndRestoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test listArchivedNodes based on the user's permission.
 */
public void testListArchivedNodesPermissions()
{
    AuthenticationUtil.setFullyAuthenticatedUser(USER_B);        
    // Create paging
    ScriptPagingDetails paging = new ScriptPagingDetails(2, 0);
    // Create canned query
    ArchivedNodesCannedQueryBuilder queryBuilder = new ArchivedNodesCannedQueryBuilder.Builder(
                this.archiveStoreRootNodeRef, paging).build();

    // Query the DB
    PagingResults<NodeRef> result = runListArchivedNodesAsAdmin(queryBuilder);
    assertEquals("USER_B hasn't deleted anything yet.", 0, result.getPage().size());

    // USER_B deletes "bb"
    nodeService.deleteNode(bb);

    result = nodeArchiveService.listArchivedNodes(queryBuilder);
    assertEquals("USER_B deleted 1 item and USER_B can see it.", 1, result.getPage().size());

    result = runListArchivedNodesAsAdmin(queryBuilder);
    assertEquals("USER_B deleted only 1 item.", 1, result.getPage().size());

    AuthenticationUtil.setFullyAuthenticatedUser(USER_A);
    // USER_A deletes "aa"
    nodeService.deleteNode(aa);

    // Create canned query
    queryBuilder = new ArchivedNodesCannedQueryBuilder.Builder(
                this.archiveStoreRootNodeRef, paging)
                .build();

    result = nodeArchiveService.listArchivedNodes(queryBuilder);
    assertEquals("USER_A deleted 1 item and USER_A can see it.", 1, result.getPage().size());

    result = runListArchivedNodesAsAdmin(queryBuilder);
    assertEquals("USER_A deleted only 1 item.", 1, result.getPage().size());
    assertEquals(QNAME_AA.getLocalName(),
                nodeService.getProperty(result.getPage().get(0), ContentModel.PROP_NAME));

    // Set the authentication to Admin
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    queryBuilder = new ArchivedNodesCannedQueryBuilder.Builder(this.archiveStoreRootNodeRef, paging)
                .build();

    result = nodeArchiveService.listArchivedNodes(queryBuilder);
    // Admin can retrieve all users' deleted nodes
    assertEquals("Admin can retrieve all users' deleted nodes.", 2, result.getPage().size());
}
 
Example 18
Source File: FileFolderLoaderTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 15 files; 10 per txn; spoofed; different
 */
@Test
public void testLoad_03() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
        int created = fileFolderLoader.createFiles(
                writeFolderPath,
                15, 10, 1024L, 1024L, Long.MAX_VALUE, false,
                10, 256L);
        assertEquals("Incorrect number of files generated.", 15, created);
        // Count
        assertEquals(15, nodeService.countChildAssocs(writeFolderNodeRef, true));
        // Check the files
        List<FileInfo> fileInfos = fileFolderService.listFiles(writeFolderNodeRef);
        String lastText = null;
        String lastDescr = null;
        String lastUrl = null;
        for (FileInfo fileInfo : fileInfos)
        {
            NodeRef fileNodeRef = fileInfo.getNodeRef();
            // The URLs must all be unique as we wrote the physical binaries
            ContentReader reader = fileFolderService.getReader(fileNodeRef);
            assertEquals("UTF-8", reader.getEncoding());
            assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, reader.getMimetype());
            assertEquals(1024L, reader.getSize());
            if (lastUrl == null)
            {
                lastUrl = reader.getContentUrl();
            }
            else
            {
                assertNotEquals("We expect different URLs: ", lastUrl, reader.getContentUrl());
                lastUrl = reader.getContentUrl();
            }
            // Check content
            if (lastText == null)
            {
                lastText = reader.getContentString();
            }
            else
            {
                String currentStr = reader.getContentString();
                assertNotEquals("All text must differ due to varying seed. ", lastText, currentStr);
                lastText = currentStr;
            }
            // Check description
            if (lastDescr == null)
            {
                lastDescr = DefaultTypeConverter.INSTANCE.convert(String.class, nodeService.getProperty(fileNodeRef, ContentModel.PROP_DESCRIPTION));
                assertEquals("cm:description length is incorrect. ", 256, lastDescr.getBytes().length);
            }
            else
            {
                String currentDescr = DefaultTypeConverter.INSTANCE.convert(String.class, nodeService.getProperty(fileNodeRef, ContentModel.PROP_DESCRIPTION));
                assertNotEquals("All descriptions must differ due to varying seed. ", lastDescr, currentDescr);
                lastDescr = currentDescr;
            }
        }
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 19
Source File: DeleteMethodTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@After
public void tearDown() throws Exception
{
    method = null;
    request = null;
    response = null;

    if (txn.getStatus() == Status.STATUS_MARKED_ROLLBACK)
    {
        txn.rollback();
    }
    else
    {
        txn.commit();
    }
    
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
 
    nodeService.deleteNode(versionableDoc);

    // As per MNT-10037 try to create a node and delete it in the next txn
    txn = transactionService.getUserTransaction();
    txn.begin();

    Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
    String nodeName = "leak-session-doc-" + GUID.generate();
    properties.put(ContentModel.PROP_NAME, nodeName);

    NodeRef nodeRef = nodeService.createNode(companyHomeNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName(ContentModel.USER_MODEL_URI, nodeName),
            ContentModel.TYPE_CONTENT, properties).getChildRef();
    contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true).putContent("WebDAVTestContent");

    txn.commit();

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

    nodeService.deleteNode(nodeRef);

    txn.commit();

    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example 20
Source File: HiddenAspectTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Before
public void setup() throws SystemException, NotSupportedException
{
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry");
    transactionService = serviceRegistry.getTransactionService();
    nodeService = serviceRegistry.getNodeService();
    fileFolderService = serviceRegistry.getFileFolderService();
    authenticationService = (MutableAuthenticationService) ctx.getBean("AuthenticationService");
    hiddenAspect = (HiddenAspect) ctx.getBean("hiddenAspect");
    interceptor = (FilenameFilteringInterceptor) ctx.getBean("filenameFilteringInterceptor");
    namespacePrefixResolver = (DictionaryNamespaceComponent) ctx.getBean("namespaceService");
    cociService = (CheckOutCheckInService) ctx.getBean("checkOutCheckInService");
    imapService = serviceRegistry.getImapService();
    personService = serviceRegistry.getPersonService();
    permissionService = serviceRegistry.getPermissionService();
    imapEnabled = serviceRegistry.getImapService().getImapServerEnabled();
    
    nodeDAO = (NodeDAO)ctx.getBean("nodeDAO");
    Properties properties = (Properties) ctx.getBean("global-properties");
    cmisDisableHide = Boolean.getBoolean(properties.getProperty("cmis.disable.hidden.leading.period.files"));
    
    // start the transaction
    txn = transactionService.getUserTransaction();
    txn.begin();
    
    username = "user" + System.currentTimeMillis();
    
    PropertyMap testUser = new PropertyMap();
    testUser.put(ContentModel.PROP_USERNAME, username);
    testUser.put(ContentModel.PROP_FIRSTNAME, username);
    testUser.put(ContentModel.PROP_LASTNAME, username);
    testUser.put(ContentModel.PROP_EMAIL, username + "@alfresco.com");
    testUser.put(ContentModel.PROP_JOBTITLE, "jobTitle");

    // authenticate
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    
    personService.createPerson(testUser);
    
    // create the ACEGI Authentication instance for the new user
    authenticationService.createAuthentication(username, username.toCharArray());
    
    user = new AlfrescoImapUser(username + "@alfresco.com", username, username);

    // create a test store
    storeRef = nodeService
            .createStore(StoreRef.PROTOCOL_WORKSPACE, getName() + System.currentTimeMillis());
    rootNodeRef = nodeService.getRootNode(storeRef);
    permissionService.setPermission(rootNodeRef, username, PermissionService.CREATE_CHILDREN, true);
    
    AuthenticationUtil.setFullyAuthenticatedUser(username);
    
    topNodeRef = nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName(NamespaceService.ALFRESCO_URI, "working root"),
            ContentModel.TYPE_FOLDER).getChildRef();
    
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
}