Java Code Examples for org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback

The following are top voted examples for showing how to use org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: alfresco-remote-api   File: RepoStore.java   Source Code and License 7 votes vote down vote up
public boolean hasDocument(final String documentPath)
{
    return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Boolean>()
    {
        public Boolean doWork() throws Exception
        {
            return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Boolean>()
            {
                public Boolean execute() throws Exception
                {
                    NodeRef nodeRef = findNodeRef(documentPath);
                    return (nodeRef != null);
                }
            }, true, false);
        }
    }, AuthenticationUtil.getSystemUserName());
}
 
Example 2
Project: alfresco-repository   File: AuditMethodInterceptorTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test for <a href="https://issues.alfresco.com/jira/browse/MNT-16748">MNT-16748</a> <br>
 * Use {@link SearchService#query(StoreRef, String, String)} to perform a query.
 */
public void testAuditSearchServiceQuery() throws Exception
{
    // Run as admin
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    // Perform a search
    @SuppressWarnings("unused")
    ResultSet rs = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<ResultSet>()
    {
        @Override
        public ResultSet execute() throws Throwable
        {
            return searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_XPATH, "/app:company_home");
        }

    }, true, false);

    // Check the audit entries
    checkAuditEntries(APPLICATION_NAME_MNT_16748, SearchService.LANGUAGE_XPATH, "/app:company_home", 1);
}
 
Example 3
Project: alfresco-repository   File: DictionaryRepositoryBootstrap.java   Source Code and License 6 votes vote down vote up
/**
 * Initialise the dictionary, ensuring that a transaction is available
 */
@Override
public void onDictionaryInit()
{
    if(onLoadDynamicModelDelegate == null)
    {
        onLoadDynamicModelDelegate = policyComponent.registerClassPolicy(DynamicModelPolicies.OnLoadDynamicModel.class);
    }
    RetryingTransactionCallback<Void> initCallback = new RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            onDictionaryInitInTxn();
            return null;
        }
    };
    transactionService.getRetryingTransactionHelper().doInTransaction(initCallback, true, false);
}
 
Example 4
Project: alfresco-remote-api   File: RepoStore.java   Source Code and License 6 votes vote down vote up
/**
 * Gets the last modified time of the content
 * 
 * @return  last modified time
 */
public long lastModified()
{
    return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Long>()
    {
        public Long doWork() throws Exception
        {
            return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Long>()
            {
                public Long execute() throws Exception
                {
                    ContentReader reader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
                    return reader.getLastModified();
                }
            });
        }
    }, AuthenticationUtil.getSystemUserName());            
}
 
Example 5
Project: alfresco-repository   File: CustomModelServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a copy of the custom model where the created node will be a child
 * of download container.
 *
 * @param newName the model new name
 * @param modelNodeRef existing model nodeRef
 * @return the created nodeRef
 */
protected NodeRef createCustomModelCopy(final String newName, final NodeRef modelNodeRef)
{
    return doInTransaction(MSG_DOWNLOAD_COPY_MODEL_ERR, true, new RetryingTransactionCallback<NodeRef>()
    {
        @Override
        public NodeRef execute() throws Exception
        {
            final NodeRef newNodeRef = createDownloadTypeNode(newName);
            Serializable content = nodeService.getProperty(modelNodeRef, ContentModel.PROP_CONTENT);
            nodeService.setProperty(newNodeRef, ContentModel.PROP_CONTENT, content);

           return newNodeRef;
        }
    });
}
 
Example 6
Project: alfresco-remote-api   File: ResourceWebScriptDelete.java   Source Code and License 6 votes vote down vote up
@Override
public Void execute(final ResourceWithMetadata resource, final Params params, final WebScriptResponse res, boolean isReadOnly)
{
    final ResourceOperation operation = resource.getMetaData().getOperation(HttpMethod.DELETE);
    final WithResponse callBack = new WithResponse(operation.getSuccessStatus(), DEFAULT_JSON_CONTENT,CACHE_NEVER);
    transactionService.getRetryingTransactionHelper().doInTransaction(
        new RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {
                executeAction(resource, params, callBack); //ignore return result
                return null;
            }
        }, false, true);
    setResponse(res,callBack);
    return null;

}
 
Example 7
Project: alfresco-repository   File: FixedAclUpdaterTest.java   Source Code and License 6 votes vote down vote up
private static RetryingTransactionCallback<NodeRef> createFolderHierchyCallback(final NodeRef root,
        final FileFolderService fileFolderService, final String rootName, final int[] filesPerLevel)
{
    RetryingTransactionCallback<NodeRef> cb = new RetryingTransactionCallback<NodeRef>()
    {
        @Override
        public NodeRef execute() throws Throwable
        {
            NodeRef parent = createFile(fileFolderService, root, rootName, ContentModel.TYPE_FOLDER);
            createFolderHierchy(fileFolderService, parent, 0, filesPerLevel);
            return parent;
        }
    };
    return cb;
}
 
Example 8
Project: alfresco-repository   File: LinksServiceImplTest.java   Source Code and License 6 votes vote down vote up
private static void deleteUser(final String userName)
{
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
       @Override
       public Void execute() throws Throwable
       {
          if (PERSON_SERVICE.personExists(userName))
          {
             PERSON_SERVICE.deletePerson(userName);
          }

          return null;
       }
    });
}
 
Example 9
Project: alfresco-remote-api   File: RepoStore.java   Source Code and License 6 votes vote down vote up
public ScriptContent getScript(final String path)
{
    return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<ScriptContent>()
    {
        public ScriptContent doWork() throws Exception
        {
            return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<ScriptContent>()
            {
                public ScriptContent execute() throws Exception
                {
                    ScriptContent location = null;
                    NodeRef nodeRef = findNodeRef(path);
                    if (nodeRef != null)
                    {
                        location = new RepoScriptContent(path, nodeRef);
                    }
                    return location;
                }
            }, true, false);
        }
    }, AuthenticationUtil.getSystemUserName());
}
 
Example 10
Project: alfresco-repository   File: IndexConfigurationCheckerBootstrapBean.java   Source Code and License 6 votes vote down vote up
@Override
protected void onBootstrap(ApplicationEvent event)
{
    RetryingTransactionCallback<Object> checkWork = new RetryingTransactionCallback<Object>()
    {
        public Object execute() throws Exception
        {
            // reindex

            log.info("Checking/Recovering indexes ...");
            check();

            return null;
        }
    };
    transactionService.getRetryingTransactionHelper().doInTransaction(checkWork, true);
    
    
    
}
 
