Java Code Examples for org.alfresco.repo.tenant.TenantUtil#runAsUserTenant()

The following examples show how to use org.alfresco.repo.tenant.TenantUtil#runAsUserTenant() . 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: WebDAVMethodTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void checkLockedNodeTenantTest()
{
    setUpApplicationContext();

    // Create a tenant domain
    TenantUtil.runAsSystemTenant(new TenantUtil.TenantRunAsWork<Object>() {
        public Object doWork() throws Exception {
            if (!tenantAdminService.existsTenant(TEST_TENANT_DOMAIN))
            {
                tenantAdminService.createTenant(TEST_TENANT_DOMAIN, (DEFAULT_ADMIN_PW + " " + TEST_TENANT_DOMAIN).toCharArray(), null);
            }
            return null;
        }
    }, TenantService.DEFAULT_DOMAIN);
    
    TenantUtil.runAsUserTenant(new TenantUtil.TenantRunAsWork<Object>()
    {
        @Override
        public Object doWork() throws Exception
        {
            checkLockedNodeTestTenantWork();
            return null;
        }
    }, AuthenticationUtil.getAdminUserName(), TEST_TENANT_DOMAIN);
}
 
Example 2
Source File: TestCMIS.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private TestSite getTestSite() throws Exception
{
    if (testSite == null)
    {
        getTestNetwork();
        getTestPersonId();

        String siteName = "site" + System.currentTimeMillis();
        testSite = TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>()
        {
            @Override
            public TestSite doWork() throws Exception
            {
                SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PUBLIC);
                return testNetwork.createSite(siteInfo);
            }
        }, testPersonId, testNetwork.getId());
    }
    return testSite;
}
 
Example 3
Source File: RepoService.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public Map<String, TestSite> getSitesForUser(String username)
{
	if(username == null)
	{
		username = AuthenticationUtil.getAdminUserName();
	}
	List<SiteInfo> sites = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<SiteInfo>>()
	{
		@Override
		public List<SiteInfo> doWork() throws Exception
		{
			List<SiteInfo> results = siteService.listSites(null, null);
			return results;
		}
	}, username, getId());
	TreeMap<String, TestSite> ret = new TreeMap<String, TestSite>();
	for(SiteInfo siteInfo : sites)
	{
		TestSite site = new TestSite(TestNetwork.this, siteInfo/*, null*/);
		ret.put(site.getSiteId(), site);
	}
	return ret;
}
 
Example 4
Source File: EnterpriseWorkflowTestApi.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected NodeRef[] createTestDocuments(final RequestContext requestContext) {
    NodeRef[] docNodeRefs = TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef[]>()
    {
        @Override
        public NodeRef[] doWork() throws Exception
        {
            String siteName = "site" + GUID.generate();
            SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PUBLIC);
            TestSite site = currentNetwork.createSite(siteInfo);
            NodeRef nodeRefDoc1 = getTestFixture().getRepoService().createDocument(site.getContainerNodeRef("documentLibrary"), "Test Doc1", "Test Doc1 Title", "Test Doc1 Description", "Test Content");
            NodeRef nodeRefDoc2 = getTestFixture().getRepoService().createDocument(site.getContainerNodeRef("documentLibrary"), "Test Doc2", "Test Doc2 Title", "Test Doc2 Description", "Test Content");
            
            NodeRef[] result = new NodeRef[2];
            result[0] = nodeRefDoc1;
            result[1] = nodeRefDoc2;
            
            return result;
        }
    }, requestContext.getRunAsUser(), requestContext.getNetworkId());
    
    return docNodeRefs;
}
 
Example 5
Source File: TestDownloads.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void assertValidZipNodeid(Download download)
{
    try{
        TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
        {

            @Override
            public Void doWork() throws Exception
            {
                nodesApi.validateNode(download.getId());
                return null;
            }
        }, user1, networkOne.getId());
        
    }catch(ApiException ex){
        org.junit.Assert.fail("The download nodeid is not valid." + ex.getMessage());
    }
}
 
Example 6
Source File: EnterpriseWorkflowTestApi.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Start a review pooled process through the public REST-API.
 */
