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

The following are Jave code examples for showing how to use setFullyAuthenticatedUser() of the org.alfresco.repo.security.authentication.AuthenticationUtil class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: alfresco-repository   File: FileFolderLoaderTest.java   Source Code and License Vote up 7 votes
@Test
public void testNoPermissionsToFindFolder() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setFullyAuthenticatedUser("BOB-1");
        fileFolderLoader.createFiles(
                hiddenFolderPath,
                0, 256, 1024L, 1024L, Long.MAX_VALUE, false,
                10, 256L);
        fail("No permissions to see folder.");
    }
    catch (AccessDeniedException e)
    {
        // Expected
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 2
Project: alfresco-remote-api   File: CustomModelImportTest.java   Source Code and License Vote up 6 votes
public void testValidUpload_ModelOnly() throws Exception
{
    File zipFile = getResourceFile("validModel.zip");
    PostRequest postRequest = buildMultipartPostRequest(zipFile);

    AuthenticationUtil.setFullyAuthenticatedUser(NON_ADMIN_USER);
    Response response = sendRequest(postRequest, 403);

    AuthenticationUtil.setFullyAuthenticatedUser(CUSTOM_MODEL_ADMIN);
    response = sendRequest(postRequest, 200);

    JSONObject json = new JSONObject(new JSONTokener(response.getContentAsString()));
    String importedModelName = json.getString("modelName");
    importedModels.add(importedModelName);

    assertFalse(json.has("shareExtModule"));

    // Import the same model again
    sendRequest(postRequest, 409); // name conflict
}
 
Example 3
Project: alfresco-repository   File: HasTagEvaluatorTest.java   Source Code and License Vote up 6 votes
@SuppressWarnings("deprecation")
@Override
protected void onSetUpInTransaction() throws Exception
{
    this.nodeService = (NodeService)applicationContext.getBean("nodeService");
    this.taggingService = (TaggingService)applicationContext.getBean("taggingService");
    
    // Create the store and get the root node
    this.testStoreRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
    this.rootNodeRef = this.nodeService.getRootNode(this.testStoreRef); 

    // Create the node used for tests
    this.nodeRef = this.nodeService.createNode(
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}testnode"),
            ContentModel.TYPE_CONTENT).getChildRef();
    
    this.evaluator = (HasTagEvaluator)applicationContext.getBean(HasTagEvaluator.NAME);        
    AuthenticationUtil.setFullyAuthenticatedUser("admin");
}
 
Example 4
Project: alfresco-repository   File: ActionServiceImpl2Test.java   Source Code and License Vote up 6 votes
@Before
public void initTestSiteAndUsersAndSomeContent()
{
    final String siteShortName = ActionServiceImpl2Test.class.getSimpleName() + "TestSite"
            + System.currentTimeMillis();

    // This will create a public Share site whose creator is the admin user.
    // It will create 4 users (one for each of the Share roles, and add them
    // to the site.
    testSiteAndMemberInfo = temporarySites.createTestSiteWithUserPerRole(siteShortName, "sitePreset",
            SiteVisibility.PUBLIC, AuthenticationUtil.getAdminUserName());

    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    testNode = transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            // get the Document Library NodeRef
            final NodeRef docLibNodeRef = testSiteAndMemberInfo.doclib;

            // Create a test node. It doesn't need content.
            return nodeService.createNode(docLibNodeRef, ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS,
                    ContentModel.TYPE_CONTENT).getChildRef();
        }
    });
}
 
Example 5
Project: alfresco-remote-api   File: TransferWebScriptTest.java   Source Code and License Vote up 6 votes
public void testVerify() throws Exception
{
    String url = "/api/transfer/test";
    PostRequest req = new PostRequest(url, new JSONObject().toString(), "application/json");
    
    //First, we'll try the request as a simple, non-admin user (expect a 401)
    AuthenticationUtil.setFullyAuthenticatedUser(USERNAME);
    sendRequest(req, 401);
    
    //Then we'll have a go as the system user (expect a 200)
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
    sendRequest(req, 200);
    
    //Then we'll disable the transfer receiver and try again as the system user (expect a 404)
    TransferWebScript webscript = (TransferWebScript)getServer().getApplicationContext().getBean("webscript.org.alfresco.repository.transfer.transfer.post");
    webscript.setEnabled(false);
    sendRequest(req, 404);
}
 