Example 11
Project: alfresco-repository   File: CannedQueryDAOTest.java   Source Code and License 6 votes vote down vote up
@Test public void testExecute_CountMimetypeWildcard() throws Throwable
{
    RetryingTransactionCallback<Long> selectCallback = new RetryingTransactionCallback<Long>()
    {
        @Override
        public Long execute() throws Throwable
        {
            // Need to make sure this does not match the one created in testExecute_FailureRecovery()
            TestOneParams params = new TestOneParams(mimetypePrefix + "-%", false);
            return cannedQueryDAOForTesting.executeCountQuery(QUERY_NS, QUERY_SELECT_MIMETYPE_COUNT, params);
        }
    };
    Long count = txnHelper.doInTransaction(selectCallback, true);
    assertNotNull(count);
    //Two values -aaa, -bbb
    assertEquals("Incorrect result count.", 2L, count.longValue());
}
 
Example 12
Project: alfresco-repository   File: AbstractMailActionExecuterTest.java   Source Code and License 6 votes vote down vote up
protected MimeMessage sendMessage(String from, String subject, String template, final Action mailAction)
{
    if (from != null)
    {
        mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, from);
    }
    mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, subject);
    mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, template);
    mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, getModel());

    RetryingTransactionHelper txHelper = APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);

    return txHelper.doInTransaction(new RetryingTransactionCallback<MimeMessage>()
    {
        @Override
        public MimeMessage execute() throws Throwable
        {
            ACTION_SERVICE.executeAction(mailAction, null);

            return ACTION_EXECUTER.retrieveLastTestMessage();
        }
    }, true);
}
 
Example 13
Project: alfresco-repository   File: SolrFacetServiceImplTest.java   Source Code and License 6 votes vote down vote up
@Test
public void reorderUnrecognisedFacetIdsShouldFail() throws Exception
{
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        @Override public Void execute() throws Throwable
        {
            final List<String> existingFacetIds = getExistingFacetIds();

            final List<String> facetIds = new ArrayList<>(existingFacetIds);
            facetIds.add("unrecognisedID");

            SOLR_FACET_SERVICE.reorderFacets(facetIds);

            final List<String> newfacetIds = getExistingFacetIds();
            
            assertEquals(existingFacetIds, newfacetIds);
            return null;
        }
        
    });
}
 
Example 14
Project: alfresco-repository   File: RepoTransferReceiverImpl.java   Source Code and License 6 votes vote down vote up
public void run()
{
    RunAsWork<Object> actionRunAs = new RunAsWork<Object>()
    {
        public Object doWork() throws Exception
        {
            return transactionService.getRetryingTransactionHelper().doInTransaction(
                    new RetryingTransactionCallback<Object>()
                    {
                        public Object execute()
                        {
                            commit(transferId);
                            return null;
                        }
                    }, false, true);
        }
    };
    AuthenticationUtil.runAs(actionRunAs, runAsUser);
}
 
Example 15
Project: alfresco-repository   File: AlfrescoPeople.java   Source Code and License 6 votes vote down vote up
@Override protected void before() throws Throwable
{
    // Set up required services
    ApplicationContext ctxt = getApplicationContext();
    final RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) ctxt.getBean("retryingTransactionHelper");
    
    transactionHelper.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        @Override public Void execute() throws Throwable
        {
            if (log.isDebugEnabled())
            {
                log.debug("Creating " + personCount + " users for test purposes...");
            }
            
            for (int i = 0; i < personCount; i++)
            {
                final String userName = GUID.generate();
                NodeRef personNode = createPerson(userName);
                usersPersons.put(userName, personNode);
            }
            
            return null;
        }
    });
}
 
Example 16
Project: alfresco-repository   File: Repository.java   Source Code and License 6 votes vote down vote up
/**
 * Gets the currently authenticated person
 * Includes any overlay authentication set by runas 
 * @return  person node ref
 */
public NodeRef getPerson()
{
    RetryingTransactionCallback<NodeRef> callback = new RetryingTransactionCallback<NodeRef>()
    {
        @Override
        public NodeRef execute() throws Throwable
        {
            NodeRef person = null;
            String currentUserName = AuthenticationUtil.getRunAsUser();
            if (currentUserName != null)
            {
                if (personService.personExists(currentUserName))
                {
                    person = personService.getPerson(currentUserName);
                }
            }
            return person;
        }
    };
    return retryingTransactionHelper.doInTransaction(callback, true);
}
 
Example 17
Project: alfresco-repository   File: RatingServiceIntegrationTest.java   Source Code and License 6 votes vote down vote up
@Test @RunAsUser(userName=USER_ONE_NAME) public void usersCantRateTheirOwnContent() throws Exception
{
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            // In the likes rating scheme, users can rate their own content.
            RATING_SERVICE.applyRating(testDoc_UserOne, 1, LIKES_SCHEME_NAME);
            
            // But fiveStar rating scheme disallows rating your own content.
            boolean expectedExceptionThrown = false;
            try
            {
                RATING_SERVICE.applyRating(testDoc_UserOne, 4, FIVE_STAR_SCHEME_NAME);
            } catch (RatingServiceException expected)
            {
                expectedExceptionThrown = true;
            }
            assertTrue(expectedExceptionThrown);
            
            return null;
        }
    });
}
 
Example 18
Project: alfresco-repository   File: UserUsageTrackingComponent.java   Source Code and License 6 votes vote down vote up
private int updateUsages(final List<Pair<NodeRef, Long>> userUsages)
{
    RetryingTransactionCallback<Integer> updateCurrentUsages = new RetryingTransactionCallback<Integer>()
    {
        public Integer execute() throws Throwable
        {
            int updateCount = 0;
            
            for (Pair<NodeRef, Long> userUsage : userUsages)
            {
                NodeRef personNodeRef = userUsage.getFirst();
                Long currentUsage = userUsage.getSecond();
                
                contentUsageImpl.setUserStoredUsage(personNodeRef, currentUsage);
                usageService.deleteDeltas(personNodeRef);
                
                updateCount++;
            }
            return updateCount;
        }
    };
    
    // execute in READ-WRITE txn
    return transactionService.getRetryingTransactionHelper().doInTransaction(updateCurrentUsages, false);
}
 
