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

The following are Jave code examples for showing how to use pushAuthentication() of the org.alfresco.repo.security.authentication.AuthenticationUtil class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: alfresco-repository   File: FileFolderLoaderTest.java   View Source Code Vote up 7 votes
@Test
public void testNoPermissionsToFindFolder() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setFullyAuthenticatedUser("BOB-1");
        fileFolderLoader.createFiles(
                hiddenFolderPath,
                0, 256, 1024L, 1024L, Long.MAX_VALUE, false,
                10, 256L);
        fail("No permissions to see folder.");
    }
    catch (AccessDeniedException e)
    {
        // Expected
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 2
Project: alfresco-repository   File: FileFolderLoaderTest.java   View Source Code Vote up 6 votes
@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 3
Project: alfresco-repository   File: FileFolderLoaderTest.java   View Source Code Vote up 6 votes
@Test
public void testNoPermissionsToWriteToFolder() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setFullyAuthenticatedUser("BOB-1");
        fileFolderLoader.createFiles(
                readOnlyFolderPath,
                1, 256, 1024L, 1024L, Long.MAX_VALUE, false,
                10, 256L);
        fail("Folder is read only.  Should not be able to write to it.");
    }
    catch (AccessDeniedException e)
    {
        // Expected
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 4
Project: alfresco-repository   File: FileFolderLoaderTest.java   View Source Code Vote up 6 votes
/**
 * 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 5
Project: alfresco-repository   File: TemporaryNodes.java   View Source Code Vote up 6 votes
/**
 * This method creates a cm:folder NodeRef and adds it to the internal list of NodeRefs to be tidied up by the rule.
 * This method will be run in its own transaction and will be run with the specified user as the fully authenticated user,
 * thus ensuring the named user is the cm:creator of the new node.
 * 
 * @param parentNode the parent node
 * @param nodeCmName the cm:name of the new node
 * @param nodeCreator the username of the person who will create the node
 * @return the newly created NodeRef.
 */
public NodeRef createFolder(final NodeRef parentNode, final String nodeCmName, final String nodeCreator)
{
    final RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) appContextRule.getApplicationContext().getBean("retryingTransactionHelper");
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(nodeCreator);
    
    NodeRef newNodeRef = transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            final NodeRef result = createNode(nodeCmName, parentNode, ContentModel.TYPE_FOLDER);
            
            return result;
        }
    });
    
    AuthenticationUtil.popAuthentication();
    
    this.temporaryNodeRefs.add(newNodeRef);
    return newNodeRef;
}
 
Example 6
Project: alfresco-remote-api   File: RemoteFileFolderLoaderTest.java   View Source Code Vote up 5 votes
@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 7
Project: alfresco-repository   File: TemporaryNodes.java   View Source Code Vote up 5 votes
/**
 * This method creates a cm:content NodeRef whose content is taken from the named Alfresco 'quick' file and adds it to the internal
 * list of NodeRefs to be tidied up by the rule.
 * This method will be run in its own transaction and will be run with the specified user as the fully authenticated user,
 * thus ensuring the named user is the cm:creator of the new node.
 *
 * @param quickFileName the file name of the quick file - will also be the cm:name of the new node.
 * @param parentNode the parent node
 * @param nodeCreator the username of the person who will create the node
 * @return the newly created NodeRef.
 * @since 4.1.4
 */
public NodeRef createQuickFileByName(final String quickFileName, final NodeRef parentNode, final String nodeCreator)
{
    final MimetypeMap mimetypeService = (MimetypeMap) appContextRule.getApplicationContext().getBean("mimetypeService");
    final RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) appContextRule.getApplicationContext().getBean("retryingTransactionHelper");
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(nodeCreator);
    
    NodeRef newNodeRef = transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            final NodeRef result = createNode(quickFileName, parentNode, ContentModel.TYPE_CONTENT);
            
            File quickFile = AbstractContentTransformerTest.loadNamedQuickTestFile(quickFileName);
            
            ContentService contentService = appContextRule.getApplicationContext().getBean("contentService", ContentService.class);
            ContentWriter writer = contentService.getWriter(result, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(mimetypeService.guessMimetype(quickFileName));
            writer.setEncoding("UTF-8");
            writer.putContent(quickFile);
            
            return result;
        }
    });
    
    AuthenticationUtil.popAuthentication();
    
    this.temporaryNodeRefs.add(newNodeRef);
    return newNodeRef;
}
 