Example 6
Project: alfresco-repository   File: FeedNotifierTest.java   Source Code and License Vote up 6 votes
/**
 * ALF-16155 test
 */
@Test
public void testFailedNotifications()
{
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    // execute the notifier, counting the number of successful and unsuccessful notifications
    assertEquals(0, errorProneActionExecutor.getNumSuccess());
    assertEquals(0, errorProneActionExecutor.getNumFailed());
    feedNotifier.execute(1);
    assertEquals(1, errorProneActionExecutor.getNumFailed()); // should be a single notification failure
    assertTrue(errorProneActionExecutor.getNumSuccess() > 0); // others should have gone through ok
    int numSuccessfulNotifications = errorProneActionExecutor.getNumSuccess();

    // execute the notifier again, checking that there are no more notifications
    feedNotifier.execute(1);
    // should still be failing
    assertEquals(2, errorProneActionExecutor.getNumFailed());
    // there should not be any more because they have been processed already
    assertEquals(numSuccessfulNotifications, errorProneActionExecutor.getNumSuccess());
}
 
Example 7
Project: alfresco-repository   File: ActionServiceImpl2Test.java   Source Code and License Vote up 5 votes
private NodeRef addTempScript(final String scriptFileName, final String javaScript)
{
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    return transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {

            // get the company_home
            NodeRef companyHomeRef = wellKnownNodes.getCompanyHome();
            // get the Data Dictionary
            NodeRef dataDictionaryRef = nodeService.getChildByName(companyHomeRef, ContentModel.ASSOC_CONTAINS,
                    "Data Dictionary");
            // get the Scripts
            NodeRef scriptsRef = nodeService.getChildByName(dataDictionaryRef, ContentModel.ASSOC_CONTAINS,
                    "Scripts");

            // Create the script node reference
            NodeRef script = nodeService.createNode(scriptsRef, ContentModel.ASSOC_CONTAINS,
                    QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, scriptFileName),
                    ContentModel.TYPE_CONTENT).getChildRef();

            nodeService.setProperty(script, ContentModel.PROP_NAME, scriptFileName);

            ContentWriter contentWriter = contentService.getWriter(script, ContentModel.PROP_CONTENT, true);
            contentWriter.setMimetype(MimetypeMap.MIMETYPE_JAVASCRIPT);
            contentWriter.setEncoding("UTF-8");
            contentWriter.putContent(javaScript);

            tempNodes.addNodeRef(script);              
            return script;
        }
    });
}
 
Example 8
Project: alfresco-remote-api   File: QueriesSitesApiTest.java   Source Code and License Vote up 5 votes
private NodeRef getNodeRef(String createdSiteId)
{
    AuthenticationUtil.setFullyAuthenticatedUser(user1);
    // The following call to siteService.getSite(createdSiteId).getNodeRef() returns a NodeRef like:
    //    workspace://SpacesStore/9db76769-96de-4de4-bdb4-a127130af362
    // We call tenantService.getName(nodeRef) to get a fully qualified NodeRef as Solr returns this.
    // They look like:
    //    workspace://@[email protected]/9db76769-96de-4de4-bdb4-a127130af362
    NodeRef nodeRef = siteService.getSite(createdSiteId).getNodeRef();
    nodeRef = tenantService.getName(nodeRef);
    return nodeRef;
}
 
Example 9
Project: alfresco-remote-api   File: CommentsApiTest.java   Source Code and License Vote up 5 votes
public void testCommentDoesNotVersion() throws Exception
{
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    String versionBefore = getCurrentVersion(nodeRef);
    addComment(nodeRef, AuthenticationUtil.getAdminUserName(), 200);
    String versionAfter = getCurrentVersion(nodeRef);
    assertEquals(versionBefore, versionAfter);
}
 