Example 19
Project: alfresco-repository   File: ReadPermissionTest.java   Source Code and License 6 votes vote down vote up
protected void buildContainers(final String username, final String permission)
{
	runAs("admin");
	
	RetryingTransactionCallback<Void> cb = new RetryingTransactionCallback<Void>()
	{
		public Void execute() throws Throwable
		{
			int i = 0;
			String namePrefix = "simple" + System.currentTimeMillis();

	        NodeRef n1 = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{test}01"),
	                ContentModel.TYPE_CONTAINER).getChildRef();
	        permissionService.setPermission(n1, username, permission, true);

			return null;
		}
	};
	retryingTransactionHelper.doInTransaction(cb, false, false);
}
 
Example 20
Project: alfresco-repository   File: ImporterActionExecuterTest.java   Source Code and License 6 votes vote down vote up
@AfterClass
public static void tearDown()
{
    try
    {
        serviceRegistry.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
        {
            public Void execute()
            {
                if (storeRef != null)
                {
                    nodeService.deleteStore(storeRef);
                }
                return null;
            }
        });
    }
    finally
    {
        AuthenticationUtil.clearCurrentSecurityContext();
    }
}
 
Example 21
Project: alfresco-repository   File: RetryingTransactionHelperTest.java   Source Code and License 6 votes vote down vote up
/**
 * Checks nesting of two transactions with <code>requiresNew == false</code>
 */
public void testNestedWithPropagation()
{
    RetryingTransactionCallback<Long> callback = new RetryingTransactionCallback<Long>()
    {
        public Long execute() throws Throwable
        {
            RetryingTransactionCallback<Long> callbackInner = new RetryingTransactionCallback<Long>()
            {
                public Long execute() throws Throwable
                {
                    incrementCheckValue();
                    incrementCheckValue();
                    return getCheckValue();
                }
            };
            txnHelper.doInTransaction(callbackInner, false, false);
            incrementCheckValue();
            incrementCheckValue();
            return getCheckValue();
        }
    };
    long checkValue = txnHelper.doInTransaction(callback);
    assertEquals("Nesting requiresNew==false didn't work", 4, checkValue);
}
 
Example 22
Project: alfresco-repository   File: AuditDAOTest.java   Source Code and License 6 votes vote down vote up
/**
 * Ensure that only the correct application's audit entries are deleted.
 * @throws Exception 
 */
public void testAuditDeleteEntriesForApplication() throws Exception
{
    final String app1 = doAuditEntryImpl(6);
    final String app2 = doAuditEntryImpl(18);
    
    final AuditQueryCallbackImpl resultsCallback = new AuditQueryCallbackImpl();
    
    RetryingTransactionCallback<Void> deletedCallback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            Long app1Id = auditDAO.getAuditApplication(app1).getId();
            auditDAO.deleteAuditEntries(app1Id, null, null);
            // There should be no entries for app1
            // but still entries for app2
            auditDAO.findAuditEntries(resultsCallback, new AuditQueryParameters(), Integer.MAX_VALUE);
            assertEquals("All entries should have been deleted from app1", 0, resultsCallback.numEntries(app1));
            assertEquals("No entries should have been deleted from app2", 18, resultsCallback.numEntries(app2));
            return null;
        }
    };
    txnHelper.doInTransaction(deletedCallback);
}
 
Example 23
Project: alfresco-repository   File: ActivitiSpringTransactionTest.java   Source Code and License 6 votes vote down vote up
/**
 * Start a process and then trigger a rollback by throwing an exception in Alfresco NodeService.
 * Check that the process instance was rolled back.
 */
public void testRollbackFromActiviti()
{
    RetryingTransactionCallback<Void> callback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            nodeService.addAspect(workingNodeRef, ASPECT, null);
            assertTrue("The node should have the aspect!", nodeService.hasAspect(workingNodeRef, ASPECT));
            try
            {
                runtime.signal("Fake Id");
                fail("Should throw an Exception here!");
            }
            catch (ActivitiException e)
            {
                // Expected, but absorbed
            }
            return null;
        }
    };
    txnHelper.doInTransaction(callback);
    assertFalse("The node should not have the aspect!", nodeService.hasAspect(workingNodeRef, ASPECT));
}
 
Example 24
Project: alfresco-repository   File: SOLRTrackingComponentTest.java   Source Code and License 6 votes vote down vote up
private void getNodeMetaData(final NodeMetaDataParameters params, final MetaDataResultsFilter filter, final SOLRTest bt)
{
    bt.clearNodesMetaData();

    long startTime = System.currentTimeMillis();
    txnHelper.doInTransaction(new RetryingTransactionCallback<Void>()
            {
        @Override
        public Void execute() throws Throwable
        {
            solrTrackingComponent.getNodesMetadata(params, filter, bt);
            return null;
        }
            }, true, true);
    long endTime = System.currentTimeMillis();

    bt.runNodeMetaDataChecks(params.getMaxResults());

    logger.debug("Got " + bt.getActualNodeMetaDataCount() + " node metadatas in " + (endTime - startTime) + " ms");
}
 
Example 25
Project: alfresco-repository   File: MimetypeDAOTest.java   Source Code and License 6 votes vote down vote up
public void testCreateWithRollback() throws Exception
{
    final String mimetype = GUID.generate();
    // Create a mimetype
    RetryingTransactionCallback<Pair<Long, String>> callback = new RetryingTransactionCallback<Pair<Long, String>>()
    {
        public Pair<Long, String> execute() throws Throwable
        {
            get(mimetype, true, true);
            // Now force a rollback
            throw new RuntimeException("Forced");
        }
    };
    try
    {
        txnHelper.doInTransaction(callback);
        fail("Transaction didn't roll back");
    }
    catch (RuntimeException e)
    {
        // Expected
    }
    // Check that it doesn't exist
    get(mimetype, false, false);
}
 
Example 26
Project: alfresco-repository   File: CifsHelper.java   Source Code and License 5 votes vote down vote up
public ContentFileInfo getFileInformation(final NodeRef nodeRef, final boolean readOnly, final boolean lockedFilesAsOffline) throws FileNotFoundException
{
    RetryingTransactionCallback<ContentFileInfo> cb =  new RetryingTransactionCallback<ContentFileInfo>()
    {
        /**
         * Perform a set of commands as a unit of transactional work.
         *
         * @return              Return the result of the unit of work
         * @throws IOException
         */
        public ContentFileInfo execute() throws IOException
        {
            try
            {
            	return getFileInformationImpl(nodeRef, readOnly, lockedFilesAsOffline);
            }
            catch (FileNotFoundException e)
            {
                // Ensure original checked IOExceptions get propagated
                throw new PropagatingException(e);
            }
        }
    };
    
    try
    {
        return getRetryingTransactionHelper().doInTransaction(cb, true);
    }
    catch(PropagatingException pe)
    {          
        // Unwrap checked exceptions
        throw (FileNotFoundException) pe.getCause();
    }
	
}
 