Example 8
Project: alfresco-repository   File: NodeArchiveServiceImpl.java   View Source Code Vote up 5 votes
/**
 * Uses batch processing and job locking to purge all archived nodes
 */
public void purgeAllArchivedNodes(StoreRef originalStoreRef)
{
    final String user = AuthenticationUtil.getFullyAuthenticatedUser();
    if (user == null)
    {
        throw new IllegalStateException("Cannot purge as there is no authenticated user.");
    }
    
    /**
     * Worker that purges each node
     */
    BatchProcessWorker<NodeRef> worker = new BatchProcessor.BatchProcessWorkerAdaptor<NodeRef>()
    {
        @Override
        public void beforeProcess() throws Throwable
        {
            AuthenticationUtil.pushAuthentication();
        }
        public void process(NodeRef nodeRef) throws Throwable
        {
            AuthenticationUtil.setFullyAuthenticatedUser(user);
            if (nodeService.exists(nodeRef))
            {
                invokeBeforePurgeNode(nodeRef);
                nodeService.deleteNode(nodeRef);
            }
        }
        @Override
        public void afterProcess() throws Throwable
        {
            AuthenticationUtil.popAuthentication();
        }
    };
    doBulkOperation(user, originalStoreRef, worker);
}
 
Example 9
Project: alfresco-repository   File: TemporaryNodes.java   View Source Code Vote up 5 votes
/**
 * This method creates a NodeRef with some text/plain, UTF-8 content and adds it to the internal list of NodeRefs to be tidied up by the rule.
 * This method will be run in its own transaction and will be run with the specified user as the fully authenticated user,
 * thus ensuring the named user is the cm:creator of the new node.
 * 
 * @param parentNode the parent node
 * @param nodeCmName the cm:name of the new node
 * @param nodeType   the type of the new node
 * @param nodeCreator the username of the person who will create the node
 * @param textContent the text/plain, UTF-8 content that will be stored in the node's content. <code>null</code> content will not be written.
 * @return the newly created NodeRef.
 */
public NodeRef createNodeWithTextContent(final NodeRef parentNode, final QName childName, final String nodeCmName, final QName nodeType, final String nodeCreator, final String textContent)
{
    final RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) appContextRule.getApplicationContext().getBean("retryingTransactionHelper");
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(nodeCreator);
    
    NodeRef newNodeRef = transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            final NodeService nodeService = (NodeService) appContextRule.getApplicationContext().getBean("nodeService");
            
            Map<QName, Serializable> props = new HashMap<QName, Serializable>();
            props.put(ContentModel.PROP_NAME, nodeCmName);
            ChildAssociationRef childAssoc = nodeService.createNode(parentNode,
                        ContentModel.ASSOC_CONTAINS,
                        childName,
                        nodeType,
                        props);
            
            // If there is any content, add it.
            if (textContent != null)
            {
                ContentService contentService = appContextRule.getApplicationContext().getBean("contentService", ContentService.class);
                ContentWriter writer = contentService.getWriter(childAssoc.getChildRef(), ContentModel.PROP_CONTENT, true);
                writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
                writer.setEncoding("UTF-8");
                writer.putContent(textContent);
            }
            return childAssoc.getChildRef();
        }
    });
    
    AuthenticationUtil.popAuthentication();
    
    this.temporaryNodeRefs.add(newNodeRef);
    return newNodeRef;
}
 
Example 10
Project: alfresco-repository   File: AbstractMailActionExecuterTest.java   View Source Code Vote up 5 votes
/**
 * ACE-2564
 */
