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

The following examples show how to use org.alfresco.repo.security.authentication.AuthenticationUtil#setFullyAuthenticatedUser() . 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: TransactionServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testSystemUserHasWritePermissionsInReadOnlyMode()
{
    createUser(USER_ALFRESCO);
    // login as user
    AuthenticationUtil.setFullyAuthenticatedUser(USER_ALFRESCO);

    // start a read-only transaction
    transactionService.setAllowWrite(false, vetoName);
    try
    {
        Boolean isReadOnly = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Boolean>()
        {
            public Boolean doWork() throws Exception
            {
                return transactionService.isReadOnly();
            }
        }, AuthenticationUtil.getSystemUserName());
        assertFalse("SystemUser must has write permissions in read-only mode", isReadOnly);
    }
    finally
    {
        transactionService.setAllowWrite(true, vetoName);
        AuthenticationUtil.clearCurrentSecurityContext();
    }
}
 
Example 2
Source File: OAuth2CredentialsStoreServiceTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testStorePersonalOAuth2Credentials()
{
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);
    //Store new credentials
    oauth2CredentialsStoreService.storePersonalOAuth2Credentials(RemoteSystemId, AccessToken, RefreshToken, ExpiresAt, IssuedAt);
    OAuth2CredentialsInfo oAuth2CredentialsInfo = oauth2CredentialsStoreService.getPersonalOAuth2Credentials(RemoteSystemId);

    assertEquals("Expect that access tokens will match", AccessToken, oAuth2CredentialsInfo.getOAuthAccessToken());
    assertEquals("Expect the refresh token will match", RefreshToken, oAuth2CredentialsInfo.getOAuthRefreshToken());
    assertEquals("Expect that the expiration date will match", ExpiresAt, oAuth2CredentialsInfo.getOAuthTicketExpiresAt());
    assertEquals("Expect that the issued date will match", IssuedAt, oAuth2CredentialsInfo.getOAuthTicketIssuedAt());

    //Update credentials
    oauth2CredentialsStoreService.storePersonalOAuth2Credentials(RemoteSystemId, UpdatedAccessToken, UpdatedRefreshToken, UpdatedExpiresAt, UpdatedIssuedAt);
    OAuth2CredentialsInfo _oAuth2CredentialsInfo = oauth2CredentialsStoreService.getPersonalOAuth2Credentials(RemoteSystemId);

    assertEquals("Expect that access tokens will match", UpdatedAccessToken, _oAuth2CredentialsInfo.getOAuthAccessToken());
    assertEquals("Expect the refresh token will match", UpdatedRefreshToken, _oAuth2CredentialsInfo.getOAuthRefreshToken());
    assertEquals("Expect that the expiration date will match", UpdatedExpiresAt, _oAuth2CredentialsInfo.getOAuthTicketExpiresAt());
    assertEquals("Expect that the issued date will match", UpdatedIssuedAt, _oAuth2CredentialsInfo.getOAuthTicketIssuedAt());
}
 
Example 3
Source File: NodeArchiveServiceRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void createUser(String userName)
{
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    if (this.authenticationService.authenticationExists(userName) == false)
    {
        this.authenticationService.createAuthentication(userName, "password".toCharArray());

        PropertyMap map = new PropertyMap(5);
        map.put(ContentModel.PROP_USERNAME, userName);
        map.put(ContentModel.PROP_FIRSTNAME, "firstName");
        map.put(ContentModel.PROP_LASTNAME, "lastName");
        map.put(ContentModel.PROP_EMAIL, "[email protected]");
        map.put(ContentModel.PROP_JOBTITLE, "jobTitle");

        this.personService.createPerson(map);
        this.createdPeople.add(userName);
    }
}
 
Example 4
Source File: InviteServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testCancelInviteForbiddenWhenInviterNotSiteManager() throws Exception
{
    // inviter (who is Site Manager of the given site) starts invite workflow
    JSONObject result = startInvite(INVITEE_FIRSTNAME,
            INVITEE_LASTNAME, INVITEE_SITE_ROLE, SITE_SHORT_NAME_INVITE_3, Status.STATUS_CREATED);

    // get hold of invite ID of started invite
    JSONObject data = result.getJSONObject("data");
    String inviteId = data.getString("inviteId");

    // when inviter 2 (who is not Site Manager of the given site) tries to cancel invite
    // http status FORBIDDEN must be returned
    AuthenticationUtil.setFullyAuthenticatedUser(USER_INVITER_2);
   //TODO cancelInvite(inviteId, SITE_SHORT_NAME_INVITE_3, Status.STATUS_FORBIDDEN);
    cancelInvite(inviteId, SITE_SHORT_NAME_INVITE_3, Status.STATUS_FORBIDDEN);
}
 