Example 27
Project: alfresco-repository   File: QNameDAOTest.java   Source Code and License 5 votes vote down vote up
public void testUpdateNamespace() throws Exception
{
    // Create a namespace
    final String uri = GUID.generate();
    Pair<Long, String> namespacePair = getNamespace(uri, true, true);
    // Use namespace in a QName
    QName qnameOld = QName.createQName(uri, GUID.generate());
    Pair<Long, QName> qnameOldPair = getQName(qnameOld, true, true);
    // Now update it
    final String uri2 = GUID.generate();
    RetryingTransactionCallback<Void> callback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            qnameDAO.updateNamespace(uri, uri2);
            return null;
        }
    };
    transactionService.getRetryingTransactionHelper().doInTransaction(callback);
    
    // Make sure that the old QName is gone (checks caching)
    getQName(qnameOld, false, false);
    
    // The new QName should be there
    QName qnameNew = QName.createQName(uri2, qnameOld.getLocalName());
    getQName(qnameNew, false, true);
    
    // Should be able to create the original namespace again
    Pair<Long, String> namespacePairAgain = getNamespace(uri, true, true);
    assertNotSame("Should have a new namespace ID", namespacePair.getFirst(), namespacePairAgain.getFirst());
}
 
Example 28
Project: alfresco-repository   File: DictionaryRepositoryBootstrap.java   Source Code and License 5 votes vote down vote up
/**
 * Initialise - after bootstrap of schema and tenant admin service
 */
public void init()
{
    PropertyCheck.mandatory(this, "dictionaryDAO", dictionaryDAO);
    PropertyCheck.mandatory(this, "contentService", contentService);
    PropertyCheck.mandatory(this, "nodeService", nodeService);
    PropertyCheck.mandatory(this, "tenantAdminService", tenantAdminService);
    PropertyCheck.mandatory(this, "namespaceService", namespaceService);
    PropertyCheck.mandatory(this, "messageService", messageService);
    PropertyCheck.mandatory(this, "transactionService", transactionService);
    PropertyCheck.mandatory(this, "policyComponent", policyComponent);
    
    if(onLoadDynamicModelDelegate == null)
    {
        onLoadDynamicModelDelegate = policyComponent.registerClassPolicy(DynamicModelPolicies.OnLoadDynamicModel.class);
    }
    
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Object>()
    {
        public Object execute() throws Exception
        {
            onDictionaryInit();
            initMessages();
            
            return (Object)null;
        }
    }, transactionService.isReadOnly(), false);
}
 
Example 29
Project: alfresco-repository   File: CheckOutCheckInServiceImplTest.java   Source Code and License 5 votes vote down vote up
/**
 * On setup in transaction implementation
 */
@Override
protected void onSetUpInTransaction() 
    throws Exception 
{
    // Set the services
    this.cociService = (CheckOutCheckInService)this.applicationContext.getBean("checkOutCheckInService");
    this.contentService = (ContentService)this.applicationContext.getBean("contentService");
    this.versionService = (VersionService)this.applicationContext.getBean("versionService");
    this.authenticationService = (MutableAuthenticationService)this.applicationContext.getBean("authenticationService");
    this.lockService = (LockService)this.applicationContext.getBean("lockService");
    this.transactionService = (TransactionService)this.applicationContext.getBean("transactionComponent");
    this.permissionService = (PermissionService)this.applicationContext.getBean("permissionService");
    this.copyService = (CopyService)this.applicationContext.getBean("copyService");
    this.personService = (PersonService) this.applicationContext.getBean("PersonService");
    ServiceRegistry serviceRegistry = (ServiceRegistry) this.applicationContext.getBean("ServiceRegistry");
    this.fileFolderService = serviceRegistry.getFileFolderService();
    this.nodeService = serviceRegistry.getNodeService();
    
    // Authenticate as system to create initial test data set
    this.authenticationComponent = (AuthenticationComponent)this.applicationContext.getBean("authenticationComponent");
    authenticationComponent.setSystemUserAsCurrentUser();
    
    RetryingTransactionCallback<Void> processInitWork = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            initTestData();
            return null;
        }
    };
    // do the init test data in a new retrying transaction because
    // there may be problems with the DB that needs to be retried; 
    // That is how Alfresco works, it relies on optimistic locking and retries
    transactionService.getRetryingTransactionHelper().doInTransaction(processInitWork, false, true);

}
 
Example 30
Project: alfresco-repository   File: AclCrudDAOTest.java   Source Code and License 5 votes vote down vote up
private void updateAuth(final String before, final String after) throws Exception
{
    RetryingTransactionCallback<Void> callback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            aclCrudDAO.renameAuthority(before, after);
            return null;
        }
    };
    txnHelper.doInTransaction(callback);
}
 
Example 31
Project: alfresco-repository   File: SOLRTrackingComponentTest.java   Source Code and License 5 votes vote down vote up
/**
 * Call {@link SOLRTrackingComponent#getAcls(List, Long, int)} in a transaction
 */
@SuppressWarnings("unused")
private List<Acl> getAcls(final List<Long> aclChangeSetIds, final Long minAclId, final int maxResults)
{
    RetryingTransactionCallback<List<Acl>> callback = new RetryingTransactionCallback<List<Acl>>()
    {
        @Override
        public List<Acl> execute() throws Throwable
        {
            return solrTrackingComponent.getAcls(aclChangeSetIds, minAclId, maxResults);
        }
    };
    return transactionService.getRetryingTransactionHelper().doInTransaction(callback, true);
}
 