@Test
public void testSendEmailByExternalUser() throws IOException, MessagingException
{
    final Serializable recipients = (Serializable) Arrays.asList(BRITISH_USER.getUsername());
    final String subject = "";
    final String template = "alfresco/templates/mail/test.txt.ftl";
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(EXTERNAL_USER.getUsername());
    MimeMessage message = null;


    try
    {

        // these persons should be without emails
        // testing for GROUP_EVERYONE
        
        final String tenantId = getUsersHomeTenant(BRITISH_USER.getUsername());

        // USER_6 not exist for USER_1, but he will be added to recipients
        message = TenantUtil.runAsTenant(new TenantRunAsWork<MimeMessage>()
        {
            @Override
            public MimeMessage doWork() throws Exception
            {
                return sendMessage(null, recipients, subject, template);
            }
        }, tenantId);

        Assert.assertNotNull(message);
        Assert.assertEquals("Hello 01-Jan-1970", (String) message.getContent());
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 11
Project: alfresco-remote-api   File: TestActions.java   View Source Code Vote up 5 votes
@Before
public void setUp() throws Exception
{
    nodeService = applicationContext.getBean("NodeService", NodeService.class);
    ownableService = applicationContext.getBean("OwnableService", OwnableService.class);
    actionService = applicationContext.getBean("ActionService", ActionService.class);
    actions = publicApiClient.actions();

    accountsIt = getTestFixture().getNetworksIt();
    account1 = accountsIt.next();
    account1PersonIt = account1.getPersonIds().iterator();
    
    // Capture authentication pre-test, so we can restore it again afterwards.
    AuthenticationUtil.pushAuthentication();
}
 
Example 12
Project: alfresco-repository   File: LockableAspectInterceptorTest.java   View Source Code Vote up 5 votes
private void writeData(String fileName, final NodeRef fileNodeRef) 
{
    nodeService.addAspect(fileNodeRef, ContentModel.ASPECT_NO_CONTENT, null);
    // Access the content
    ContentWriter writer = fileFolderService.getWriter(fileNodeRef);

    // set content properties
    writer.guessMimetype(fileName);
    writer.guessEncoding();

    // Get the input stream from the request data
    InputStream is = getClass().getClassLoader().getResourceAsStream(
          "farmers_markets_list_2003.doc");

    // Write the new data to the content node
    writer.putContent(is);

    // write info about author
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
    this.transactionService.getRetryingTransactionHelper().doInTransaction(
    new RetryingTransactionCallback<Void>() {
       public Void execute() throws Throwable 
       {
          // Create the action
          Action action = actionService.createAction(ContentMetadataExtracter.EXECUTOR_NAME);
          try 
          {
             actionService.executeAction(action, fileNodeRef);
          }
          catch (Throwable th) 
          {
             // do nothing
          }
          return null;
       }
    });
    AuthenticationUtil.popAuthentication();
}
 
Example 13
Project: alfresco-repository   File: HomeFolderProviderSynchronizer.java   View Source Code Vote up 4 votes
@Override
public void beforeProcess() throws Throwable
{
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(userName);
}
 
Example 14
Project: alfresco-repository   File: CMISTest.java   View Source Code Vote up 4 votes
/**
 * MNT-14951: Test that the list of parents can be retrieved for a folder.
 */
@Test
public void testCMISGetObjectParents() throws Exception
{
    // setUp audit subsystem
    setupAudit();
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    
    try
    {
        final NodeRef folderWithTwoParents = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<NodeRef>()
        {
            @Override
            public NodeRef execute() throws Throwable
            {
                NodeRef companyHomeNodeRef = repositoryHelper.getCompanyHome();

                String folder1 = GUID.generate();
                FileInfo folderInfo1 = fileFolderService.create(companyHomeNodeRef, folder1, ContentModel.TYPE_FOLDER);
                assertNotNull(folderInfo1);
                
                String folder2 = GUID.generate();
                FileInfo folderInfo2 = fileFolderService.create(companyHomeNodeRef, folder2, ContentModel.TYPE_FOLDER);
                assertNotNull(folderInfo2);
                
                // Create folder11 as a subfolder of folder1
                String folder11 = GUID.generate();
                FileInfo folderInfo11 = fileFolderService.create(folderInfo1.getNodeRef(), folder11, ContentModel.TYPE_FOLDER);
                assertNotNull(folderInfo11);
                
                // Add folder2 as second parent for folder11
                nodeService.addChild(folderInfo2.getNodeRef(), folderInfo11.getNodeRef(), ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS);
                
                return folderInfo11.getNodeRef();
            }
        });
        
        withCmisService(new CmisServiceCallback<Void>()
        {
            @Override
            public Void execute(CmisService cmisService)
            {
                List<RepositoryInfo> repositories = cmisService.getRepositoryInfos(null);
                assertNotNull(repositories);
                assertTrue(repositories.size() > 0);
                String repositoryId = repositories.iterator().next().getId();

                List<ObjectParentData> parents = cmisService.getObjectParents(repositoryId, folderWithTwoParents.getId(), null, Boolean.FALSE, IncludeRelationships.NONE,
                                                                              "cmis:none", Boolean.FALSE, null);
                // Check if the second parent was also returned.
                assertEquals(2, parents.size());

                return null;
            }
        }, CmisVersion.CMIS_1_1);
    }
    finally
    {
        auditSubsystem.destroy();
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 15
Project: alfresco-repository   File: ModelValidatorTest.java   View Source Code Vote up 4 votes
/**
 * Test that a model cannot be deleted if nodes and properties exist that reference it.
 * 
 * @throws Exception
 */
@Test
public void testInvalidModelDelete() throws Exception
{
    // authenticate
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    final QName modelQName = QName.createQName(testNamespace, modelName);

    // Create a node that uses the new type (type is created in setUp)
    RetryingTransactionCallback<NodeRef> createNodeCallback = new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            // Create a node that uses it
            NodeRef parentNodeRef = getParentNodeRef();
            FileInfo folder = fileFolderService.create(parentNodeRef, GUID.generate(), ContentModel.TYPE_FOLDER);
            assertNotNull(folder);
            NodeRef folderNodeRef = folder.getNodeRef();
            FileInfo node = fileFolderService.create(folderNodeRef, GUID.generate(), typeQName);
            assertNotNull(node);
            NodeRef nodeRef = node.getNodeRef();

            ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
            writer.putContent("Test");

            Map<QName, Serializable> properties = new HashMap<>();
            properties.put(propertyQName, "Test");
            nodeService.setProperties(nodeRef, properties);

            versionService.createVersion(nodeRef, null);

            return nodeRef;
        }
    };
    transactionService.getRetryingTransactionHelper().doInTransaction(createNodeCallback, false, true);

    // try to delete the model
    RetryingTransactionCallback<Void> deleteModelCallback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            if(modelValidator.canDeleteModel(modelQName))
            {
                fail("Model delete should have failed");
            }

            return null;
        }
    };
    transactionService.getRetryingTransactionHelper().doInTransaction(deleteModelCallback, false, true);
}
 