@SuppressWarnings("unchecked")
protected ProcessInfo startReviewPooledProcess(final RequestContext requestContext) throws PublicApiException {
    org.activiti.engine.repository.ProcessDefinition processDefinition = activitiProcessEngine
            .getRepositoryService()
            .createProcessDefinitionQuery()
            .processDefinitionKey("@" + requestContext.getNetworkId() + "@activitiReviewPooled")
            .singleResult();

    ProcessesClient processesClient = publicApiClient.processesClient();
    
    final JSONObject createProcessObject = new JSONObject();
    createProcessObject.put("processDefinitionId", processDefinition.getId());
    
    final JSONObject variablesObject = new JSONObject();
    variablesObject.put("bpm_priority", 1);
    variablesObject.put("bpm_workflowDueDate", ISO8601DateFormat.format(new Date()));
    variablesObject.put("wf_notifyMe", Boolean.FALSE);
    
    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            List<MemberOfSite> memberships = getTestFixture().getNetwork(requestContext.getNetworkId()).getSiteMemberships(requestContext.getRunAsUser());
            assertTrue(memberships.size() > 0);
            MemberOfSite memberOfSite = memberships.get(0);
            String group = "GROUP_site_" + memberOfSite.getSiteId() + "_" + memberOfSite.getRole().name();
            variablesObject.put("bpm_groupAssignee", group);
            return null;
        }
    }, requestContext.getRunAsUser(), requestContext.getNetworkId());
    
    createProcessObject.put("variables", variablesObject);
    
    return processesClient.createProcess(createProcessObject.toJSONString());
}
 
Example 7
Source File: ProcessWorkflowApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void completeAdhocTasks(String instanceId, RequestContext requestContext) 
{
    final Task task = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(instanceId).singleResult();
    assertEquals(requestContext.getRunAsUser(), task.getAssignee());
    
    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            activitiProcessEngine.getTaskService().complete(task.getId());
            return null;
        }
    }, requestContext.getRunAsUser(), requestContext.getNetworkId());
    
    final Task task2 = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(instanceId).singleResult();
    assertEquals(requestContext.getRunAsUser(), task2.getAssignee());
    
    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            activitiProcessEngine.getTaskService().complete(task2.getId());
            return null;
        }
    }, requestContext.getRunAsUser(), requestContext.getNetworkId());
    
    assertEquals(0, activitiProcessEngine.getRuntimeService().createProcessInstanceQuery().processInstanceId(instanceId).count());
    cleanupProcessInstance(instanceId);
}
 
Example 8
Source File: TestFavourites.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * REPO-1147 Tests create and get favourite with 'include' parameter and properties.
 *
 * <p>POST:</p>
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/people/<userName>/favorites?include=properties}
 *
 * <p>GET:</p>
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/people/<userName>/favorites/<targetId>?include=properties}
 */
@Test
public void testCreateAndGetFavouriteWithIncludeProperties() throws Exception
{
    setRequestContext(network1.getId(), person11Id, "password");
    final NodeRef nodeRef1= person1PublicDocs.get(0); // a file in the site's document library (Test Doc1)

    // Favourite the doc (Test Doc1) using POST
    Favourite file1Favourite = makeFileFavourite(nodeRef1.getId());
    Favourite file1FavouriteResponse = favouritesProxy.createFavourite(person11Id, file1Favourite, null);
    assertNull("Properties should be null because they wasn't requested via include=properties", file1FavouriteResponse.getProperties());
    // Same results for GET
    file1FavouriteResponse = favouritesProxy.getFavourite(person11Id, file1FavouriteResponse.getTargetGuid(), null);
    assertNull("Properties should be null because they wasn't requested via include=properties", file1FavouriteResponse.getProperties());

    // create Favourite with include=properties in the result using POST
    Map<String, String> include = Collections.singletonMap("include", "properties");
    file1FavouriteResponse = favouritesProxy.createFavourite(person11Id, file1Favourite, include);
    assertNull("Properties should be null because all of the properties are already in the favourite target and will not be listed twice!", file1FavouriteResponse.getProperties());
    // Same results for GET
    file1FavouriteResponse = favouritesProxy.getFavourite(person11Id, file1FavouriteResponse.getTargetGuid(), include);
    assertNull("Properties should be null because all of the properties are already in the favourite target and will not be listed twice!", file1FavouriteResponse.getProperties());

    // Lock node for creating lock properties
    TenantUtil.runAsUserTenant((TenantRunAsWork<Void>) () -> {
        repoService.lockNode(nodeRef1);
        return null;
    }, person11Id, network1.getId());

    // create Favourite with include=properties in the result using POST
    file1FavouriteResponse = favouritesProxy.createFavourite(person11Id, file1Favourite, include);
    assertNotNull("Properties shouldn't be null because we created some properties while locking the file", file1FavouriteResponse.getProperties());
    // Same results for GET
    file1FavouriteResponse = favouritesProxy.getFavourite(person11Id, file1FavouriteResponse.getTargetGuid(), include);
    assertNotNull("Properties shouldn't be null because we created some properties while locking the file", file1FavouriteResponse.getProperties());
}
 