Example 32
Project: alfresco-repository   File: DbNodeServiceImplTest.java   Source Code and License 5 votes vote down vote up
private void executeAndCheck(NodeRef nodeRef, RetryingTransactionCallback<Object> callback) throws Throwable
{
    UserTransaction txn = txnService.getUserTransaction();
    txn.begin();
    
    NodeRef.Status currentStatus = nodeService.getNodeStatus(nodeRef);
    assertNotNull(currentStatus);
    String currentTxnId = AlfrescoTransactionSupport.getTransactionId();
    assertNotNull(currentTxnId);
    assertNotSame(currentTxnId, currentStatus.getChangeTxnId());
    try
    {
        callback.execute();
        // get the status
        NodeRef.Status newStatus = nodeService.getNodeStatus(nodeRef);
        assertNotNull(newStatus);
        // check
        assertEquals("Change didn't update status", currentTxnId, newStatus.getChangeTxnId());
        
        // Make sure we can pre-load the node i.e. nodes in all state need to be pre-loadable
        // See CLOUD-1807
        Long nodeId = newStatus.getDbId();
        nodeDAO.getParentAssocs(nodeId, null, null, null, new DummyChildAssocRefQueryCallback());
        nodeDAO.cacheNodesById(Collections.singletonList(nodeId));
        
        txn.commit();
    }
    catch (Throwable e)
    {
        try { txn.rollback(); } catch (Throwable ee) {}
        throw e;
    }
}
 
Example 33
Project: alfresco-repository   File: LinksServiceImplTest.java   Source Code and License 5 votes vote down vote up
private static void createUser(final String userName)
{
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
       @Override
       public Void execute() throws Throwable
       {
          if (!AUTHENTICATION_SERVICE.authenticationExists(userName))
          {
             AUTHENTICATION_SERVICE.createAuthentication(userName, "PWD".toCharArray());
          }

          if (!PERSON_SERVICE.personExists(userName))
          {
             PropertyMap ppOne = new PropertyMap();
             ppOne.put(ContentModel.PROP_USERNAME, userName);
             ppOne.put(ContentModel.PROP_FIRSTNAME, "firstName");
             ppOne.put(ContentModel.PROP_LASTNAME, "lastName");
             ppOne.put(ContentModel.PROP_EMAIL, "[email protected]");
             ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");

             PERSON_SERVICE.createPerson(ppOne);
          }

          return null;
       }
    });
}
 
Example 34
Project: alfresco-repository   File: SOLRDAOTest.java   Source Code and License 5 votes vote down vote up
private List<Acl> getAcls(final List<Long> aclChangeSetIds, final Long minAclId, final int maxResults)
{
    return transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<List<Acl>>()
    {
        @Override
        public List<Acl> execute() throws Throwable
        {
            return solrDAO.getAcls(aclChangeSetIds, minAclId, maxResults);
        }
    }, true);
}
 
Example 35
Project: alfresco-repository   File: AclCrudDAOTest.java   Source Code and License 5 votes vote down vote up
private void deleteAclChangeSet(final Long aclChangeSetId) throws Exception
{
    RetryingTransactionCallback<Void> callback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            aclCrudDAO.deleteAclChangeSet(aclChangeSetId);
            return null;
        }
    };
    txnHelper.doInTransaction(callback);
}
 
Example 36
Project: alfresco-repository   File: TemporaryNodes.java   Source Code and License 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 37
Project: alfresco-repository   File: UpdateTagScopesActionExecuterTest.java   Source Code and License 5 votes vote down vote up
@Before
@Override
public void setUp() throws Exception
{
    applicationContext = ApplicationContextHelper.getApplicationContext();
    final ServiceRegistry registry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY);

    nodeService = registry.getNodeService();
    actionService = registry.getActionService();
    actionExecuter = (UpdateTagScopesActionExecuter) applicationContext.getBean(UPDATE_TAGSCOPE_ACTION_EXECUTER_BEAN_NAME);
    taggingService = registry.getTaggingService();
    fileFolderService = registry.getFileFolderService();
    transactionService = registry.getTransactionService();
    actionTrackingService = (ActionTrackingService) applicationContext.getBean(ACTION_TRACKING_SERVICE_BEAN_NAME);

    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    expectedTagScopes = new LinkedList<NodeRef>();
    testTags = new LinkedList<String>();

    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            createTestContent(registry, expectedTagScopes);
            return null;
        }
    }, false, true);

    waitForTagScopeUpdate();

    transaction = transactionService.getUserTransaction();
    transaction.begin();
}
 
Example 38
Project: alfresco-repository   File: DiscussionServiceImplTest.java   Source Code and License 5 votes vote down vote up
/**
 * Deletes the specified NodeRefs, if they exist.
 * @param nodesToDelete List<NodeRef>
 */
private static void performDeletionOfNodes(final List<NodeRef> nodesToDelete)
{
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
       @Override
       public Void execute() throws Throwable
       {
          AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER);

          for (NodeRef node : nodesToDelete)
          {
             if (NODE_SERVICE.exists(node))
             {
                // st:site nodes can only be deleted via the SiteService
                if (NODE_SERVICE.getType(node).equals(SiteModel.TYPE_SITE))
                {

                   SiteInfo siteInfo = SITE_SERVICE.getSite(node);
                   SITE_SERVICE.deleteSite(siteInfo.getShortName());
                }
                else
                {
                   NODE_SERVICE.deleteNode(node);
                }
             }
          }

          return null;
       }
    });
}
 
Example 39
Project: alfresco-repository   File: ConcurrentNodeServiceTest.java   Source Code and License 5 votes vote down vote up
protected void setUp() throws Exception
{
    ctx = ApplicationContextHelper.getApplicationContext();
    DictionaryDAO dictionaryDao = (DictionaryDAO) ctx.getBean("dictionaryDAO");
    // load the system model
    ClassLoader cl = BaseNodeServiceTest.class.getClassLoader();
    InputStream modelStream = cl.getResourceAsStream("alfresco/model/systemModel.xml");
    assertNotNull(modelStream);
    M2Model model = M2Model.createModel(modelStream);
    dictionaryDao.putModel(model);
    // load the test model
    modelStream = cl.getResourceAsStream("org/alfresco/repo/node/BaseNodeServiceTest_model.xml");
    assertNotNull(modelStream);
    model = M2Model.createModel(modelStream);
    dictionaryDao.putModel(model);

    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    nodeService = serviceRegistry.getNodeService();
    nodeDAO = (NodeDAO) ctx.getBean("nodeDAO");
    transactionService = serviceRegistry.getTransactionService();
    authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");

    this.authenticationComponent.setSystemUserAsCurrentUser();

    // create a first store directly
    RetryingTransactionCallback<Object> createRootNodeCallback =  new RetryingTransactionCallback<Object>()
    {
        public Object execute() throws Exception
        {
            StoreRef storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_"
                    + System.currentTimeMillis());
            rootNodeRef = nodeService.getRootNode(storeRef);
            return null;
        }
    };
    transactionService.getRetryingTransactionHelper().doInTransaction(createRootNodeCallback);
}
 
