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

The following examples show how to use org.alfresco.repo.tenant.TenantUtil#runAsTenant() . 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: QuickShareServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public boolean canRead(String sharedId)
{
    Pair<String, NodeRef> pair = getTenantNodeRefFromSharedId(sharedId);
    final String tenantDomain = pair.getFirst();
    final NodeRef nodeRef = pair.getSecond();
    
    return TenantUtil.runAsTenant(new TenantRunAsWork<Boolean>()
    {
        public Boolean doWork() throws Exception
        {
            try
            {
                checkQuickShareNode(nodeRef);
                return permissionService.hasPermission(nodeRef, PermissionService.READ) == AccessStatus.ALLOWED;
            }
            catch (AccessDeniedException ex)
            {
                return false;
            }
        }
    }, tenantDomain);
    
}
 
Example 2
Source File: MailActionExecuter.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public boolean personExists(final String user)
{
    boolean exists = false;
    String domain = tenantService.getPrimaryDomain(user); // get primary tenant 
    if (domain != null) 
    { 
        exists = TenantUtil.runAsTenant(new TenantRunAsWork<Boolean>()
        {
            public Boolean doWork() throws Exception
            {
                return personService.personExists(user);
            }
        }, domain);
    }
    else
    {
        exists = personService.personExists(user);
    }
    return exists;
}
 
Example 3
Source File: MailActionExecuter.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public NodeRef getPerson(final String user)
{
    NodeRef person = null;
    String domain = tenantService.getPrimaryDomain(user); // get primary tenant 
    if (domain != null) 
    { 
        person = TenantUtil.runAsTenant(new TenantRunAsWork<NodeRef>()
        {
            public NodeRef doWork() throws Exception
            {
                return personService.getPerson(user);
            }
        }, domain);
    }
    else
    {
        person = personService.getPerson(user);
    }
    return person;
}
 
Example 4
Source File: MailActionExecuter.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public String getPersonEmail(final String user)
{
    final NodeRef person = getPerson(user);
    String email = null;
    String domain = tenantService.getPrimaryDomain(user); // get primary tenant 
    if (domain != null) 
    { 
        email = TenantUtil.runAsTenant(new TenantRunAsWork<String>()
        {
            public String doWork() throws Exception
            {
                return (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL);
            }
        }, domain);
    }
    else
    {
        email = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL);
    }
    return email;
}
 
Example 5
Source File: AbstractMailActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * ACE-2564
 */