Example 10
Project: alfresco-remote-api   File: AuditAppTest.java   Source Code and License Vote up 5 votes
private void testRetrieveAuditEntry(AuditApps auditAppsProxy, AuditApp auditApp) throws Exception
{
    int skipCount = 0;
    int maxItems = 4;
    Paging paging = getPaging(skipCount, maxItems);

    Map<String, String> otherParams = new HashMap<>();
    ListResponse<AuditEntry> resp = auditAppsProxy.getAuditAppEntries(auditApp.getId(),
            createParams(paging, otherParams), HttpServletResponse.SC_OK);
    String id = resp.getList().get(0).getId().toString();

    //Positive tests
    //200
    AuditEntry entryResp = auditAppsProxy.getAuditEntry(auditApp.getId(), id, null, HttpServletResponse.SC_OK);
    validateAuditEntryFields(entryResp, auditApp);
    assertNotNull(entryResp.getValues());

    // Negative tests
    // 400
    auditAppsProxy.getAuditEntry(auditApp.getId(), id+"invalidIdText", null, HttpServletResponse.SC_BAD_REQUEST);
    // 401
    setRequestContext(networkOne.getId(), networkAdmin, "wrongPassword");
    auditAppsProxy.getAuditEntry(auditApp.getId(), id, null, HttpServletResponse.SC_UNAUTHORIZED);
    // 403
    setRequestContext(networkOne.getId(), user1, null);
    auditAppsProxy.getAuditEntry(auditApp.getId(), id, null, HttpServletResponse.SC_FORBIDDEN);
    // 404
    setRequestContext(networkOne.getId(), networkAdmin, DEFAULT_ADMIN_PWD);
    auditAppsProxy.getAuditEntry(auditApp.getId(), "" + Math.abs(new Random().nextLong()), null, HttpServletResponse.SC_NOT_FOUND);
    // 501
    setRequestContext(networkOne.getId(), networkAdmin, DEFAULT_ADMIN_PWD);
    AuthenticationUtil.setFullyAuthenticatedUser(networkAdmin);
    disableSystemAudit();
    auditAppsProxy.getAuditEntry(auditApp.getId(), id, null, HttpServletResponse.SC_NOT_IMPLEMENTED);
    enableSystemAudit();
}
 
Example 11
Project: alfresco-repository   File: TemporaryNodes.java   Source Code and License Vote up 5 votes
/**
 * This method creates a cm:content NodeRef whose content is taken from the named Alfresco 'quick' file and adds it to the internal
 * list of NodeRefs to be tidied up by the rule.
 * This method will be run in its own transaction and will be run with the specified user as the fully authenticated user,
 * thus ensuring the named user is the cm:creator of the new node.
 *
 * @param quickFileName the file name of the quick file - will also be the cm:name of the new node.
 * @param parentNode the parent node
 * @param nodeCreator the username of the person who will create the node
 * @return the newly created NodeRef.
 * @since 4.1.4
 */
public NodeRef createQuickFileByName(final String quickFileName, final NodeRef parentNode, final String nodeCreator)
{
    final MimetypeMap mimetypeService = (MimetypeMap) appContextRule.getApplicationContext().getBean("mimetypeService");
    final RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) appContextRule.getApplicationContext().getBean("retryingTransactionHelper");
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(nodeCreator);
    
    NodeRef newNodeRef = transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            final NodeRef result = createNode(quickFileName, parentNode, ContentModel.TYPE_CONTENT);
            
            File quickFile = AbstractContentTransformerTest.loadNamedQuickTestFile(quickFileName);
            
            ContentService contentService = appContextRule.getApplicationContext().getBean("contentService", ContentService.class);
            ContentWriter writer = contentService.getWriter(result, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(mimetypeService.guessMimetype(quickFileName));
            writer.setEncoding("UTF-8");
            writer.putContent(quickFile);
            
            return result;
        }
    });
    
    AuthenticationUtil.popAuthentication();
    
    this.temporaryNodeRefs.add(newNodeRef);
    return newNodeRef;
}
 