Example 9
Source File: TestNodeComments.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testNodeCommentsAndLockingIncludingChildren() throws Exception
{
	Comments commentsProxy = publicApiClient.comments();

	// TODO push-down to future CommentServiceImplTest (see ACE-5437) - since includeChildren is via LockService api only

	try
	{
		publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));

		Comment comment = new Comment();
		comment.setContent("my comment");
		Comment createdComment = commentsProxy.createNodeComment(nodeRef5.getId(), comment);

		// recursive lock (folderRef1, nodeRef5)
		TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
		{
			@Override
			public Void doWork() throws Exception
			{
				repoService.lockNode(folderNodeRef1, LockType.WRITE_LOCK, 0, true);
				return null;
			}
		}, person11.getId(), network1.getId());

	}
	finally
	{
		TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>()
		{
			@Override
			public Void doWork() throws Exception
			{
				repoService.unlockNode(folderNodeRef1, true);
				return null;
			}
		}, network1.getId());
	}
}
 
Example 10
Source File: EnterpriseWorkflowTestApi.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Start a review pooled process through the public REST-API.
 */
@SuppressWarnings("unchecked")
protected ProcessInfo startParallelReviewProcess(final RequestContext requestContext) throws PublicApiException {
    org.activiti.engine.repository.ProcessDefinition processDefinition = activitiProcessEngine
            .getRepositoryService()
            .createProcessDefinitionQuery()
            .processDefinitionKey("@" + requestContext.getNetworkId() + "@activitiParallelReview")
            .singleResult();

    ProcessesClient processesClient = publicApiClient.processesClient();
    
    final JSONObject createProcessObject = new JSONObject();
    createProcessObject.put("processDefinitionId", processDefinition.getId());
    
    final JSONObject variablesObject = new JSONObject();
    variablesObject.put("bpm_priority", 1);
    variablesObject.put("wf_notifyMe", Boolean.FALSE);
    
    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            JSONArray assigneeArray = new JSONArray();
            assigneeArray.add(requestContext.getRunAsUser());
            TestPerson otherPerson = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId());
            assigneeArray.add(otherPerson.getId());
            variablesObject.put("bpm_assignees", assigneeArray);
            return null;
        }
    }, requestContext.getRunAsUser(), requestContext.getNetworkId());
    
    createProcessObject.put("variables", variablesObject);
    
    return processesClient.createProcess(createProcessObject.toJSONString());
}
 
Example 11
Source File: TestActivities.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testPUBLICAPI23() throws Exception
{
	// Add and then remove personId as a member of the public site
	TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
	{
		@Override
		public Void doWork() throws Exception
		{
			testSite.updateMember(person2.getId(), SiteRole.SiteConsumer);
			testSite.removeMember(person2.getId());

			return null;
		}
	}, person1.getId(), network1.getId());

	// make sure activities have been generated
	repoService.generateFeed();	

	// check that (empty) role is not in the response

	People peopleProxy = publicApiClient.people();
	
	{
		publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));

		int skipCount = 0;
		int maxItems = 10;
		Paging paging = getPaging(skipCount, maxItems);
		ListResponse<Activity> activities = peopleProxy.getActivities(person2.getId(), createParams(paging, null));
		for(Activity activity : activities.getList())
		{
			String activityType = activity.getActivityType();
			if(activityType.equals("org.alfresco.site.user-left"))
			{
				String role = (String)activity.getSummary().get("role");
				String feedPersonId = activity.getFeedPersonId();
				if(feedPersonId.equals(person2.getId()))
				{
					assertTrue(role == null);
					break;
				}
			}
		}
	}
}
 