Example 16
Project: alfresco-remote-api   File: RemoteFileFolderLoaderTest.java   View Source Code Vote up 4 votes
/**
 * Load 15 files with default sizes
 */
@SuppressWarnings("unchecked")
public void testLoad_15_default() throws Exception
{
    JSONObject body = new JSONObject();
    body.put(FileFolderLoaderPost.KEY_FOLDER_PATH, loadHomePath);
    body.put(FileFolderLoaderPost.KEY_FILE_COUNT, 15);
    body.put(FileFolderLoaderPost.KEY_FILES_PER_TXN, 10);
    
    Response response = null;
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setFullyAuthenticatedUser("hhoudini");
        response = sendRequest(
                new PostRequest(URL,  body.toString(), "application/json"),
                Status.STATUS_OK,
                "hhoudini");
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
    assertEquals("{\"count\":15}", response.getContentAsString());
    
    // Check file(s)
    assertEquals(15, nodeService.countChildAssocs(loadHomeNodeRef, true));
    // Size should be default
    List<FileInfo> fileInfos = fileFolderService.list(loadHomeNodeRef);
    for (FileInfo fileInfo : fileInfos)
    {
        NodeRef fileNodeRef = fileInfo.getNodeRef();
        ContentReader reader = fileFolderService.getReader(fileNodeRef);
        // Expect spoofing by default
        assertTrue(reader.getContentUrl().startsWith(FileContentStore.SPOOF_PROTOCOL));
        assertTrue(
                "Default file size not correct: " + reader,
                FileFolderLoaderPost.DEFAULT_MIN_FILE_SIZE < reader.getSize() &&
                    reader.getSize() < FileFolderLoaderPost.DEFAULT_MAX_FILE_SIZE);
        // Check creator
        assertEquals("hhoudini", nodeService.getProperty(fileNodeRef, ContentModel.PROP_CREATOR));
        // We also expect the default language description to be present
        String description = (String) nodeService.getProperty(fileNodeRef, ContentModel.PROP_DESCRIPTION);
        assertNotNull("No description", description);
        assertEquals("Description length incorrect: \"" + description + "\"", 128L, description.getBytes("UTF-8").length);
    }
}
 