Example 12
Project: alfresco-repository   File: ScriptNodeTest.java   Source Code and License Vote up 5 votes
@Test(expected=AccessDeniedException.class)
public void userTwoCannotAccessTestFile() throws Exception
{
    AuthenticationUtil.setFullyAuthenticatedUser(USER_TWO_NAME);
    touchFileToTriggerPermissionCheck(USER_ONES_TEST_FILE);
    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example 13
Project: alfresco-repository   File: DiscussionServiceImplTest.java   Source Code and License Vote up 5 votes
@BeforeClass public static void initTestsContext() throws Exception
{
    testContext = ApplicationContextHelper.getApplicationContext();
    AUTHENTICATION_SERVICE = (MutableAuthenticationService)testContext.getBean("authenticationService");
    BEHAVIOUR_FILTER       = (BehaviourFilter)testContext.getBean("policyBehaviourFilter");
    DISCUSSION_SERVICE     = (DiscussionService)testContext.getBean("DiscussionService");
    NODE_SERVICE           = (NodeService)testContext.getBean("nodeService");
    PUBLIC_NODE_SERVICE    = (NodeService)testContext.getBean("NodeService");
    PERSON_SERVICE         = (PersonService)testContext.getBean("personService");
    TRANSACTION_HELPER     = (RetryingTransactionHelper)testContext.getBean("retryingTransactionHelper");
    PERMISSION_SERVICE     = (PermissionService)testContext.getBean("permissionService");
    SITE_SERVICE           = (SiteService)testContext.getBean("SiteService");
    TENANT_ADMIN_SERVICE   = testContext.getBean("tenantAdminService", TenantAdminService.class);

    ADMIN_USER = AuthenticationUtil.getAdminUserName() + "@" + TENANT_DOMAIN;

    createTenant();
    
    // Do the setup as admin
    AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER);
    TenantContextHolder.setTenantDomain(TENANT_DOMAIN);
    createUser(TEST_USER);
    
    // We need to create the test site as the test user so that they can contribute content to it in tests below.
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER);
    TenantContextHolder.setTenantDomain(TENANT_DOMAIN);
    createTestSites();
}
 
Example 14
Project: alfresco-remote-api   File: JSR168PortletAuthenticatorFactory.java   Source Code and License Vote up 5 votes
public boolean authenticate(RequiredAuthentication required, boolean isGuest)
{
    // first look for the username key in the session - we add this by hand for some portals
    // when the WebScriptPortletRequest is created
    String portalUser = (String)req.getPortletSession().getAttribute(WebScriptPortletRequest.ALFPORTLETUSERNAME);
    if (portalUser == null)
    {
        portalUser = req.getRemoteUser();
    }
    
    if (logger.isDebugEnabled())
    {
        logger.debug("JSR-168 Remote user: " + portalUser);
    }
    
    if (isGuest || portalUser == null)
    {
        if (logger.isDebugEnabled())
            logger.debug("Authenticating as Guest");
        
        // authenticate as guest
        AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getGuestUserName());
    }
    else
    {
        if (logger.isDebugEnabled())
            logger.debug("Authenticating as user " + portalUser);

        UserTransaction txn = null;
        try
        {
        	txn = txnService.getUserTransaction();
        	txn.begin();

        	if (!unprotAuthenticationService.authenticationExists(portalUser))
        	{
        		throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN, "User " + portalUser + " is not a known Alfresco user");
        	}
        	AuthenticationUtil.setFullyAuthenticatedUser(portalUser);
        }
        catch (Throwable err)
        {
        	throw new AlfrescoRuntimeException("Error authenticating user: " + portalUser, err);
        }
        finally
        {
        	try
        	{
        		if (txn != null)
        		{
        			txn.rollback();
        		}
        	}
        	catch (Exception tex)
        	{
        		// nothing useful we can do with this
        	}
        }
    }
    
    return true;
}
 
Example 15
Project: alfresco-repository   File: ArchiveAndRestoreTest.java   Source Code and License Vote up 5 votes
/**
 * <a href="https://issues.alfresco.com/jira/browse/MNT-2777">MNT-2777</a>
 */
public void testALF17554ArchiveAndRestoreCheckPermission() throws Exception
{
    permissionService.setInheritParentPermissions(a, false);
    // Set the permission for the node for user USER_C
    AuthenticationUtil.setFullyAuthenticatedUser(USER_C);
    assertTrue(
            "The user should not have the permission set on the node yet.",
            permissionService.hasPermission(a, PermissionService.COORDINATOR) == AccessStatus.DENIED);
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    permissionService.setPermission(a, USER_C, PermissionService.COORDINATOR, true);
    assertTrue(
            "The user should have the permission set on the node.",
            permissionService.hasPermission(a, PermissionService.COORDINATOR) == AccessStatus.ALLOWED);
    commitAndBeginNewTransaction();
    nodeService.deleteNode(a);
    verifyNodeExistence(a, false);
    nodeService.restoreNode(a_, null, null, null);
    // Check the permission
    AuthenticationUtil.setFullyAuthenticatedUser(USER_C);
    assertTrue(
            "The user should have the same permission after restoring the node.",
            permissionService.hasPermission(a, PermissionService.COORDINATOR) == AccessStatus.ALLOWED);
    assertFalse(
            "The node should have InheritParentPermissions set to false.",
            permissionService.getInheritParentPermissions(a));
}
 