Example 12
Source File: ProcessWorkflowApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testGetProcessInstanceById() throws Exception
{
    final RequestContext requestContext = initApiClientWithTestUser();
    ProcessesClient processesClient = publicApiClient.processesClient();
    
    final ProcessInfo process = startAdhocProcess(requestContext, null);
    try 
    {
        ProcessInfo processInfo = processesClient.findProcessById(process.getId());
        assertNotNull(processInfo);
        
        final Map<String, Object> variables = activitiProcessEngine.getRuntimeService().getVariables(processInfo.getId());
        assertEquals(1, variables.get("bpm_priority"));

        HistoricProcessInstance processInstance = activitiProcessEngine.getHistoryService().createHistoricProcessInstanceQuery()
                .processInstanceId(processInfo.getId()).singleResult();
        
        assertNotNull(processInfo.getId());
        assertEquals(processInstance.getId(), processInfo.getId());
        assertNotNull(processInfo.getStartActivityId());
        assertEquals(processInstance.getStartActivityId(), processInfo.getStartActivityId());
        assertNotNull(processInfo.getStartUserId());
        assertEquals(processInstance.getStartUserId(), processInfo.getStartUserId());
        assertNotNull(processInfo.getStartedAt());
        assertEquals(processInstance.getStartTime(), processInfo.getStartedAt());
        assertNotNull(processInfo.getProcessDefinitionId());
        assertEquals(processInstance.getProcessDefinitionId(), processInfo.getProcessDefinitionId());
        assertNotNull(processInfo.getProcessDefinitionKey());
        assertEquals("activitiAdhoc", processInfo.getProcessDefinitionKey());
        assertNull(processInfo.getBusinessKey());
        assertNull(processInfo.getDeleteReason());
        assertNull(processInfo.getDurationInMs());
        assertNull(processInfo.getEndActivityId());
        assertNull(processInfo.getEndedAt());
        assertNull(processInfo.getSuperProcessInstanceId());
        assertFalse(processInfo.isCompleted());
        
        TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
        {
            @Override
            public Void doWork() throws Exception
            {
                // now complete the process and see if ending info is available in the REST response
                Task task = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(process.getId()).singleResult();
                activitiProcessEngine.getTaskService().complete(task.getId());
                task = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(process.getId()).singleResult();
                activitiProcessEngine.getTaskService().complete(task.getId());
                return null;
            }
        }, requestContext.getRunAsUser(), requestContext.getNetworkId());
        
        processInstance = activitiProcessEngine.getHistoryService().createHistoricProcessInstanceQuery()
                .processInstanceId(processInfo.getId()).singleResult();
        
        processInfo = processesClient.findProcessById(processInfo.getId());
        
        assertNotNull(processInfo.getId());
        assertEquals(processInstance.getId(), processInfo.getId());
        assertNotNull(processInfo.getStartActivityId());
        assertEquals(processInstance.getStartActivityId(), processInfo.getStartActivityId());
        assertNotNull(processInfo.getStartUserId());
        assertEquals(processInstance.getStartUserId(), processInfo.getStartUserId());
        assertNotNull(processInfo.getStartedAt());
        assertEquals(processInstance.getStartTime(), processInfo.getStartedAt());
        assertNotNull(processInfo.getProcessDefinitionId());
        assertEquals(processInstance.getProcessDefinitionId(), processInfo.getProcessDefinitionId());
        assertNotNull(processInfo.getProcessDefinitionKey());
        assertEquals("activitiAdhoc", processInfo.getProcessDefinitionKey());
        assertNull(processInfo.getBusinessKey());
        assertNull(processInfo.getDeleteReason());
        assertNotNull(processInfo.getDurationInMs());
        assertEquals(processInstance.getDurationInMillis(), processInfo.getDurationInMs());
        assertNotNull(processInfo.getEndActivityId());
        assertEquals(processInstance.getEndActivityId(), processInfo.getEndActivityId());
        assertNotNull(processInfo.getEndedAt());
        assertEquals(processInstance.getEndTime(), processInfo.getEndedAt());
        assertNull(processInfo.getSuperProcessInstanceId());
        assertTrue(processInfo.isCompleted());
    }
    finally
    {
        cleanupProcessInstance(process.getId());
    }
}
 
Example 13
Source File: TestPersonSites.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void initializePersonAndNetwork4WithSites() throws Exception
{
    if (network4 == null)
    {
        network4 = getRepoService().createNetwork(this.getClass().getSimpleName().toLowerCase() + "-3-" + GUID.generate(), true);
        network4.create();

        // Create some users
        TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>()
        {
            @Override
            public Void doWork() throws Exception
            {
                person41 = network4.createUser();
                person42 = network4.createUser();
                return null;
            }
        }, network4.getId());

        // ...and some sites
        TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
        {
            @Override
            public Void doWork() throws Exception
            {
                site41 = network4.createSite("A", SiteVisibility.PRIVATE);
                site41.inviteToSite(person41.getId(), SiteRole.SiteContributor);

                site42 = network4.createSite("B", SiteVisibility.PUBLIC);
                site42.inviteToSite(person41.getId(), SiteRole.SiteContributor);

                site43 = network4.createSite("C", SiteVisibility.PUBLIC);
                site43.inviteToSite(person41.getId(), SiteRole.SiteContributor);

                site44 = network4.createSite("D", SiteVisibility.MODERATED);
                site44.inviteToSite(person41.getId(), SiteRole.SiteContributor);
                return null;
            }
        }, person42.getId(), network4.getId());
    }
}
 