Example 17
Project: alfresco-repository   File: TemporarySites.java   View Source Code Vote up 4 votes
/**
 * This method creates a test site (of Alfresco type <code>st:site</code>) and one user for each of the Share Site Roles.
 * This method will be run in its own transaction and will be run with the specified user as the fully authenticated user,
 * thus ensuring the named user is the creator of the new site.
 * The site and its users will be deleted automatically by the rule.
 * 
 * @param sitePreset the site preset.
 * @param visibility the Site visibility.
 * @param siteCreator the username of a user who will be used to create the site (user must exist of course).
 * @return the {@link SiteInfo} object for the newly created site.
 */
public TestSiteAndMemberInfo createTestSiteWithUserPerRole(final String siteShortName, String sitePreset, SiteVisibility visibility, String siteCreator)
{
    // create the site
    SiteInfo result = this.createSite(sitePreset, siteShortName, null, null, visibility, siteCreator);
    
    // create the users
    final RetryingTransactionHelper transactionHelper = appContextRule.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    final SiteService siteService = appContextRule.getApplicationContext().getBean("siteService", SiteService.class);
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(siteCreator);
    
    // Create users for this test site that cover the various roles.
    List<String> userNames = transactionHelper.doInTransaction(new RetryingTransactionCallback<List<String>>()
    {
        public List<String> execute() throws Throwable
        {
            List<String> users = new ArrayList<String>(4);
            
            for (String shareRole : SiteModel.STANDARD_PERMISSIONS)
            {
                final String userName = siteShortName + "_" + shareRole + "_" + GUID.generate();
                
                log.debug("Creating temporary site user " + userName);
                
                createPerson(userName);
                siteService.setMembership(siteShortName, userName, shareRole);
                users.add(userName);
                
                temporarySiteUsers.add(userName);
            }
            
            return users;
        }
    });
    
    NodeRef doclibFolder = transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            return siteService.getContainer(siteShortName, SiteService.DOCUMENT_LIBRARY);
        }
    });
    
    AuthenticationUtil.popAuthentication();
     
    
    return new TestSiteAndMemberInfo(result, doclibFolder, userNames.get(0),
                                                           userNames.get(1),
                                                           userNames.get(2),
                                                           userNames.get(3));
}
 
Example 18
Project: alfresco-repository   File: FileFolderLoaderTest.java   View Source Code Vote up 4 votes
/**
 * 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
Project: alfresco-repository   File: FileFolderLoaderTest.java   View Source Code Vote up 4 votes
/**
 * 10 files; 10 per txn; force storage; identical
 */