Example 40
Project: alfresco-repository   File: RepoAdminServiceImplTest.java   Source Code and License 5 votes vote down vote up
public void run()
{
    try
    {
        AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
        
        transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Object>()
        {
            public Object execute() throws Throwable
            {
                if (opType == 1)
                {
                    // Deploy model
                    String model = MODEL_MKR_XML.replace(MKR, i+"");
                    InputStream modelStream = new ByteArrayInputStream(model.getBytes("UTF-8"));
                    repoAdminService.deployModel(modelStream, modelPrefix+i);
                    
                    logger.info("["+i+"] Deploying - test model: "+modelPrefix+i);
                }
                else if (opType == 2)
                {
                    // Undeploy model
                    repoAdminService.undeployModel(modelPrefix+i);
                    
                    logger.info("["+i+"] Undeployed - test model: "+modelPrefix+i);
                }
                
                return null;
            }
        });
    }
    catch (Throwable t)
    {
        StringWriter sw = new StringWriter();
        t.printStackTrace(new PrintWriter(sw));
        errorStackTrace = sw.toString();
        
        logger.error("["+i+"] Failed to "+(opType == 1 ? "deploy" : "undeploy")+" test model: "+t);
    }
}
 
Example 41
Project: alfresco-repository   File: SiteServiceImplTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test for duplicate site exception where the duplicate is a private site.
 * 
 * @throws Exception
 */
public void testETHREEOH_2133() throws Exception
{
    RetryingTransactionCallback<Object> work = new RetryingTransactionCallback<Object>()
    {

        @Override
        public Object execute() throws Throwable
        {
            // Test for duplicate site error with a private site
            String siteShortName = "wibble" + UUID.randomUUID();
            siteService.createSite(TEST_SITE_PRESET, siteShortName, TEST_TITLE, TEST_DESCRIPTION, SiteVisibility.PRIVATE);

            authenticationComponent.setCurrentUser(USER_THREE);

            try
            {
                siteService.createSite(TEST_SITE_PRESET, siteShortName, TEST_TITLE, TEST_DESCRIPTION, SiteVisibility.PRIVATE);
                fail("Shouldn't allow duplicate site short names.");
            }
            catch (AlfrescoRuntimeException exception)
            {
                // Expected
            }

            authenticationComponent.setSystemUserAsCurrentUser();
            siteService.deleteSite(siteShortName);
            
            return null;
        }
    };
    endTransaction();
    transactionService.getRetryingTransactionHelper().doInTransaction(work);
    startNewTransaction();

}
 
Example 42
Project: alfresco-repository   File: PropertyValueDAOTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPropertyDateValue() throws Exception
{
    final Date dateValue = ISO8601DateFormat.parse("1936-08-04T23:37:25.793Z");
    final Date dateValueBack = ISO8601DateFormat.parse("1936-08-04T00:00:00.000Z");
    RetryingTransactionCallback<Pair<Long, Date>> createValueCallback = new RetryingTransactionCallback<Pair<Long, Date>>()
    {
        public Pair<Long, Date> execute() throws Throwable
        {
            return propertyValueDAO.getOrCreatePropertyDateValue(dateValue);
        }
    };
    final Pair<Long, Date> entityPair = txnHelper.doInTransaction(createValueCallback, false);
    assertNotNull(entityPair);
    assertEquals(dateValueBack, entityPair.getSecond());
    
    RetryingTransactionCallback<Pair<Long, Date>> getValueCallback = new RetryingTransactionCallback<Pair<Long, Date>>()
    {
        public Pair<Long, Date> execute() throws Throwable
        {
            return propertyValueDAO.getPropertyDateValue(dateValue);
        }
    };
    final Pair<Long, Date> entityPairCheck = txnHelper.doInTransaction(getValueCallback, false);
    assertNotNull(entityPairCheck);
    assertEquals(entityPair, entityPairCheck);
}
 
Example 43
Project: alfresco-repository   File: SOLRDAOTest.java   Source Code and License 5 votes vote down vote up
private List<AclChangeSet> getAclChangeSets(
        final Long minAclChangeSetId, final Long fromCommitTime,
        final Long maxAclChangeSetId, final Long toCommitTime,
        final int maxResults)
{
    return transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<List<AclChangeSet>>()
    {
        @Override
        public List<AclChangeSet> execute() throws Throwable
        {
            return solrDAO.getAclChangeSets(minAclChangeSetId, fromCommitTime, maxAclChangeSetId, toCommitTime, maxResults);
        }
    }, true);
}
 
Example 44
Project: alfresco-repository   File: ImapFoldersPatch.java   Source Code and License 5 votes vote down vote up
@Override
protected String applyInternal() throws Exception
{
    checkCommonProperties();
    setUp();
    String msg = null;
    if (imapConfigFolderNodeRef == null)
    {
        // import the content
        final RunAsWork<Object> importRunAs = new RunAsWork<Object>()
        {
            public Object doWork() throws Exception
            {
                importImapConfig();
                importScripts();
                importEmailActions();
                return null;
            }
        };
        
        RetryingTransactionCallback<Object> cb = new RetryingTransactionCallback<Object>()
        {
            public Object execute() throws Throwable 
            {
                AuthenticationUtil.runAs(importRunAs, authenticationContext.getSystemUserName());
                return null;
            }
     
        };
        
        transactionHelper.doInTransaction(cb, false, true);
        msg = I18NUtil.getMessage(MSG_CREATED);
    }
    else
    {
        msg = I18NUtil.getMessage(MSG_EXISTS, imapConfigFolderNodeRef);
    }
    return msg;

}
 
Example 45
Project: alfresco-repository   File: AclCrudDAOTest.java   Source Code and License 5 votes vote down vote up
private void deletePermission(final long permissionId) throws Exception
{
    RetryingTransactionCallback<Void> callback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            aclCrudDAO.deletePermission(permissionId);
            return null;
        }
    };
    txnHelper.doInTransaction(callback);
}
 
Example 46
Project: alfresco-repository   File: TemporaryNodes.java   Source Code and License 5 votes vote down vote up
/**
 * 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 47
Project: alfresco-repository   File: SolrFacetServiceImplTest.java   Source Code and License 5 votes vote down vote up
@Test(expected=MissingFacetId.class)
public void reorderEmptyFacetIdsShouldFail() throws Exception
{
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        @Override public Void execute() throws Throwable
        {
            SOLR_FACET_SERVICE.reorderFacets(Collections.<String>emptyList());
            return null;
        }
    });
}
 
Example 48
Project: alfresco-repository   File: ActivitiSpringTransactionTest.java   Source Code and License 5 votes vote down vote up
/**
 * Checks nesting of two transactions with <code>requiresNew == true</code>
 */