Example 14
Source File: TestCMIS.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * <p>Related to REPO-4613.</p>
 * <p>A checkout should not lock the private working copy.</p>
 * <p>Adding aspects or properties to a pwc should remain possible after a checkout.</p>
 * @throws Exception
 */
@Test
public void aPrivateCopyShouldAllowTheAdditionOfAspects_CMIS_1_1_Version() throws Exception
{
    final String aspectName = "P:cm:summarizable";
    final String propertyName = "cm:summary";
    final String propertyValue = "My summary";

    final TestNetwork network1 = getTestFixture().getRandomNetwork();

    String username = "user" + System.currentTimeMillis();
    PersonInfo personInfo = new PersonInfo(username, username, username, TEST_PASSWORD, null, null, null, null, null, null, null);
    TestPerson person1 = network1.createUser(personInfo);
    String person1Id = person1.getId();

    final String siteName = "site" + System.currentTimeMillis();

    TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef>()
    {
        @Override
        public NodeRef doWork() throws Exception
        {
            SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PRIVATE);
            TestSite site = repoService.createSite(null, siteInfo);

            String name = GUID.generate();
            NodeRef folderNodeRef = repoService.createFolder(site.getContainerNodeRef(DOCUMENT_LIBRARY_CONTAINER_NAME), name);
            return folderNodeRef;
        }
    }, person1Id, network1.getId());

    // Create a document...
    publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));

    CmisSession cmisSession = publicApiClient.createPublicApiCMISSession(Binding.atom, CMIS_VERSION_11);
    Folder folder = (Folder) cmisSession.getObjectByPath(String.format(DOCUMENT_LIBRARY_PATH_PATTERN, siteName));
    String fileName = String.format(TEST_DOCUMENT_NAME_PATTERN, GUID.generate());

    // Create a document...
    publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));

    HashMap<String, Object> props = new HashMap<>();
    props.put(PropertyIds.OBJECT_TYPE_ID, TYPE_CMIS_DOCUMENT);
    props.put(PropertyIds.NAME, fileName);

    final ContentStream cs = new ContentStreamImpl(fileName, "text/plain",
            "This is just a test");

    final Document document = folder.createDocument(props, cs, VersioningState.MAJOR);

    ObjectId pwcObjectId = document.checkOut();

    CmisObject cmisObject = cmisSession.getObject(pwcObjectId.getId());
    final Document pwc = (Document) cmisObject;

    List<Object> aspects = pwc.getProperty(PropertyIds.SECONDARY_OBJECT_TYPE_IDS).getValues();

    // asserts that we have the right aspect for the private working copy
    assertTrue(aspects.contains("P:cm:workingcopy"));

    aspects.add(aspectName);

    props = new HashMap<>();
    props.put(PropertyIds.SECONDARY_OBJECT_TYPE_IDS, aspects);
    props.put(propertyName, propertyValue);


    pwc.updateProperties(props);

    final ObjectId id = pwc.checkIn(true, null, null, "CheckIn comment");
    Document checkedInDocument = (Document) cmisSession.getObject(id.getId());

    List<String> secondaryTypeIds = checkedInDocument.getPropertyValue(PropertyIds.SECONDARY_OBJECT_TYPE_IDS);

    // asserts the new aspect has been added to the original copy, via the check in from the private copy
    assertTrue(secondaryTypeIds.contains(aspectName));
    assertEquals(checkedInDocument.getPropertyValue(propertyName),  propertyValue);
}
 
Example 15
Source File: TestCMIS.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
  public void testALF19320() throws Exception
  {
      final TestNetwork network1 = getTestFixture().getRandomNetwork();

      String username = "user" + System.currentTimeMillis();
PersonInfo personInfo = new PersonInfo(username, username, username, TEST_PASSWORD, null, null, null, null, null, null, null);
      TestPerson person1 = network1.createUser(personInfo);
      String person1Id = person1.getId();

      final String siteName = "site" + System.currentTimeMillis();

      TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef>()
      {
          @Override
          public NodeRef doWork() throws Exception
          {
              SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PRIVATE);
              TestSite site = repoService.createSite(null, siteInfo);

              String name = GUID.generate();
		NodeRef folderNodeRef = repoService.createFolder(site.getContainerNodeRef(DOCUMENT_LIBRARY_CONTAINER_NAME), name);
              return folderNodeRef;
          }
      }, person1Id, network1.getId());

      // Create a document...
      publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));