@Test
public void testLoad_04() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
        int created = fileFolderLoader.createFiles(
                writeFolderPath,
                10, 10, 1024L, 1024L, 1L, true,
                10, 256L);
        assertEquals("Incorrect number of files generated.", 10, created);
        // Count
        assertEquals(10, 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 unique URLs: ", lastUrl, reader.getContentUrl());
                lastUrl = reader.getContentUrl();
            }
            // Check content
            if (lastText == null)
            {
                lastText = reader.getContentString();
            }
            else
            {
                String currentStr = reader.getContentString();
                assertEquals("All text must be identical due to same 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));
                assertEquals("All descriptions must be identical due to varying seed. ", lastDescr, currentDescr);
                lastDescr = currentDescr;
            }
        }
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 20
Project: alfresco-repository   File: CMISTest.java   View Source Code Vote up 4 votes
/**
 * Test to ensure that versioning properties have default values defined in Alfresco content model.
 * Testing  <b>cm:initialVersion</b>, <b>cm:autoVersion</b> and <b>cm:autoVersionOnUpdateProps</b> properties 
 * 
 * @throws Exception
 */
@Test
public void testVersioningPropertiesHaveDefaultValue() throws Exception
{
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    try
    {
        // Create document via CMIS
        final NodeRef documentNodeRef = withCmisService(new CmisServiceCallback<NodeRef>()
        {
            @Override
            public NodeRef execute(CmisService cmisService)
            {
                String repositoryId = cmisService.getRepositoryInfos(null).get(0).getId();

                String rootNodeId = cmisService.getObjectByPath(repositoryId, "/", null, true, IncludeRelationships.NONE, null, false, true, null).getId();

                Collection<PropertyData<?>> propsList = new ArrayList<PropertyData<?>>();
                propsList.add(new PropertyStringImpl(PropertyIds.NAME, "Folder-" + GUID.generate()));
                propsList.add(new PropertyIdImpl(PropertyIds.OBJECT_TYPE_ID, "cmis:folder"));

                String folderId = cmisService.createFolder(repositoryId, new PropertiesImpl(propsList), rootNodeId, null, null, null, null);

                propsList = new ArrayList<PropertyData<?>>();
                propsList.add(new PropertyStringImpl(PropertyIds.NAME, "File-" + GUID.generate()));
                propsList.add(new PropertyIdImpl(PropertyIds.OBJECT_TYPE_ID, "cmis:document"));

                String nodeId = cmisService.createDocument(repositoryId, new PropertiesImpl(propsList), folderId, null, null, null, null, null, null);

                return new NodeRef(nodeId.substring(0, nodeId.indexOf(';')));
            }
        }, CmisVersion.CMIS_1_1);

        // check versioning properties
        transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<List<Void>>()
        {
            @Override
            public List<Void> execute() throws Throwable
            {
                assertTrue(nodeService.exists(documentNodeRef));
                assertTrue(nodeService.hasAspect(documentNodeRef, ContentModel.ASPECT_VERSIONABLE));

                AspectDefinition ad = dictionaryService.getAspect(ContentModel.ASPECT_VERSIONABLE);
                Map<QName, org.alfresco.service.cmr.dictionary.PropertyDefinition> properties = ad.getProperties();

                for (QName qName : new QName[] {ContentModel.PROP_INITIAL_VERSION, ContentModel.PROP_AUTO_VERSION, ContentModel.PROP_AUTO_VERSION_PROPS})
                {
                    Serializable property = nodeService.getProperty(documentNodeRef, qName);

                    assertNotNull(property);

                    org.alfresco.service.cmr.dictionary.PropertyDefinition pd = properties.get(qName);
                    assertNotNull(pd.getDefaultValue());

                    assertEquals(property, Boolean.parseBoolean(pd.getDefaultValue()));
                }

                return null;
            }
        });
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}