public void testNestedWithoutPropogation()
{
    RetryingTransactionCallback<Void> callback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            ProcessInstance instance = runtime.startProcessInstanceByKey(PROC_DEF_KEY);
            final String id = instance.getId();
            
            ProcessInstance instanceInDb = findProcessInstance(id);
            assertNotNull("Can't read process instance in same transaction!", instanceInDb);
            RetryingTransactionCallback<Void> callbackInner = new RetryingTransactionCallback<Void>()
            {
                public Void execute() throws Throwable
                {
                    ProcessInstance instanceInDb2 = findProcessInstance(id);
                    assertNull("Should not be able to read process instance in inner transaction!", instanceInDb2);
                    return null;
                }
            };
            try
            {
                txnHelper.doInTransaction(callbackInner, false, true);
                return null;
            }
            finally
            {
                runtime.deleteProcessInstance(id, "FOr test");
            }
        }
    };
    txnHelper.doInTransaction(callback);
}
 
Example 49
Project: alfresco-repository   File: AbstractImapFolder.java   Source Code and License 5 votes vote down vote up
public T run(boolean readOnly)
{
    RetryingTransactionHelper txHelper = serviceRegistry.getTransactionService().getRetryingTransactionHelper();
    txHelper.setMaxRetries(MAX_RETRIES);
    txHelper.setReadOnly(readOnly);
    T result = txHelper.doInTransaction(
            new RetryingTransactionCallback<T>()
            {
                public T execute() throws Throwable
                {
                    return command();
                }
            }, readOnly);
    return result;
}
 
Example 50
Project: alfresco-repository   File: QNameDAOTest.java   Source Code and License 5 votes vote down vote up
private Pair<Long, QName> getQName(final QName qname, final boolean autoCreate, boolean expectSuccess)
{
    RetryingTransactionCallback<Pair<Long, QName>> callback = new RetryingTransactionCallback<Pair<Long, QName>>()
    {
        public Pair<Long, QName> execute() throws Throwable
        {
            Pair<Long, QName> qnamePair = null;
            if (autoCreate)
            {
                qnamePair = qnameDAO.getOrCreateQName(qname);
            }
            else
            {
                qnamePair = qnameDAO.getQName(qname);
            }
            return qnamePair;
        }
    };
    try
    {
        return txnHelper.doInTransaction(callback, !autoCreate, false);
    }
    catch (Throwable e)
    {
        if (expectSuccess)
        {
            // oops
            throw new RuntimeException("Expected to get qname '" + qname + "'.", e);
        }
        else
        {
            return null;
        }
    }
}
 
Example 51
Project: alfresco-repository   File: AclCrudDAOTest.java   Source Code and License 5 votes vote down vote up
private Permission createPermission(final PermissionReference permissionReference) throws Exception
{
    RetryingTransactionCallback<Permission> callback = new RetryingTransactionCallback<Permission>()
    {
        public Permission execute() throws Throwable
        {
            return aclCrudDAO.getOrCreatePermission(permissionReference);
        }
    };
    return txnHelper.doInTransaction(callback);
}
 
Example 52
Project: alfresco-remote-api   File: InvitationWebScriptTest.java   Source Code and License 5 votes vote down vote up
@Override
protected void tearDown() throws Exception
{
    super.tearDown();
    this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());

    RetryingTransactionCallback<Void> deleteCallback = new RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            personService.deletePerson(userOne);
            personService.deletePerson(userTwo);
            personService.deletePerson(userThree);
            return null;
        }
    };
    transactionService.getRetryingTransactionHelper().doInTransaction(deleteCallback);

    // Tidy-up any sites created during the execution of the test
    for (String shortName : this.createdSites)
    {
        sendRequest(new DeleteRequest(URL_SITES + "/" + shortName), 0);
    }

    // Clear the list
    this.createdSites.clear();
    // Clear the list
    this.createdInvitations.clear();
}
 
Example 53
Project: alfresco-repository   File: MetadataEncryptorTests.java   Source Code and License 5 votes vote down vote up
public void testWithEncryption()
{
    RetryingTransactionCallback<Void> encryptionWork = new RetryingTransactionCallback<Void>()
    {
        public Void execute()
        {
            NodeRef nodeRef1 = nodeService.createNode(
                    rootNodeRef,
                    ContentModel.ASSOC_CHILDREN,
                    QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, getName()),
                    ContentModel.TYPE_FOLDER, null).getChildRef();

            Map<QName, Serializable> allProperties = new PropertyMap();
            allProperties.put(ENCRYPTED_PROP_QNAME, "ABC");
            allProperties = metadataEncryptor.encrypt(allProperties);
            
            try
            {
             NodeRef nodeRef2 = nodeService.createNode(
             		nodeRef1,
                     ContentModel.ASSOC_CONTAINS,
                     QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, getName()),
                     ENCRYPTED_TYPE_QNAME, allProperties).getChildRef();
             assertNotNull(nodeRef2);

             Serializable encryptedPropertyValue = nodeService.getProperty(nodeRef2, ENCRYPTED_PROP_QNAME);
             Serializable decryptedPropertyValue = metadataEncryptor.decrypt(ENCRYPTED_PROP_QNAME, encryptedPropertyValue);
             assertEquals("ABC", decryptedPropertyValue);
            }
            //catch(IntegrityException e)
            catch(Throwable e)
            {
            	fail();
            }

            return null;
        }
    };
    transactionService.getRetryingTransactionHelper().doInTransaction(encryptionWork);
}
 
Example 54
Project: alfresco-repository   File: DiscussionServiceImplTest.java   Source Code and License 5 votes vote down vote up
private static void createUser(final String userName)
{
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
       @Override
       public Void execute() throws Throwable
       {
          if (!AUTHENTICATION_SERVICE.authenticationExists(userName))
          {
             AUTHENTICATION_SERVICE.createAuthentication(userName, "PWD".toCharArray());
          }

          if (!PERSON_SERVICE.personExists(userName))
          {
             PropertyMap ppOne = new PropertyMap();
             ppOne.put(ContentModel.PROP_USERNAME, userName);
             ppOne.put(ContentModel.PROP_FIRSTNAME, "firstName");
             ppOne.put(ContentModel.PROP_LASTNAME, "lastName");
             ppOne.put(ContentModel.PROP_EMAIL, "[email protected]");
             ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");

             PERSON_SERVICE.createPerson(ppOne);
          }

          return null;
       }
    });
}
 