Example 16
Project: alfresco-repository   File: SiteServiceImplTest.java   Source Code and License Vote up 5 votes
/**
 * This method tests https://issues.alfresco.com/jira/browse/ALF-3785 which allows 'public' sites
 * to be only visible to members of a configured group, by default EVERYONE.
 * 
 * <br><br/>author Neil McErlean
 * @since 3.4
 */
@SuppressWarnings("deprecation")
public void testConfigurableSitePublicGroup() throws Exception
{
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    
    // We'll be configuring a JMX managed bean (in this test method only).
    ChildApplicationContextFactory sysAdminSubsystem = (ChildApplicationContextFactory) applicationContext.getBean("sysAdmin");
    final String sitePublicGroupPropName = "site.public.group";
    final String originalSitePublicGroup = "GROUP_EVERYONE";
    
    try
    {
        // Firstly we'll ensure that the site.public.group has the correct (pristine) value.
        String groupName = sysAdminSubsystem.getProperty(sitePublicGroupPropName);
        assertEquals(sitePublicGroupPropName + " was not the pristine value",
                originalSitePublicGroup, groupName);
        
        // Create a 'normal', unconfigured site.
        SiteInfo unconfiguredSite = siteService.createSite(TEST_SITE_PRESET, "unconfigured",
                                                           TEST_TITLE, TEST_DESCRIPTION, SiteVisibility.PUBLIC);
        assertTrue(containsConsumerPermission(originalSitePublicGroup, unconfiguredSite));

        
        // Now set the managed bean's visibility group to something other than GROUP_EVERYONE.
        // This is the group that will have visibility of subsequently created sites.
        //
        // We'll intentionally set it to a group that DOES NOT EXIST YET.
        String newGroupName = this.getClass().getSimpleName() + System.currentTimeMillis();
        String prefixedNewGroupName = PermissionService.GROUP_PREFIX + newGroupName;
        
        sysAdminSubsystem.stop();
        sysAdminSubsystem.setProperty(sitePublicGroupPropName, prefixedNewGroupName);
        sysAdminSubsystem.start();

        // Now create a site as before. It should fail as we're using a group that doesn't exist.
        boolean expectedExceptionThrown = false;
        try
        {
            siteService.createSite(TEST_SITE_PRESET, "thisShouldFail",
                    TEST_TITLE, TEST_DESCRIPTION, SiteVisibility.PUBLIC);
        }
        catch (SiteServiceException expected)
        {
            expectedExceptionThrown = true;
        }
        if (!expectedExceptionThrown)
        {
            fail("Expected exception on createSite with non-existent group was not thrown.");
        }
        
        
        // Now we'll create the group used above.
        authorityService.createAuthority(AuthorityType.GROUP, newGroupName);
        
        
        // And create the site as before. This time it should succeed.
        SiteInfo configuredSite = siteService.createSite(TEST_SITE_PRESET, "configured",
                TEST_TITLE, TEST_DESCRIPTION, SiteVisibility.PUBLIC);
        
        // And check the permissions on the site.
        assertTrue("The configured site should not have " + originalSitePublicGroup + " as SiteContributor",
                !containsConsumerPermission(originalSitePublicGroup, configuredSite));
        assertTrue("The configured site should have (newGroupName) as SiteContributor",
                containsConsumerPermission(prefixedNewGroupName, configuredSite));
    }
    finally
    {
        // Reset the JMX bean to its out-of-the-box values.
        sysAdminSubsystem.stop();
        sysAdminSubsystem.setProperty(sitePublicGroupPropName, originalSitePublicGroup);
        sysAdminSubsystem.start();
    }
}
 