Example 5
Source File: MultiTDemoTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    ctx = ApplicationContextHelper.getApplicationContext(new String[] { ApplicationContextHelper.CONFIG_LOCATIONS[0], "classpath:tenant/mt-*context.xml" });

    nodeService = (NodeService) ctx.getBean("NodeService");
    nodeArchiveService = (NodeArchiveService) ctx.getBean("nodeArchiveService");
    namespaceService = (NamespaceService) ctx.getBean("NamespaceService");
    authenticationService = (MutableAuthenticationService) ctx.getBean("AuthenticationService");
    tenantAdminService = (TenantAdminService) ctx.getBean("tenantAdminService");
    tenantService = (TenantService) ctx.getBean("tenantService");
    personService = (PersonService) ctx.getBean("PersonService");
    searchService = (SearchService) ctx.getBean("SearchService");
    contentService = (ContentService) ctx.getBean("ContentService");
    permissionService = (PermissionService) ctx.getBean("PermissionService");
    ownableService = (OwnableService) ctx.getBean("OwnableService");
    authorityService = (AuthorityService) ctx.getBean("AuthorityService");
    categoryService = (CategoryService) ctx.getBean("CategoryService");
    cociService = (CheckOutCheckInService) ctx.getBean("CheckoutCheckinService");
    repoAdminService = (RepoAdminService) ctx.getBean("RepoAdminService");
    dictionaryService = (DictionaryService) ctx.getBean("DictionaryService");
    usageService = (UsageService) ctx.getBean("usageService");
    transactionService = (TransactionService) ctx.getBean("TransactionService");
    fileFolderService = (FileFolderService) ctx.getBean("FileFolderService");
    ownableService = (OwnableService) ctx.getBean("OwnableService");
    repositoryHelper = (Repository) ctx.getBean("repositoryHelper");
    siteService = (SiteService) ctx.getBean("SiteService");
    
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName()); // authenticate as super-admin
    
    createTenants();
    createUsers();
}
 
Example 6
Source File: ThumbnailServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testCreateThumbnailInReadonlyMode() throws Exception
{
    createUser(USER_ALFRESCO);
    AuthenticationUtil.setFullyAuthenticatedUser(USER_ALFRESCO);
    this.transactionService.setAllowWrite(false);
    
    // do pdfToSWF transformation in read-only
    if (synchronousTransformClient.isSupported(MimetypeMap.MIMETYPE_PDF, -1, null,
            MimetypeMap.MIMETYPE_FLASH, Collections.emptyMap(), null, null))
    {
        // in share creation of thumbnail for webpreview is forced
        String url = "/api/node/" + pdfNode.getStoreRef().getProtocol() + "/" + pdfNode.getStoreRef().getIdentifier() + "/" + pdfNode.getId() + "/content/thumbnails/webpreview?c=force";
        
        JSONObject tn = new JSONObject();
        tn.put("thumbnailName", "webpreview");
        
        sendRequest(new GetRequest(url), 200, USER_ALFRESCO);
    }
    
    this.transactionService.setAllowWrite(true);
    
    // Check getAll whilst we are here 
    Response getAllResp = sendRequest(new GetRequest(getThumbnailsURL(jpgNode)), 200);
    JSONArray getArr = new JSONArray(getAllResp.getContentAsString());
    assertNotNull(getArr);
    assertEquals(0, getArr.length());
}
 
Example 7
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 8
Source File: TestPersonManager.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void setUser(String userName)
{
    if(people.containsKey(userName))
    {
        AuthenticationUtil.setFullyAuthenticatedUser(userName);
    }
    else throw new IllegalArgumentException("Cannot set user as unregistered person: "+userName);
}
 
Example 9
Source File: RepositoryContainerTest.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.authenticationService = (MutableAuthenticationService) getServer().getApplicationContext().getBean("AuthenticationService");
    this.authenticationComponent = (AuthenticationComponent)getServer().getApplicationContext().getBean("authenticationComponent");
    this.personService = (PersonService) getServer().getApplicationContext().getBean("PersonService");

    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
    
    // Create users
    createUser(USER_ONE);
    createUser(USER_TWO);
}
 