Example 55
Project: alfresco-repository   File: RepoUsageComponentTest.java   Source Code and License 5 votes vote down vote up
/**
 * Helper to wrap in a txn
 */
private boolean updateUsage(final UsageType usageType)
{
    RetryingTransactionCallback<Boolean> getCallback = new RetryingTransactionCallback<Boolean>()
    {
        @Override
        public Boolean execute() throws Throwable
        {
            return repoUsageComponent.updateUsage(usageType);
        }
    };
    return transactionService.getRetryingTransactionHelper().doInTransaction(getCallback, false);
}
 
Example 56
Project: alfresco-repository   File: RatingServiceIntegrationTest.java   Source Code and License 5 votes vote down vote up
/** ALF-17861 */
@Test public void itIsPossibleToDefineCustomRatingSchemes() throws Exception
{
    // This is obviously only visible in test code.
    final String spinalTapScheme = "spinalTapRatingScheme";
    final QName rollupAspect = QName.createQName("http://www.alfresco.org/model/testratings/1.0", "spinalTapRatingSchemeRollups");
    final QName countProp = QName.createQName("http://www.alfresco.org/model/testratings/1.0", "spinalTapRatingSchemeCount");
    final QName totalProp = QName.createQName("http://www.alfresco.org/model/testratings/1.0", "spinalTapRatingSchemeTotal");
    
    RatingScheme spinalTap = RATING_SERVICE.getRatingScheme(spinalTapScheme);
    assertEquals(11.0f, spinalTap.getMaxRating(), 0.0001f);
    
    
    // So the rating scheme exists. Now to use it.
    // Apply a rating.
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        @Override public NodeRef execute() throws Throwable
        {
            RATING_SERVICE.applyRating(testDoc_UserOne, 11.0F, spinalTapScheme);
            return null;
        }
    });
    
    // Now we'll go back to the node and check that the rollups were calculated.
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        @Override public NodeRef execute() throws Throwable
        {
            assertTrue(NODE_SERVICE.hasAspect(testDoc_UserOne, rollupAspect));
            final int count = (Integer)NODE_SERVICE.getProperty(testDoc_UserOne, countProp);
            final float total = (Float)NODE_SERVICE.getProperty(testDoc_UserOne, totalProp);
            
            assertEquals(1, count);
            assertEquals("But this one goes to 11. See? 11.", 11, total, 0.1);
            return null;
        }
    });
}
 
Example 57
Project: alfresco-repository   File: Repository.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the Company Home. Note this is tenant-aware if the correct Cache is supplied.
 *  
 * @return  company home node ref
 */
public NodeRef getCompanyHome()
{
    NodeRef companyHomeRef = singletonCache.get(KEY_COMPANYHOME_NODEREF);
    if (companyHomeRef == null)
    {
        companyHomeRef = AuthenticationUtil.runAs(new RunAsWork<NodeRef>()
        {
            public NodeRef doWork() throws Exception
            {
                return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
                {
                    public NodeRef execute() throws Exception
                    {
                        List<NodeRef> refs = searchService.selectNodes(nodeService.getRootNode(companyHomeStore), companyHomePath, null, namespaceService, false);
                        if (refs.size() != 1)
                        {
                            throw new IllegalStateException("Invalid company home path: " + companyHomePath + " - found: " + refs.size());
                        }
                        return refs.get(0);
                    }
                }, true);
            }
        }, AuthenticationUtil.getSystemUserName());
        
        singletonCache.put(KEY_COMPANYHOME_NODEREF, companyHomeRef);
    }
    return companyHomeRef;
}
 
Example 58
Project: alfresco-repository   File: ScriptNodeTest.java   Source Code and License 5 votes vote down vote up
private void touchFileToTriggerPermissionCheck(final NodeRef noderef)
{
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            // We don't actually care about the path of the NodeRef.
            // We just want to access some state of the NodeRef that will throw an AccessDenied if the current user
            // doesn't have the correct permissions.
            NODE_SERVICE.getPath(noderef);
            
            return null;
        }
    });
}
 
Example 59
Project: alfresco-remote-api   File: SOLRWebScriptTest.java   Source Code and License 5 votes vote down vote up
private void buildTransactions6()
{
    txnHelper.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            PropertyMap props = new PropertyMap();
            props.put(ContentModel.PROP_NAME, "Container6");
            NodeRef container6 = nodeService.createNode(
                    rootNodeRef,
                    ContentModel.ASSOC_CHILDREN,
                    ContentModel.ASSOC_CHILDREN,
                    ContentModel.TYPE_FOLDER,
                    props).getChildRef();
            if(logger.isDebugEnabled())
            {
                logger.debug("container6 = " + container6);
            }
            
            for(int i = 0; i < 2000; i++)
            {
                FileInfo content1Info = fileFolderService.create(container6, "Content" + i, ContentModel.TYPE_CONTENT);
                NodeRef nodeRef = content1Info.getNodeRef();
                contents.add(nodeRef);
                
                if(i % 2 == 1)
                {
                    nodeService.addAspect(nodeRef, ContentModel.ASPECT_TEMPORARY, null);
                }
            }
            
            return null;
        }
    });
}
 
Example 60
Project: alfresco-repository   File: MultiTDemoTest.java   Source Code and License 5 votes vote down vote up
private void createTestAuthoritiesForTenant(final String[] uniqueGroupNames, final String userName)
{
    String tenantDomain = tenantService.getUserDomain(userName);

    // Create groups for tenant
    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
    {
        public Void doWork() throws Exception
        {
            transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
            {
                @Override
                public Void execute() throws Throwable
                {
                    // find person
                    NodeRef personNodeRef = personService.getPerson(userName);
                    NodeRef homeSpaceRef = (NodeRef) nodeService.getProperty(personNodeRef, ContentModel.PROP_HOMEFOLDER);
                    assertNotNull(homeSpaceRef);

                    for (int i = 0; i < uniqueGroupNames.length; i++)
                    {
                        authorityService.createAuthority(AuthorityType.GROUP, uniqueGroupNames[i]);
                        permissionService.setPermission(homeSpaceRef, "GROUP_" + uniqueGroupNames[i], "Consumer", true);
                    }

                    return null;
                }
            }, false);
            return null;
        }
    }, userName, tenantDomain);
}