CmisSession cmisSession = publicApiClient.createPublicApiCMISSession(Binding.atom, CMIS_VERSION_10, AlfrescoObjectFactoryImpl.class.getName());
      AlfrescoFolder docLibrary = (AlfrescoFolder)cmisSession.getObjectByPath("/Sites/" + siteName + "/documentLibrary");
      Map<String, String> properties = new HashMap<String, String>();
      {
          // create a document with 2 aspects
          properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document,P:cm:titled,P:cm:author");
          properties.put(PropertyIds.NAME, "mydoc-" + GUID.generate() + ".txt");
      }
      ContentStreamImpl fileContent = new ContentStreamImpl();
      {
          ContentWriter writer = new FileContentWriter(TempFileProvider.createTempFile(GUID.generate(), ".txt"));
          writer.putContent("Ipsum and so on");
          ContentReader reader = writer.getReader();
          fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
          fileContent.setStream(reader.getContentInputStream());
      }
      
      AlfrescoDocument doc = (AlfrescoDocument)docLibrary.createDocument(properties, fileContent, VersioningState.MAJOR);
      String versionLabel = doc.getVersionLabel();
assertEquals(CMIS_VERSION_10, versionLabel);

      AlfrescoDocument doc1 = (AlfrescoDocument)doc.getObjectOfLatestVersion(false);
      String versionLabel1 = doc1.getVersionLabel();
assertEquals(CMIS_VERSION_10, versionLabel1);
  }
 
Example 16
Source File: TestCMIS.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 1) Creating a file with currency symbols in the name, title and description (MNT-15044)
 * 2) Get the document with correct chars in the properties.
 * @throws Exception
 */
@Test
public void testGetXmlWithCorrectCurrencySymbols() throws Exception
{
    final TestNetwork network1 = getTestFixture().getRandomNetwork();

    String username = "user" + System.currentTimeMillis();
    PersonInfo personInfo = new PersonInfo(username, username, username, "password", null, null, null, null, null, null, null);
    TestPerson person1 = network1.createUser(personInfo);
    String person1Id = person1.getId();

    final String siteName = "site" + System.currentTimeMillis();

    NodeRef fileNode = TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef>()
            {
        @Override
        public NodeRef doWork() throws Exception
        {
            SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PUBLIC);
            final TestSite site = network1.createSite(siteInfo);

            NodeRef resNode = repoService.createDocument(site.getContainerNodeRef("documentLibrary"), 
                                                         "Euro \u20AC Pound \u00A3 Franc \u20A3.txt", 
                                                         "Euro \u20AC Pound \u00A3 Franc \u20A3 File", 
                                                         "\u20A3 \u00A3 \u20A3", 
                                                         "\u20A3 \u00A3 \u20A3");
            return resNode;
        }
            }, person1Id, network1.getId());

    publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));
    CmisSession atomCmisSession10 = publicApiClient.createPublicApiCMISSession(Binding.atom, CMIS_VERSION_10, AlfrescoObjectFactoryImpl.class.getName());

    String objectId = fileNode.getId();
    Document doc = (Document)atomCmisSession10.getObject(objectId);

    String name = (String)doc.getProperty(PropertyIds.NAME).getFirstValue();
    String title = (String)doc.getProperty("cm:title").getFirstValue();
    String description = (String)doc.getProperty("cm:description").getFirstValue();

    assertEquals("Euro \u20AC Pound \u00A3 Franc \u20A3.txt", name);
    assertEquals("Euro \u20AC Pound \u00A3 Franc \u20A3 File", title);
    assertEquals("\u20A3 \u00A3 \u20A3", description);
}
 