Example 10
Source File: VirtualRatingServiceExtensionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void applyRatingAs(final NodeRef targetNode, final float rating, final String ratingSchemeName,
            String asUser) throws RatingServiceException
{

    String fau = AuthenticationUtil.getFullyAuthenticatedUser();
    try
    {
        AuthenticationUtil.setFullyAuthenticatedUser(asUser);
        RunAsWork<Void> applyRatingsAsWork = new RunAsWork<Void>()
        {

            @Override
            public Void doWork() throws Exception
            {
                ratingService.applyRating(targetNode,
                                          rating,
                                          ratingSchemeName);
                return null;
            }

        };
        AuthenticationUtil.runAs(applyRatingsAsWork,
                                 asUser);
    }
    finally
    {
        AuthenticationUtil.setFullyAuthenticatedUser(fau);
    }
}
 
Example 11
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 12
Source File: AbstractJodConverterBasedTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
* This test relies upon customised OpenOffice.org subsystems being available.
* The OOoDirect subsystem (usually enabled by default) is disabled and the
* OOoJodconverter subsystem (usually disabled by default) is enabled.
* @throws Exception
*/
  @BeforeClass
  public static void initServicesAndRestartOOoSubsystems() throws Exception
  {
  	if (log.isDebugEnabled())
  	{
  		log.debug("initServicesAndRestartOOoSubsystems");
  	}
  	
  	repositoryHelper = (Repository) ctx.getBean("repositoryHelper");
      serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
      contentService = serviceRegistry.getContentService();
      nodeService = serviceRegistry.getNodeService();
      thumbnailService = serviceRegistry.getThumbnailService();
      transactionService = serviceRegistry.getTransactionService();
      
      AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
      
      oooJodcSubsystem = (ChildApplicationContextFactory) ctx.getBean("OOoJodconverter");

  	// Stop the OOoJodconverter subsystem and restart it with test settings i.e. enabled.
  	// Also a pool of 3 JodConverter instances, just for fun.
      if (log.isDebugEnabled())
      {
      	log.debug("Enabling OOoJodconverter");
      }
oooJodcSubsystem.stop();
oooJodcSubsystem.setProperty("jodconverter.enabled", "true");
oooJodcSubsystem.setProperty("jodconverter.portNumbers", "2022, 2023, 2024");
oooJodcSubsystem.start();
  }
 
Example 13
Source File: ScriptNodeTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test(expected=AccessDeniedException.class)
public void userTwoCannotAccessTestFile() throws Exception
{
    AuthenticationUtil.setFullyAuthenticatedUser(USER_TWO_NAME);
    touchFileToTriggerPermissionCheck(USER_ONES_TEST_FILE);
    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example 14
Source File: PersonServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void addUserUsageContent(final String userName, final int stringDataLength)
{
    RetryingTransactionHelper.RetryingTransactionCallback<Void> usageCallback = new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            try
            {
                AuthenticationUtil.pushAuthentication();
                AuthenticationUtil.setFullyAuthenticatedUser(userName);
                String textData = "This is default text added. Add more: ";
                for (int i = 0; i < stringDataLength; i++)
                {
                    textData += "abc";
                }
                NodeRef homeFolder = getHomeSpaceFolderNode(userName);
                NodeRef folder = nodeService.createNode(
                        homeFolder,
                        ContentModel.ASSOC_CONTAINS,
                        QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "testFolder"),
                        ContentModel.TYPE_FOLDER).getChildRef();
                addTextContent(folder, "text1.txt", textData);
            }
            finally
            {
                AuthenticationUtil.popAuthentication();
            }
            return null;
        }
    };

    RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
    txnHelper.doInTransaction(usageCallback);
}
 
Example 15
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();
    }
}
 
Example 16
Source File: NodeArchiveServiceRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void tearDown() throws Exception
{
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    super.tearDown();

    // Tidy up any test nodes that are hanging around.
    transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
                {
                    public Void execute() throws Throwable
                    {
                        AuthenticationUtil.runAs(new RunAsWork<Void>()
                        {
                            public Void doWork() throws Exception
                            {
                                for (NodeRef nodeRef : createdNodes)
                                {
                                    if (nodeRef != null && nodeService.exists(nodeRef))
                                    {
                                        nodeService.deleteNode(nodeRef);
                                    }
                                }

                                for (StoreRef store : createdStores)
                                {
                                    if (store != null && nodeService.exists(store))
                                    {
                                        nodeService.deleteStore(store);
                                    }
                                }
                                return null;
                            }
                        }, AuthenticationUtil.getSystemUserName());

                        return null;
                    }
                });

    // Delete users
    for (String userName : this.createdPeople)
    {
        personService.deletePerson(userName);
    }
    // Clear the lists
    this.createdPeople.clear();
    this.createdNodes.clear();
    this.createdStores.clear();

    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example 17
Source File: GetChildrenCannedQueryTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testPrimaryVsSecondary() throws Exception
{
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    NodeRef userHomeRef = repositoryHelper.getCompanyHome();

    NodeRef parentNodeRef1 = createFolder(userHomeRef, "GetChildrenCannedQueryTest-PrimaryVsSecondary-"+TEST_RUN_ID, ContentModel.TYPE_FOLDER);

    PagingResults<NodeRef> results = list(parentNodeRef1, -1, -1, 0, null, null, null);
    assertEquals(0, results.getPage().size());

    List<FilterProp> filterPropsPrimary = new ArrayList<>(1);
    filterPropsPrimary.add(new FilterPropBoolean(GetChildrenCannedQuery.FILTER_QNAME_NODE_IS_PRIMARY, true));

    List<FilterProp> filterPropsSecondary = new ArrayList<>(1);
    filterPropsSecondary.add(new FilterPropBoolean(GetChildrenCannedQuery.FILTER_QNAME_NODE_IS_PRIMARY, false));

    results = list(parentNodeRef1, -1, -1, 0, null, filterPropsPrimary, null);
    assertEquals(0, results.getPage().size());

    results = list(parentNodeRef1, -1, -1, 0, null, filterPropsSecondary, null);
    assertEquals(0, results.getPage().size());

    NodeRef folder1Ref = createFolder(parentNodeRef1, FOLDER_1, ContentModel.TYPE_FOLDER);
    NodeRef folder2Ref = createFolder(parentNodeRef1, FOLDER_2, ContentModel.TYPE_FOLDER);

    results = list(parentNodeRef1, -1, -1, 0, null, null, null);
    assertEquals(2, results.getPage().size());
    assertTrue(results.getPage().contains(folder1Ref));
    assertTrue(results.getPage().contains(folder2Ref));

    results = list(parentNodeRef1, -1, -1, 0, null, filterPropsPrimary, null);
    assertEquals(2, results.getPage().size());
    assertTrue(results.getPage().contains(folder1Ref));
    assertTrue(results.getPage().contains(folder2Ref));

    results = list(parentNodeRef1, -1, -1, 0, null, filterPropsSecondary, null);
    assertEquals(0, results.getPage().size());

    NodeRef parentNodeRef2 = getOrCreateParentTestFolder("GetChildrenCannedQueryTest-2-"+TEST_RUN_ID);

    NodeRef folder3Ref = createFolder(parentNodeRef2, FOLDER_3, ContentModel.TYPE_FOLDER);

    nodeService.addChild(parentNodeRef1, folder3Ref, ContentModel.ASSOC_CONTAINS, QName.createQName("cm:2nd"));

    results = list(parentNodeRef1, -1, -1, 0, null, null, null);
    assertEquals(3, results.getPage().size());
    assertTrue(results.getPage().contains(folder1Ref));
    assertTrue(results.getPage().contains(folder2Ref));
    assertTrue(results.getPage().contains(folder3Ref));

    results = list(parentNodeRef1, -1, -1, 0, null, filterPropsPrimary, null);
    assertEquals(2, results.getPage().size());
    assertTrue(results.getPage().contains(folder1Ref));
    assertTrue(results.getPage().contains(folder2Ref));

    results = list(parentNodeRef1, -1, -1, 0, null, filterPropsSecondary, null);
    assertEquals(1, results.getPage().size());
    assertTrue(results.getPage().contains(folder3Ref));
}
 
Example 18
Source File: RemoteCredentialsServicesTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Tests that read only methods don't create the shared credentials
 *  container, but that write ones will do.
 */