Example 17
Project: alfresco-remote-api   File: RatingRestApiTest.java   Source Code and License Vote up 5 votes
@Override
protected void setUp() throws Exception
{
    super.setUp();
    authenticationService = (MutableAuthenticationService) getServer().getApplicationContext().getBean("AuthenticationService");
    nodeService = (NodeService) getServer().getApplicationContext().getBean("NodeService");
    personService = (PersonService) getServer().getApplicationContext().getBean("PersonService");
    repositoryHelper = (Repository) getServer().getApplicationContext().getBean("repositoryHelper");
    transactionHelper = (RetryingTransactionHelper)getServer().getApplicationContext().getBean("retryingTransactionHelper");  
    
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
    
    // Create some users to rate each other's content
    // and a test node which we will rate.
    // It doesn't matter that it has no content.
    testNode = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
            {
                public NodeRef execute() throws Throwable
                {
                    createUser(USER_ONE);
                    createUser(USER_TWO);

                    ChildAssociationRef result = nodeService.createNode(repositoryHelper.getCompanyHome(),
                                                            ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS,
                                                            ContentModel.TYPE_CONTENT, null);
                    return result.getChildRef();
                }          
            });        
}
 
Example 18
Project: alfresco-repository   File: RetryingTransactionHelperTestCase.java   Source Code and License Vote up 4 votes
/**
 * Executes a test in a retrying transaction as the admin user.
 * 
 * @param <A>    type of the object resulting from the test, can be set to {@link Void} if none.
 * @param test   test object to be executed within a retrying transaction
 * @param asUser user to execute the test as
 * @return A     the result of the test
 */
protected <A> A doTestInTransaction(final Test<A> test, final String asUser)
{    
    String origUser = AuthenticationUtil.getFullyAuthenticatedUser();
    AuthenticationUtil.setFullyAuthenticatedUser(asUser);
    try
    {        
        // Execute the run() method within a retrying transaction
        RetryingTransactionCallback<A> doRun = new RetryingTransactionCallback<A>()
        {
            @Override
            public A execute() throws Throwable
            {
                // Run test as user
                return test.run();              
            }            
        };                
        final A result = getRetryingTransactionHelper().doInTransaction(doRun);
        
        // Execute the test() method within a retrying transaction
        RetryingTransactionCallback<Void> doTest = new RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {
                // pass the result of the run into the test
                test.test(result);
                return null;                    
            }
            
        };
        getRetryingTransactionHelper().doInTransaction(doTest);
        
        return result;
    }
    finally
    {
        if (origUser != null)
        {
            AuthenticationUtil.setFullyAuthenticatedUser(origUser);
        }
        else
        {
            AuthenticationUtil.clearCurrentSecurityContext();
        }
    }                   
}
 
Example 19
Project: alfresco-repository   File: LinksServiceImplTest.java   Source Code and License Vote up 4 votes
@Test public void createUpdateDeleteEntry() throws Exception
{
   LinkInfo link;
   
   // Run as the test user instead
   AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER);
   
   
   // Create a link
   link = LINKS_SERVICE.createLink(
         LINKS_SITE.getShortName(), "Title", "Description",
         "http://www.alfresco.com/", false);
   
   
   // Check it
   assertEquals("Title", link.getTitle());
   assertEquals("Description", link.getDescription());
   assertEquals("http://www.alfresco.com/", link.getURL());
   assertEquals(false, link.isInternal());
   assertEquals(TEST_USER, link.getCreator());
   assertEquals(0, link.getTags().size());
   
   
   // Check the underlying node
   assertEquals("Title", PUBLIC_NODE_SERVICE.getProperty(link.getNodeRef(), LinksModel.PROP_TITLE));
   assertEquals("Description", PUBLIC_NODE_SERVICE.getProperty(link.getNodeRef(), LinksModel.PROP_DESCRIPTION));
   assertEquals("http://www.alfresco.com/", PUBLIC_NODE_SERVICE.getProperty(link.getNodeRef(), LinksModel.PROP_URL));
   assertEquals("http://www.alfresco.com/", CONTENT_SERVICE.getReader(link.getNodeRef(), ContentModel.PROP_CONTENT).getContentString());
   assertEquals(false, PUBLIC_NODE_SERVICE.hasAspect(link.getNodeRef(), LinksModel.ASPECT_INTERNAL_LINK));
   
   
   // Change it
   link.setTitle("New Title");
   link.setURL("http://share.alfresco.com/");
   link.setInternal(true);
   
   LINKS_SERVICE.updateLink(link);
   
   
   // Fetch, and check
   link = LINKS_SERVICE.getLink(LINKS_SITE.getShortName(), link.getSystemName());
   assertEquals("New Title", link.getTitle());
   assertEquals("Description", link.getDescription());
   assertEquals("http://share.alfresco.com/", link.getURL());
   assertEquals(true, link.isInternal());
   assertEquals(TEST_USER, link.getCreator());
   assertEquals(0, link.getTags().size());
   
   
   // Check the underlying node now
   assertEquals("New Title", PUBLIC_NODE_SERVICE.getProperty(link.getNodeRef(), LinksModel.PROP_TITLE));
   assertEquals("Description", PUBLIC_NODE_SERVICE.getProperty(link.getNodeRef(), LinksModel.PROP_DESCRIPTION));
   assertEquals("http://share.alfresco.com/", PUBLIC_NODE_SERVICE.getProperty(link.getNodeRef(), LinksModel.PROP_URL));
   assertEquals("http://share.alfresco.com/", CONTENT_SERVICE.getReader(link.getNodeRef(), ContentModel.PROP_CONTENT).getContentString());
   assertEquals(true, PUBLIC_NODE_SERVICE.hasAspect(link.getNodeRef(), LinksModel.ASPECT_INTERNAL_LINK));
   
   
   // Delete it
   LINKS_SERVICE.deleteLink(link);
   
   // Check it went
   assertEquals(null, LINKS_SERVICE.getLink(LINKS_SITE.getShortName(), link.getSystemName()));
}
 