Example 17
Source File: TestCMIS.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testPublicApi110() throws Exception
{
    Iterator<TestNetwork> networksIt = getTestFixture().networksIterator();
    final TestNetwork network1 = networksIt.next();
    Iterator<String> personIt = network1.getPersonIds().iterator();
    final String person1Id = personIt.next();
    final String person2Id = personIt.next();

    final List<NodeRef> nodes = new ArrayList<NodeRef>(5);
    
    // Create some favourite targets, sites, files and folders
    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            String siteName1 = "site" + GUID.generate();
            SiteInformation siteInfo1 = new SiteInformation(siteName1, siteName1, siteName1, SiteVisibility.PUBLIC);
            TestSite site1 = network1.createSite(siteInfo1);
            
            String siteName2 = "site" + GUID.generate();
            SiteInformation siteInfo2 = new SiteInformation(siteName2, siteName2, siteName2, SiteVisibility.PRIVATE);
            TestSite site2 = network1.createSite(siteInfo2);

NodeRef nodeRef1 = repoService.createDocument(site1.getContainerNodeRef(DOCUMENT_LIBRARY_CONTAINER_NAME), "Test Doc1", "Test Doc1 Title", "Test Doc1 Description", "Test Content");
            nodes.add(nodeRef1);
NodeRef nodeRef2 = repoService.createDocument(site1.getContainerNodeRef(DOCUMENT_LIBRARY_CONTAINER_NAME), "Test Doc2", "Test Doc2 Title", "Test Doc2 Description", "Test Content");
            nodes.add(nodeRef2);
NodeRef nodeRef3 = repoService.createDocument(site2.getContainerNodeRef(DOCUMENT_LIBRARY_CONTAINER_NAME), "Test Doc2", "Test Doc2 Title", "Test Doc2 Description", "Test Content");
            nodes.add(nodeRef3);
            repoService.createAssociation(nodeRef2, nodeRef1, ASSOC_ORIGINAL);
            repoService.createAssociation(nodeRef3, nodeRef1, ASSOC_ORIGINAL);

            site1.inviteToSite(person2Id, SiteRole.SiteCollaborator);

            return null;
        }
    }, person1Id, network1.getId());

    {
        OperationContext cmisOperationCtxOverride = new OperationContextImpl();
        cmisOperationCtxOverride.setIncludeRelationships(IncludeRelationships.BOTH);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2Id, cmisOperationCtxOverride));
		CmisSession cmisSession = publicApiClient.createPublicApiCMISSession(Binding.atom, CMIS_VERSION_10, AlfrescoObjectFactoryImpl.class.getName());

        CmisObject o1 = cmisSession.getObject(nodes.get(0).getId());
        List<Relationship> relationships = o1.getRelationships();
        assertEquals(1, relationships.size());
        Relationship r = relationships.get(0);
        CmisObject source = r.getSource();
        CmisObject target = r.getTarget();
        String sourceVersionSeriesId = (String)source.getProperty(PropertyIds.VERSION_SERIES_ID).getFirstValue();
        String targetVersionSeriesId = (String)target.getProperty(PropertyIds.VERSION_SERIES_ID).getFirstValue();
        assertEquals(nodes.get(1).getId(), sourceVersionSeriesId);
        assertEquals(nodes.get(0).getId(), targetVersionSeriesId);
    }
}
 
Example 18
Source File: TestCMIS.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
private String getTestFileIdWithTwoRenditionsOneSourceAndTwoTargetAssociations() throws Exception
{
    if (testFileIdWithTwoRenditions == null)
    {
        getTestNetwork();
        getTestPersonId();
        getTestSite();

        NodeRef fileNode = TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef>()
        {
            @Override
            public NodeRef doWork() throws Exception
            {
                NodeRef documentLibrary = testSite.getContainerNodeRef("documentLibrary");
                NodeRef folder = repoService.createFolder(documentLibrary, "myFoder");
                NodeRef testFile1 = repoService.createDocument(folder,
                    "testdoc1.txt", "Test title 1", "Test description 1", "Test content 2");

                makeRenditionNode(testFile1,    "pdf",       "pdf", "application/pdf");
                makeRenditionNode(testFile1, "doclib", "thumbnail", "image/png");

                // Make three more files and associate one as the source of testFile1 and the others as a copy of it.
                NodeRef testFile0 = repoService.createDocument(folder,
                    "testdoc0.txt", "Test title 0", "Test description 0", "Test content 0");
                NodeRef testFile2 = repoService.createDocument(folder,
                    "testdoc2.txt", "Test title 2", "Test description 2", "Test content 2");
                NodeRef testFile3 = repoService.createDocument(folder,
                    "testdoc3.txt", "Test title 3", "Test description 3", "Test content 3");
                nodeService.addAspect(testFile1, ContentModel.ASPECT_COPIEDFROM, null);
                nodeService.addAspect(testFile2, ContentModel.ASPECT_COPIEDFROM, null);
                nodeService.addAspect(testFile3, ContentModel.ASPECT_COPIEDFROM, null);
                nodeService.createAssociation(testFile1, testFile0, ASSOC_ORIGINAL);
                nodeService.createAssociation(testFile2, testFile1, ASSOC_ORIGINAL);
                nodeService.createAssociation(testFile3, testFile1, ASSOC_ORIGINAL);

                return testFile1;
            }
        }, testPersonId, testNetwork.getId());
        testFileIdWithTwoRenditions = fileNode.getId();
    }
    return testFileIdWithTwoRenditions;
}
 
