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

The following examples show how to use org.alfresco.repo.security.authentication.AuthenticationUtil#popAuthentication() . 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: RemoteFileFolderLoaderTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void tearDown() throws Exception
{
    RetryingTransactionCallback<Void> deleteFolderWork = new RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            fileFolderService.delete(loadHomeNodeRef);
            // Done
            return null;
        }
    };
    try
    {
        transactionService.getRetryingTransactionHelper().doInTransaction(deleteFolderWork);
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 2
Source File: TemporaryNodes.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 3
Source File: FileFolderLoaderTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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
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 5
Source File: TestActions.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@After
public void tearDown()
{
    // Restore authentication to pre-test state.
    try
    {
        AuthenticationUtil.popAuthentication();
    }
    catch(EmptyStackException e)
    {
        // Nothing to do.
    }
}
 
Example 6
Source File: TemporaryNodes.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 7
Source File: NodeArchiveServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 8
Source File: SiteServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testInviteDisabledUser() throws Exception
{
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    String username = "testUser" + System.nanoTime();
    String siteShortName = GUID.generate();
    try
    {
        createUser(username);
        createSite("myPreset", siteShortName, "myTitle", "myDescription", SiteVisibility.PUBLIC, 200);

        NodeRef personNodeRef = personService.getPerson(username);
        String firstName = (String) nodeService.getProperty(personNodeRef, ContentModel.PROP_FIRSTNAME);
        String lastName = (String) nodeService.getProperty(personNodeRef, ContentModel.PROP_LASTNAME);
        String email = (String) nodeService.getProperty(personNodeRef, ContentModel.PROP_EMAIL);
        String serverPath = "http://localhost:8081/share/";
        String acceptURL = "page/accept-invite";
        String rejectURL = "page/reject-invite";

        authenticationService.setAuthenticationEnabled(username, false);
        createNominatedInvitation(siteShortName, firstName, lastName, email, username, SiteModel.SITE_CONSUMER, serverPath, acceptURL, rejectURL, 409);
        fail("The user " + username + " is disabled and cannot be invited");
    }
    catch (JSONException e)
    {
        // expected
    }
    finally
    {
        siteService.deleteSite(siteShortName);
        deleteUser(username);
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 9
Source File: MultilingualContentServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Check whether non-admin users can take part in ML document manipulation
 */
public void testPermissions() throws Exception
{
    // Grant the guest user rights to our working folder
    PermissionService permissionService = serviceRegistry.getPermissionService();
    AuthenticationComponent authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
    permissionService.setPermission(
            folderNodeRef,
            AuthenticationUtil.getGuestUserName(),
            PermissionService.ALL_PERMISSIONS,
            true);
    // Push the current authentication
    AuthenticationUtil.pushAuthentication();
    try
    {
        authenticationComponent.setGuestUserAsCurrentUser();
        // Create some documents
        NodeRef chineseContentNodeRef = createContent();
        NodeRef frenchContentNodeRef = createContent();
        // Do ML work
        multilingualContentService.makeTranslation(chineseContentNodeRef, Locale.CHINESE);
        multilingualContentService.addTranslation(frenchContentNodeRef, chineseContentNodeRef, Locale.FRENCH);
        multilingualContentService.addEmptyTranslation(chineseContentNodeRef, null, Locale.JAPANESE);
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 10
Source File: TestPeople.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@After
public void tearDown()
{
    // Restore authentication to pre-test state.
    try
    {
        AuthenticationUtil.popAuthentication();
    }
    catch(EmptyStackException e)
    {
        // Nothing to do.
    }
}
 
Example 11
Source File: CMISTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * MNT-20139
 * CmisConnector returns wrong values for changeLogToken and hasMoreItems
 */
@Test
public void testGetContentChanges()
{
    setupAudit();

    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    try
    {
        // create folders with files
        createContent("testfolder" + GUID.generate(), "testdoc.txt" + GUID.generate(), false);
        createContent("testfolder" + GUID.generate(), "testdoc.txt" + GUID.generate(), false);
        createContent("testfolder" + GUID.generate(), "testdoc.txt" + GUID.generate(), false);

        Holder<String> changeLogToken = new Holder<String>();

        /*
         * GetContentChanges with maxitems = 2 and null changeLogToken
         * Check that changeLogToken should be the latest from the retrieved entries
         */
        ObjectList ol = this.cmisConnector.getContentChanges(changeLogToken, new BigInteger("2"));
        assertEquals(2, ol.getObjects().size());
        assertEquals("ChangeLogToken should be latest from retrieved entries.", "2", changeLogToken.getValue());
        assertTrue(ol.hasMoreItems());

        /*
         * GetContentChanges with maxitems = 2 and changeLogToken = 0
         * Check that changeLogToken should be the latest from the retrieved entries
         */
        changeLogToken.setValue(Integer.toString(0));
        ol = this.cmisConnector.getContentChanges(changeLogToken, new BigInteger("2"));
        assertEquals(2, ol.getObjects().size());
        assertEquals("ChangeLogToken should be latest from retrieved entries.", "2", changeLogToken.getValue());
        assertTrue(ol.hasMoreItems());

        /*
         * GetContentChanges with changeLogToken = maxChangeLogToken - 2
         * Check that changeLogToken is not null when the latest entries (fromToken) are retrieved
         */
        Long latestToken = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Long>()
        {
            public Long execute() throws Exception
            {
                return Long.parseLong(cmisConnector.getRepositoryInfo(CmisVersion.CMIS_1_1).getLatestChangeLogToken());
            }
        }, true, false);

        Long fromToken = latestToken - 2;
        changeLogToken.setValue(fromToken.toString());

        ol = this.cmisConnector.getContentChanges(changeLogToken, new BigInteger("20"));
        assertEquals(3, ol.getObjects().size());
        assertNotNull(changeLogToken.getValue());
        assertEquals("ChangeLogToken should be the latest from all entries.", latestToken.toString(), changeLogToken.getValue());
        assertFalse(ol.hasMoreItems());
    }
    finally
    {
        auditSubsystem.destroy();
        AuthenticationUtil.popAuthentication();
    };
}
 
Example 12
Source File: CMISTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * MNT-13529: Just-installed Alfresco does not return a CMIS latestChangeLogToken
 * 
 * @throws Exception
 */
@Test
public void testMNT13529() throws Exception
{
    setupAudit();

    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    try
    {
        // Delete the entries, it simulates just installed Alfresco for reproduce the issue
        final Long appId = auditSubsystem.getAuditApplicationByName("CMISChangeLog").getApplicationId();
        RetryingTransactionCallback<Void> deletedCallback = new RetryingTransactionCallback<Void>()
        {
            public Void execute() throws Throwable
            {
                auditDAO.deleteAuditEntries(appId, null, null);
                return null;
            }
        };
        transactionService.getRetryingTransactionHelper().doInTransaction(deletedCallback);

        // Retrieve initial latestChangeLogToken
        final String initialChangeLogToken = withCmisService(new CmisServiceCallback<String>()
        {
            @Override
            public String execute(CmisService cmisService)
            {
                List<RepositoryInfo> repositories = cmisService.getRepositoryInfos(null);
                assertNotNull(repositories);
                assertTrue(repositories.size() > 0);
                RepositoryInfo repo = repositories.iterator().next();

                return repo.getLatestChangeLogToken();
            }
        }, CmisVersion.CMIS_1_1);

        assertNotNull(initialChangeLogToken);
        assertEquals("0", initialChangeLogToken);
    }
    finally
    {
        auditSubsystem.destroy();
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 13
Source File: RunAsFullyAuthenticatedRule.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override public Statement apply(final Statement base, final Description description)
{
    return new Statement()
    {
        @Override public void evaluate() throws Throwable
        {
            // Store the current authentication
            AuthenticationUtil.pushAuthentication();
            
            // First, try for a username provided on the @Test method itself.
            String runAsUser = getMethodAnnotatedUserName(description);
            
            if (runAsUser != null)
            {
                // There is a @Test method username.
                log.debug("Running as method annotation-provided user: " + runAsUser);
                log.debug("   See " + description.getClassName() + "." + description.getMethodName());
            }
            else
            {
                // There is no @Test method username, so fall back to rule-provided person.
                if (fixedUserName != null)
                {
                    runAsUser = fixedUserName;
                    log.debug("Running as username defined in this rule: " + runAsUser);
                }
                else if (personRule != null)
                {
                    runAsUser = personRule.getUsername();
                    log.debug("Running as username provided by another rule: " + runAsUser);
                }
                else
                {
                    throw new Exception("Illegal rule: must provide username or " +
                                                                    AlfrescoPerson.class.getSimpleName() + " at rule construction or else a " +
                                                                    RunAsUser.class.getSimpleName() + " annotation.");
                }
            }
            AuthenticationUtil.setFullyAuthenticatedUser(runAsUser);
            
            
            try
            {
                // Execute the test method or whatever other rules are configured further down the stack.
                base.evaluate();
            }
            finally
            {
                // After - ensure that pass or fail, the authentication is restored.
                AuthenticationUtil.popAuthentication();
            }
        }
    };
}
 
Example 14
Source File: RemoteFileFolderLoaderTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Load 15 files; 1K size; 1 document sample; force binary storage
 */
@SuppressWarnings("unchecked")
public void testLoad_15_16bytes() throws Exception
{
    JSONObject body = new JSONObject();
    body.put(FileFolderLoaderPost.KEY_FOLDER_PATH, loadHomePath);
    body.put(FileFolderLoaderPost.KEY_MIN_FILE_SIZE, 16L);
    body.put(FileFolderLoaderPost.KEY_MAX_FILE_SIZE, 16L);
    body.put(FileFolderLoaderPost.KEY_MAX_UNIQUE_DOCUMENTS, 1L);
    body.put(FileFolderLoaderPost.KEY_FORCE_BINARY_STORAGE, Boolean.TRUE);
    
    Response response = null;
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setFullyAuthenticatedUser("maggi");
        response = sendRequest(
                new PostRequest(URL,  body.toString(), "application/json"),
                Status.STATUS_OK,
                "maggi");
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
    assertEquals("{\"count\":100}", response.getContentAsString());
    
    // Check file(s)
    assertEquals(100, nodeService.countChildAssocs(loadHomeNodeRef, true));
    
    // Consistent binary text
    String contentUrlCheck = SpoofedTextContentReader.createContentUrl(Locale.ENGLISH, 0L, 16L);
    ContentReader readerCheck = new SpoofedTextContentReader(contentUrlCheck);
    String textCheck = readerCheck.getContentString();
    
    // Size should be default
    List<FileInfo> fileInfos = fileFolderService.list(loadHomeNodeRef);
    for (FileInfo fileInfo : fileInfos)
    {
        NodeRef fileNodeRef = fileInfo.getNodeRef();
        ContentReader reader = fileFolderService.getReader(fileNodeRef);
        // Expect storage in store
        assertTrue(reader.getContentUrl().startsWith(FileContentStore.STORE_PROTOCOL));
        // Check text
        String text = reader.getContentString();
        assertEquals("Text not the same.", textCheck, text);
    }
}
 
Example 15
Source File: TemporarySites.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 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 16
Source File: CMISTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 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();
    }
}
 
Example 17
Source File: GetChildrenCannedQueryTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unused")
public void testAspectFiltering() throws Exception
{
    NodeRef parentNodeRef = repositoryHelper.getCompanyHome();
    NodeRef nodeRef1 = null;
    NodeRef nodeRef2 = null;
    NodeRef nodeRef3 = null;
    NodeRef nodeRef4 = null;
    NodeRef nodeRef5 = null;
    NodeRef nodeRef6 = null;
    NodeRef nodeRef7 = null;
    NodeRef nodeRef8 = null;
    NodeRef nodeRef9 = null;
    NodeRef nodeRef10 = null;
    
    // Create some nodes with integer properties on which to sort, in this case cm:fiveStarRatingScheme and cm:likesRatingScheme
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    try
    {
        nodeRef1 = createContent(parentNodeRef, "node1", ContentModel.TYPE_CONTENT);
        nodeRef2 = createContent(parentNodeRef, "node2", ContentModel.TYPE_CONTENT);
        nodeRef3 = createContent(parentNodeRef, "node3", ContentModel.TYPE_CONTENT);
        nodeRef4 = createContent(parentNodeRef, "node4", ContentModel.TYPE_CONTENT);
        nodeRef5 = createContent(parentNodeRef, "node5", ContentModel.TYPE_CONTENT);
        
        nodeRef6 = createContent(parentNodeRef, "node6", ContentModel.TYPE_CONTENT);
        nodeRef7 = createContent(parentNodeRef, "node7", ContentModel.TYPE_CONTENT);
        nodeRef8 = createContent(parentNodeRef, "node8", ContentModel.TYPE_CONTENT);
        nodeRef9 = createContent(parentNodeRef, "node9", ContentModel.TYPE_CONTENT);
        nodeRef10 = createContent(parentNodeRef, "node10", ContentModel.TYPE_CONTENT);
        
        Map<QName, Serializable> props = Collections.emptyMap();
        
        nodeService.addAspect(nodeRef2, ContentModel.ASPECT_CLASSIFIABLE, props);
        nodeService.addAspect(nodeRef4, ContentModel.ASPECT_CLASSIFIABLE, props);
        nodeService.addAspect(nodeRef4, RenditionModel.ASPECT_RENDITION, props);
        nodeService.addAspect(nodeRef8, ContentModel.ASPECT_CLASSIFIABLE, props);
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
    
    // do children canned query
    PagingResults<NodeRef> results = list(parentNodeRef, -1, -1, 0);
    List<NodeRef> nodeRefs = results.getPage();
    for (NodeRef nodeRef : nodeRefs)
    {
        System.out.print(nodeRef);
        Set<QName> aspects = nodeService.getAspects(nodeRef);
        for (QName aspect : aspects)
        {
            System.out.print(" " + aspect);
        }
        System.out.println();
    }
    Set<QName> includedAspects = new HashSet<QName>(Arrays.asList(new QName[] {ContentModel.ASPECT_CLASSIFIABLE}));
    results = list(parentNodeRef, includedAspects, null, -1, -1, 0);
    assertEquals(3, results.getPage().size());

    Set<QName> excludedAspects = new HashSet<QName>(Arrays.asList(new QName[] {RenditionModel.ASPECT_RENDITION}));
    results = list(parentNodeRef, null, excludedAspects, -1, -1, 0);
    for (NodeRef result : results.getPage())
    {
        assertFalse(nodeService.getAspects(result).contains(RenditionModel.ASPECT_RENDITION));
    }

    results = list(parentNodeRef, includedAspects, excludedAspects, -1, -1, 0);
    assertEquals(2, results.getPage().size());
}
 
Example 18
Source File: CMISTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * MNT-11304: Test that Alfresco has no default boundaries for decimals
 * @throws Exception
 */
@Test
public void testDecimalDefaultBoundaries() throws Exception
{
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    
    try
    {
        withCmisService(new CmisServiceCallback<Void>()
        {
            @Override
            public Void execute(CmisService cmisService)
            {
                List<RepositoryInfo> repositories = cmisService.getRepositoryInfos(null);
                assertTrue(repositories.size() > 0);
                RepositoryInfo repo = repositories.get(0);
                String repositoryId = repo.getId();
                
                TypeDefinition decimalTypeDef = cmisService.getTypeDefinition(repositoryId, "D:tcdm:testdecimalstype", null);
                
                PropertyDecimalDefinitionImpl floatNoBoundsTypeDef = 
                        (PropertyDecimalDefinitionImpl)decimalTypeDef.getPropertyDefinitions().get("tcdm:float");
                PropertyDecimalDefinitionImpl doubleNoBoundsTypeDef = 
                        (PropertyDecimalDefinitionImpl)decimalTypeDef.getPropertyDefinitions().get("tcdm:double");
                
                PropertyDecimalDefinitionImpl floatWithBoundsTypeDef = 
                        (PropertyDecimalDefinitionImpl)decimalTypeDef.getPropertyDefinitions().get("tcdm:floatwithbounds");
                PropertyDecimalDefinitionImpl doubleWithBoundsTypeDef = 
                        (PropertyDecimalDefinitionImpl)decimalTypeDef.getPropertyDefinitions().get("tcdm:doublewithbounds");
                
                // test that there is not default boundaries for decimals
                assertNull(floatNoBoundsTypeDef.getMinValue());
                assertNull(floatNoBoundsTypeDef.getMaxValue());
                
                assertNull(doubleNoBoundsTypeDef.getMinValue());
                assertNull(doubleNoBoundsTypeDef.getMaxValue());
                
                // test for pre-defined boundaries
                assertTrue(floatWithBoundsTypeDef.getMinValue().equals(BigDecimal.valueOf(-10f)));
                assertTrue(floatWithBoundsTypeDef.getMaxValue().equals(BigDecimal.valueOf(10f)));
                
                assertTrue(doubleWithBoundsTypeDef.getMinValue().equals(BigDecimal.valueOf(-10d)));
                assertTrue(doubleWithBoundsTypeDef.getMaxValue().equals(BigDecimal.valueOf(10d)));

                return null;
            }
        }, CmisVersion.CMIS_1_1);
        
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 19
Source File: CMISTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * MNT-11727: move and rename operations should be shown as an UPDATE in the CMIS change log
 */
@Test
public void testMoveRenameWithCMISshouldBeAuditedAsUPDATE() throws Exception
{
    // setUp audit subsystem
    setupAudit();

    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    try
    {
        assertTrue("Audit is not enabled", auditSubsystem.isAuditEnabled());
        assertNotNull("CMIS audit is not enabled", auditSubsystem.getAuditApplicationByName("CMISChangeLog"));

        NodeRef companyHomeNodeRef = repositoryHelper.getCompanyHome();

        String folder = GUID.generate();
        FileInfo folderInfo = fileFolderService.create(companyHomeNodeRef, folder, ContentModel.TYPE_FOLDER);

        final String actualToken = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<String>()
        {
            public String execute() throws Exception
            {
                return cmisConnector.getRepositoryInfo(CmisVersion.CMIS_1_1).getLatestChangeLogToken();
            }
        }, true, false);

        String content = GUID.generate();
        FileInfo document = fileFolderService.create(folderInfo.getNodeRef(), content, ContentModel.TYPE_CONTENT);
        assertNotNull(document);
        nodeService.setProperty(document.getNodeRef(), ContentModel.PROP_NAME, content);

        Holder<String> changeLogToken = new Holder<String>();
        changeLogToken.setValue(actualToken);
        ObjectList changeLog = CMISTest.this.cmisConnector.getContentChanges(changeLogToken, new BigInteger("10"));
        List<ObjectData> events = changeLog.getObjects();
        int count = events.size();
        // it should be 3 entries: 1 for previous folder create, 1 new CREATE (for document create)
        // and 1 NEW UPDATE
        assertEquals(3, count);

        assertEquals(events.get(0).getProperties().getPropertyList().get(0).getValues().get(0), folderInfo.getNodeRef().getId());
        assertEquals(events.get(0).getChangeEventInfo().getChangeType(), ChangeType.CREATED);

        assertTrue(((String) events.get(1).getProperties().getPropertyList().get(0).getValues().get(0)).contains(document.getNodeRef().getId()));
        assertEquals(events.get(1).getChangeEventInfo().getChangeType(), ChangeType.CREATED);

        assertTrue(((String) events.get(2).getProperties().getPropertyList().get(0).getValues().get(0)).contains(document.getNodeRef().getId()));
        assertEquals(events.get(2).getChangeEventInfo().getChangeType(), ChangeType.UPDATED);

        // test rename
        final String actualToken2 = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<String>()
        {
            public String execute() throws Exception
            {
                return cmisConnector.getRepositoryInfo(CmisVersion.CMIS_1_1).getLatestChangeLogToken();
            }
        }, true, false);
        nodeService.setProperty(document.getNodeRef(), ContentModel.PROP_NAME, content + "-updated");

        changeLogToken = new Holder<String>();
        changeLogToken.setValue(actualToken2);
        changeLog = CMISTest.this.cmisConnector.getContentChanges(changeLogToken, new BigInteger("10"));
        events = changeLog.getObjects();
        count = events.size();
        assertEquals(2, count);
        assertEquals("Rename operation should be shown as an UPDATE in the CMIS change log", events.get(1).getChangeEventInfo().getChangeType(), ChangeType.UPDATED);

        // test move
        String targetFolder = GUID.generate();
        FileInfo targetFolderInfo = fileFolderService.create(companyHomeNodeRef, targetFolder, ContentModel.TYPE_FOLDER);

        final String actualToken3 = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<String>()
        {
            public String execute() throws Exception
            {
                return cmisConnector.getRepositoryInfo(CmisVersion.CMIS_1_1).getLatestChangeLogToken();
            }
        }, true, false);
        nodeService.moveNode(document.getNodeRef(), targetFolderInfo.getNodeRef(), ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS);

        changeLogToken = new Holder<String>();
        changeLogToken.setValue(actualToken3);
        changeLog = CMISTest.this.cmisConnector.getContentChanges(changeLogToken, new BigInteger("10"));
        events = changeLog.getObjects();
        count = events.size();
        assertEquals(2, count);
        assertEquals("Move operation should be shown as an UPDATE in the CMIS change log", events.get(1).getChangeEventInfo().getChangeType(), ChangeType.UPDATED);
    }
    finally
    {
        auditSubsystem.destroy();
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 20
Source File: CMISTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 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();
    }
}