@Test
public void testSendEmailByExternalUser() throws IOException, MessagingException
{
    final Serializable recipients = (Serializable) Arrays.asList(BRITISH_USER.getUsername());
    final String subject = "";
    final String template = "alfresco/templates/mail/test.txt.ftl";
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(EXTERNAL_USER.getUsername());
    MimeMessage message = null;


    try
    {

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

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

        Assert.assertNotNull(message);
        Assert.assertEquals("Hello 1 Jan 1970", (String) message.getContent());
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 6
Source File: RepoService.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String getSiteNetwork(final String siteShortName, String tenantDomain)
  {
return TenantUtil.runAsTenant(new TenantRunAsWork<String>()
{
	@Override
	public String doWork() throws Exception
	{
    	return tenantService.getName(siteShortName);
	}
}, tenantDomain);
  }
 
Example 7
Source File: RepoService.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public NodeRef addUserDescription(final String personId, final String personDescription)
{
	NodeRef personRef = TenantUtil.runAsTenant(new TenantRunAsWork<NodeRef>()
	{
		public NodeRef doWork() throws Exception
		{
			return RepoService.this.addUserDescription(personId, TestNetwork.this, personDescription);
		}
	}, getId());

	return personRef;
}
 
Example 8
Source File: RepoService.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public TestPerson createUser(final PersonInfo personInfo)
{
	final String username = publicApiContext.createUserName(personInfo.getUsername(), getId());
	TestPerson testPerson = TenantUtil.runAsTenant(new TenantRunAsWork<TestPerson>()
          {
              public TestPerson doWork() throws Exception
              {
              	TestPerson person = RepoService.this.createUser(personInfo, username, TestNetwork.this);
                  
                  return person;
              }
          }, getId());
	addPerson(testPerson);
	return testPerson;
}
 
Example 9
Source File: RepoService.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public TestSite getSite(final String siteShortName)
{
	TestSite site = TenantUtil.runAsTenant(new TenantRunAsWork<TestSite>()
	{
		@Override
		public TestSite doWork() throws Exception
		{
			SiteInfo siteInfo = siteService.getSite(siteShortName);
			return new TestSite(TestNetwork.this, siteInfo);
		}
	}, getId());
	return site;
}
 
Example 10
Source File: AuthenticatedTimerJobHandler.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void execute(final JobEntity job, final String configuration, final ExecutionEntity execution,
            final CommandContext commandContext) 
{
    String userName = null;
    String tenantToRunIn = (String) execution.getVariable(ActivitiConstants.VAR_TENANT_DOMAIN);
    if(tenantToRunIn != null && tenantToRunIn.trim().length() == 0)
    {
        tenantToRunIn = null;
    }
    
    final ActivitiScriptNode initiatorNode = (ActivitiScriptNode) execution.getVariable(WorkflowConstants.PROP_INITIATOR);
    
    // Extracting the properties from the initiatornode should be done in correct tennant or as administrator, since we don't 
    // know who started the workflow yet (We can't access node-properties when no valid authentication context is set up).
    if(tenantToRunIn != null)
    {
        userName = TenantUtil.runAsTenant(new TenantRunAsWork<String>()
        {
            @Override
            public String doWork() throws Exception
            {
                return getInitiator(initiatorNode);
            }
        }, tenantToRunIn);
    }
    else
    {
        // No tenant on worklfow, run as admin in default tenant
        userName = AuthenticationUtil.runAs(new RunAsWork<String>()
        {
            @SuppressWarnings("synthetic-access")
            public String doWork() throws Exception
            {
                return getInitiator(initiatorNode);
            }
        }, AuthenticationUtil.getSystemUserName());
    }
    
    // Fall back to task assignee, if no initiator is found
    if(userName == null)
    {
        PvmActivity targetActivity = execution.getActivity();
        if (targetActivity != null)
        {
            // Only try getting active task, if execution timer is waiting on is a userTask
            String activityType = (String) targetActivity.getProperty(ActivitiConstants.NODE_TYPE);
            if (ActivitiConstants.USER_TASK_NODE_TYPE.equals(activityType))
            {
                Task task = new TaskQueryImpl(commandContext)
                .executionId(execution.getId())
                .executeSingleResult(commandContext);
                
                if (task != null && task.getAssignee() != null)
                {
                    userName = task.getAssignee();
                }
            }
        }
    }
    
    // When no task assignee is set, nor the initiator, use system user to run job
    if (userName == null)
    {
        userName = AuthenticationUtil.getSystemUserName();
        tenantToRunIn = null;
    }
    
    if(tenantToRunIn != null)
    {
        TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
        {
            @Override
            public Void doWork() throws Exception
            {
                wrappedHandler.execute(job, configuration, execution, commandContext);
                return null;
            }
        }, userName, tenantToRunIn);
    }
    else
    {
        // Execute the timer without tenant
        AuthenticationUtil.runAs(new RunAsWork<Void>()
        {
            @SuppressWarnings("synthetic-access")
            public Void doWork() throws Exception
            {
                wrappedHandler.execute(job, configuration, execution, commandContext);
                return null;
            }
        }, userName);
    }
}
 
Example 11
Source File: DefaultImporterContentCache.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public ContentData getContent(final ImportPackageHandler handler, final ContentData sourceContentData)
{
    ContentData cachedContentData = null;
    final String sourceContentUrl = sourceContentData.getContentUrl();

    contentUrlsLock.readLock().lock();
    
    try
    {
        cachedContentData = contentUrls.get(sourceContentUrl);
        if (cachedContentData == null)
        {
            contentUrlsLock.readLock().unlock();
            contentUrlsLock.writeLock().lock();
            
            try
            {
                cachedContentData = contentUrls.get(sourceContentUrl);
                if (cachedContentData == null)
                {
                    cachedContentData = TenantUtil.runAsTenant(new TenantRunAsWork<ContentData>()
                    {
                        @Override
                        public ContentData doWork() throws Exception
                        {
                            InputStream contentStream = handler.importStream(sourceContentUrl);
                            ContentWriter writer = contentService.getWriter(null, null, false);
                            writer.setEncoding(sourceContentData.getEncoding());
                            writer.setMimetype(sourceContentData.getMimetype());
                            writer.putContent(contentStream);
                            return writer.getContentData();
                        }
                    }, TenantService.DEFAULT_DOMAIN);
                    
                    contentUrls.put(sourceContentUrl, cachedContentData);
                }
            }
            finally
            {
                contentUrlsLock.readLock().lock();
                contentUrlsLock.writeLock().unlock();
            }
        }
    }
    finally
    {
        contentUrlsLock.readLock().unlock();
    }
    
    if (logger.isDebugEnabled())
        logger.debug("Mapped contentUrl " + sourceContentUrl + " to " + cachedContentData);
        
    return cachedContentData;
}
 
Example 12
Source File: PublicApiRepositoryContainer.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void executeScript(final WebScriptRequest scriptReq, final WebScriptResponse scriptRes, final Authenticator auth)
    throws IOException
{
    String tenant = ((PublicApiTenantWebScriptServletRequest)scriptReq).getTenant();
    if (tenant != null)
    {
        // handle special tenant keys
        // -super-    => run as system tenant
        // -default-  => run as user's default tenant
        String user = null;
        if (tenant.equalsIgnoreCase(TenantUtil.DEFAULT_TENANT))
        {
            // switch from default to super tenant, if not authenticated
            user = AuthenticationUtil.getFullyAuthenticatedUser();
            if (user == null)
            {
                tenant = TenantUtil.SYSTEM_TENANT;
            }
        }
        
        // run as super tenant
        if (tenant.equalsIgnoreCase(TenantUtil.SYSTEM_TENANT))
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("executeScript (-system-): ["+user+","+tenant+"] "+scriptReq.getServicePath());
            }

            TenantUtil.runAsTenant(new TenantRunAsWork<Object>()
            {
                public Object doWork() throws Exception
                {
                    PublicApiRepositoryContainer.super.executeScript(scriptReq, scriptRes, auth);
                    return null;
                    
                }
            }, TenantService.DEFAULT_DOMAIN);
        }
        else
        {
            if (tenant.equalsIgnoreCase(TenantUtil.DEFAULT_TENANT))
            {
                tenant = tenantAdminService.getUserDomain(user);
            }

            // run as explicit tenant
            TenantUtil.runAsTenant(new TenantRunAsWork<Object>()
            {
                public Object doWork() throws Exception
                {
                    PublicApiRepositoryContainer.super.executeScript(scriptReq, scriptRes, auth);
                    return null;
                }
            }, tenant);
        }
    }
}