Example 20
Project: alfresco-remote-api   File: PutMethodTest.java   Source Code and License Vote up 4 votes
@Before
public void setUp() throws Exception
{
    searchService = ctx.getBean("SearchService", SearchService.class);
    fileFolderService = ctx.getBean("FileFolderService", FileFolderService.class);
    nodeService = ctx.getBean("NodeService", NodeService.class);
    transactionService = ctx.getBean("transactionService", TransactionService.class);
    webDAVHelper = ctx.getBean("webDAVHelper", WebDAVHelper.class);
    authenticationService = ctx.getBean("authenticationService", MutableAuthenticationService.class);
    personService = ctx.getBean("PersonService", PersonService.class);
    lockService = ctx.getBean("LockService", LockService.class);
    contentService = ctx.getBean("contentService", ContentService.class);
    checkOutCheckInService = ctx.getBean("CheckOutCheckInService", CheckOutCheckInService.class);
    permissionService = ctx.getBean("PermissionService", PermissionService.class);
    namespaceService = ctx.getBean("namespaceService", NamespaceService.class);

    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    repositoryHelper = (Repository)ctx.getBean("repositoryHelper");
    companyHomeNodeRef = repositoryHelper.getCompanyHome();
    txn = transactionService.getUserTransaction();
    txn.begin();
    createUser(USER1_NAME);
    createUser(USER2_NAME);

    InputStream testDataIS = getClass().getClassLoader().getResourceAsStream(TEST_DATA_FILE_NAME);
    InputStream davLockInfoAdminIS = getClass().getClassLoader().getResourceAsStream(DAV_LOCK_INFO_ADMIN);
    InputStream davLockInfoUser2IS = getClass().getClassLoader().getResourceAsStream(DAV_LOCK_INFO_USER2);
    
    testDataFile = IOUtils.toByteArray(testDataIS);
    davLockInfoAdminFile = IOUtils.toByteArray(davLockInfoAdminIS);
    davLockInfoUser2File = IOUtils.toByteArray(davLockInfoUser2IS);

    testDataIS.close();
    davLockInfoAdminIS.close();
    davLockInfoUser2IS.close();

    // Create a test file with versionable aspect and content
    Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
    versionableDocName = "doc-" + GUID.generate();
    properties.put(ContentModel.PROP_NAME, versionableDocName);

    versionableDoc = nodeService.createNode(companyHomeNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName(ContentModel.USER_MODEL_URI, versionableDocName),
            ContentModel.TYPE_CONTENT, properties).getChildRef();
    contentService.getWriter(versionableDoc, ContentModel.PROP_CONTENT, true).putContent("WebDAVTestContent");
    nodeService.addAspect(versionableDoc, ContentModel.ASPECT_VERSIONABLE, null);

    txn.commit();

    txn = transactionService.getUserTransaction();
    txn.begin();
}