Example 19
Source File: TestPersonSites.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testSitesWithSameTitles() throws Exception
{
    // Creates 3 sites
    initializeSites();

    final String site4_name = "d_" + GUID.generate();
    final String site4_title = site3_title; // Same title as site3
    final SiteRole site4_role = SiteRole.SiteCollaborator;

    TestSite site4 = TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>()
    {
        @Override
        public TestSite doWork() throws Exception
        {
            SiteInformation siteInfo = new SiteInformation(site4_name, site4_title, site4_title, SiteVisibility.PRIVATE);
            TestSite site = network1.createSite(siteInfo);
            site.inviteToSite(person32.getId(), site4_role);
            return site;
        }
    }, person31.getId(), network1.getId());
    assertNotNull(site4);

    // paging
    int totalResults = 4;
    Paging paging = getPaging(null, null, totalResults, totalResults);

    // get memberships
    ListResponse<MemberOfSite> resp = getSiteMembershipsForPerson32(null, null, false);

    // check results
    List<MemberOfSite> expectedList = new LinkedList<>();
    expectedList.add(new MemberOfSite(site2, site2_role));
    expectedList.add(new MemberOfSite(site3, site3_role));
    expectedList.add(new MemberOfSite(site4, site4_role));
    expectedList.add(new MemberOfSite(site1, site1_role));

    try
    {
        checkList(expectedList, paging.getExpectedPaging(), resp);
    }
    catch (AssertionError error)
    {
        // Site3 and Site4 have a same title, and as we are sorting on titles (default sorting),
        // we can't guarantee the order in which the sites will
        // return, hence swap the sites and compare again.
        Collections.swap(expectedList, 1, 2);
        checkList(expectedList, paging.getExpectedPaging(), resp);
    }
}
 
Example 20
Source File: AsynchronousActionExecutionQueueImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Executes the action via the action runtime service
 * 
 * @see java.lang.Runnable#run()
 */
public void run()
{
    try
    {
        // Get the run as user name
        final String userName = ((ActionImpl)ActionExecutionWrapper.this.action).getRunAsUser();
        if (userName == null)
        {
            throw new ActionServiceException("Cannot execute action asynchronously since run as user is 'null'");
        }
        // Get the tenant the action was submitted from
        final String tenantId = ((ActionImpl)ActionExecutionWrapper.this.action).getTenantId();
        
        // import the content
        TenantRunAsWork<Object> actionRunAs = new TenantRunAsWork<Object>()
        {
            public Object doWork() throws Exception
            {
                RetryingTransactionCallback<Object> actionCallback = new RetryingTransactionCallback<Object>()
                {
                    public Object execute()
                    {   
                        // If we have rules, apply them
                        if (ActionExecutionWrapper.this.executedRules != null)
                        {
                            AlfrescoTransactionSupport.bindResource("RuleServiceImpl.ExecutedRules", ActionExecutionWrapper.this.executedRules);
                        }
                        
                        // Allow other classes to know when this action completes
                        AlfrescoTransactionSupport.bindListener(new CallbackTransactionListener(
                              ActionExecutionWrapper.this.action,
                              ActionExecutionWrapper.this.actionedUponNodeRef
                        ));
                        
                        // Have the action run
                        ActionExecutionWrapper.this.actionService.executeActionImpl(
                                ActionExecutionWrapper.this.action,
                                ActionExecutionWrapper.this.actionedUponNodeRef,
                                ActionExecutionWrapper.this.checkConditions, true,
                                ActionExecutionWrapper.this.actionChain);

                        return null;
                    }
                };
                return transactionService.getRetryingTransactionHelper().doInTransaction(actionCallback);
            }
        };
        TenantUtil.runAsUserTenant(actionRunAs, userName, tenantId);
    }
    catch (Throwable e)
    {
        Throwable rootCause = (e instanceof AlfrescoRuntimeException) ? ((AlfrescoRuntimeException)e).getRootCause() : null;
        String message = (rootCause == null ? null : rootCause.getMessage());
        message = "Failed to execute asynchronous action: " + action+ (message == null ? "" : ": "+message);
        if(!ActionExecutionWrapper.this.actionService.onLogException(action, logger, rootCause, message))
        {
            //if not handled by the executor just show in the log
            logger.error(message, e);
        }
    }
    handleAsyncActionIsCompleted(actionedUponNodeRef, action);
}