@Test public void testSharedCredentialsContainer() throws Exception
{
    // Run as a test user
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);
    
    
    // To start with, the container shouldn't be there
    NodeRef container = ((RemoteCredentialsServiceImpl)PRIVATE_REMOTE_CREDENTIALS_SERVICE).getSharedContainerNodeRef(false);
    if (container != null)
    {
        // Tidy up
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
        
        // Zap the container
        PUBLIC_NODE_SERVICE.deleteNode(container);
    }
    
    
    // Run as a test user
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);
    
    // Ask for the list of shared remote systems
    REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));
    
    // Won't have been created by a read
    container = ((RemoteCredentialsServiceImpl)PRIVATE_REMOTE_CREDENTIALS_SERVICE).getSharedContainerNodeRef(false);
    assertEquals(null, container);
    
    
    // Try to store some credentials
    PasswordCredentialsInfo credentials = new PasswordCredentialsInfoImpl();
    REMOTE_CREDENTIALS_SERVICE.createSharedCredentials(TEST_REMOTE_SYSTEM_ONE, credentials);
    
    // It will now exist
    container = ((RemoteCredentialsServiceImpl)PRIVATE_REMOTE_CREDENTIALS_SERVICE).getSharedContainerNodeRef(false);
    assertNotNull(container);
    
    // Should have a marker aspect, and the specified name
    Set<QName> cAspects = PUBLIC_NODE_SERVICE.getAspects(container);
    assertEquals("Aspect missing, found " + cAspects, true, 
            cAspects.contains(RemoteCredentialsModel.ASPECT_REMOTE_CREDENTIALS_SYSTEM_CONTAINER));
    assertEquals(SHARED_SYSTEM_CONTAINER_NAME, PUBLIC_NODE_SERVICE.getProperty(container, ContentModel.PROP_NAME));
    
    // Should have single node in it
    assertEquals(1, PUBLIC_NODE_SERVICE.getChildAssocs(container).size());
    
    
    // Tidy up
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    
    // Zap the container
    PUBLIC_NODE_SERVICE.deleteNode(container);
}
 
Example 19
Source File: GroupsTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test Tree for all group tests
 *
 * TEST_ROOTGROUP
 *	GROUPA
 *	GROUPB
 *		GROUPD
 *		GROUPE (in Share Zone)
 *		USER_TWO
 *		USER_THREE
 *	GROUPC
 *		USER_TWO
 *	GROUPF
 *		GROUPD
 *	GROUPG
 *		GROUPD
 */	
private synchronized String createTestTree()
{
	if(rootGroupName == null)
	{
		rootGroupName = authorityService.getName(AuthorityType.GROUP, TEST_ROOTGROUP);
	}
	
    Set<String> shareZones = new HashSet<String>(1, 1.0f);
    shareZones.add(AuthorityService.ZONE_APP_SHARE);
	
    if(!authorityService.authorityExists(rootGroupName))
    {
        AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    	 
    	rootGroupName = authorityService.createAuthority(AuthorityType.GROUP, TEST_ROOTGROUP, TEST_ROOTGROUP_DISPLAY_NAME, authorityService.getDefaultZones());
    	String groupA = authorityService.createAuthority(AuthorityType.GROUP, TEST_GROUPA, TEST_GROUPA, authorityService.getDefaultZones());
    	authorityService.addAuthority(rootGroupName, groupA);
    	String groupB = authorityService.createAuthority(AuthorityType.GROUP, TEST_GROUPB, TEST_GROUPB,authorityService.getDefaultZones());
        authorityService.addAuthority(rootGroupName, groupB);
    	String groupD = authorityService.createAuthority(AuthorityType.GROUP, TEST_GROUPD, TEST_GROUPD, authorityService.getDefaultZones());
     	String groupE = authorityService.createAuthority(AuthorityType.GROUP, TEST_GROUPE, TEST_GROUPE, shareZones);
        authorityService.addAuthority(groupB, groupD);
        authorityService.addAuthority(groupB, groupE);
    	authorityService.addAuthority(groupB, USER_TWO);
    	authorityService.addAuthority(groupB, USER_THREE);
        String groupF = authorityService.createAuthority(AuthorityType.GROUP, TEST_GROUPF, TEST_GROUPF, authorityService.getDefaultZones());
        authorityService.addAuthority(rootGroupName, groupF);
        authorityService.addAuthority(groupF, groupD);
        String groupG = authorityService.createAuthority(AuthorityType.GROUP, TEST_GROUPG, TEST_GROUPG, authorityService.getDefaultZones());
        authorityService.addAuthority(rootGroupName, groupG);
        authorityService.addAuthority(groupG, groupD);
        
    	String groupC = authorityService.createAuthority(AuthorityType.GROUP, TEST_GROUPC, TEST_GROUPC,authorityService.getDefaultZones());
    	authorityService.addAuthority(rootGroupName, groupC);
    	authorityService.addAuthority(groupC, USER_TWO);
    
    	String link = authorityService.createAuthority(AuthorityType.GROUP, TEST_LINK, TEST_LINK, authorityService.getDefaultZones());
    	authorityService.addAuthority(rootGroupName, link);
    	
        this.authenticationComponent.setCurrentUser(USER_ONE);
    }
    
    return rootGroupName;

}
 
Example 20
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();
    }
}