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

The following are top voted examples for showing how to use org.alfresco.repo.transaction.RetryingTransactionHelper. 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-repository   File: EmailServiceImplTest.java   Source Code and License 7 votes vote down vote up
@Override
public void setUp() throws Exception
{  
    AuthenticationUtil.setRunAsUserSystem();
    nodeService = (NodeService)ctx.getBean("NodeService");
    assertNotNull("nodeService", nodeService);
    authorityService = (AuthorityService)ctx.getBean("AuthorityService");
    assertNotNull("authorityService", authorityService);
    ChildApplicationContextFactory emailSubsystem = (ChildApplicationContextFactory) ctx.getBean("InboundSMTP");
    assertNotNull("emailSubsystem", emailSubsystem);
    ApplicationContext emailCtx = emailSubsystem.getApplicationContext();
    emailService = (EmailService)emailCtx.getBean("emailService");       
    assertNotNull("emailService", emailService);
    personService = (PersonService)emailCtx.getBean("PersonService");       
    assertNotNull("personService", personService);     
    namespaceService = (NamespaceService)emailCtx.getBean("NamespaceService");       
    assertNotNull("namespaceService", namespaceService);
    searchService = (SearchService)emailCtx.getBean("SearchService");  
    assertNotNull("searchService", searchService);
    folderEmailMessageHandler = (FolderEmailMessageHandler) emailCtx.getBean("folderEmailMessageHandler");  
    assertNotNull("folderEmailMessageHandler", folderEmailMessageHandler);
    transactionHelper = (RetryingTransactionHelper) emailCtx.getBean("retryingTransactionHelper");
    assertNotNull("transactionHelper", transactionHelper);
}
 
Example 2
Project: alfresco-repository   File: CMMDownloadTestUtil.java   Source Code and License 7 votes vote down vote up
public CMMDownloadTestUtil(ApplicationContext ctx)
{
    this.transactionHelper = ctx.getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    this.contentService = ctx.getBean("contentService", ContentService.class);
    this.searchService = ctx.getBean("searchService", SearchService.class);
    this.nodeService = ctx.getBean("nodeService", NodeService.class);
    this.namespaceService = ctx.getBean("namespaceService", NamespaceService.class);
    this.downloadService = ctx.getBean("downloadService", DownloadService.class);
}
 
Example 3
Project: alfresco-remote-api   File: BaseCustomModelApiTest.java   Source Code and License 6 votes vote down vote up
@After
public void tearDown() throws Exception
{
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    for (final String user : users)
    {
        transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {
                deleteUser(user, null);
                return null;
            }
        });
    }
    users.clear();
    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example 4
Project: alfresco-repository   File: RemoteCredentialsServicesTest.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 5
Project: alfresco-repository   File: DiscussionServiceImplTest.java   Source Code and License 6 votes vote down vote up
private static void deleteTenant()
{
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
       @Override
       public Void execute() throws Throwable
       {
           // TODO: WARNING: HACK for ALF-19155: MT deleteTenant does not work
           //       PersonService prevents 'guest' authorities from being deleted
           {
               BehaviourFilter behaviourFilter = (BehaviourFilter) testContext.getBean("policyBehaviourFilter");
               behaviourFilter.disableBehaviour(ContentModel.TYPE_PERSON);
               behaviourFilter.disableBehaviour(ContentModel.ASPECT_UNDELETABLE);
           }
           TENANT_ADMIN_SERVICE.deleteTenant(TENANT_DOMAIN);
           return null;
       }
    });
}
 
Example 6
Project: alfresco-repository   File: ActionServiceImplTest.java   Source Code and License 6 votes vote down vote up
@Override
protected void onSetUpInTransaction() throws Exception
{
    super.onSetUpInTransaction();

    this.transactionHelper = (RetryingTransactionHelper)this.applicationContext.getBean("retryingTransactionHelper");

    // 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.nodeService.setProperty(
            this.nodeRef,
            ContentModel.PROP_CONTENT,
            new ContentData(null, MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, null));
    this.folder = this.nodeService.createNode(
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}testFolder"),
            ContentModel.TYPE_FOLDER).getChildRef();
    
    // Register the test executor, if needed
    SleepActionExecuter.registerIfNeeded(applicationContext);
}
 
Example 7
Project: alfresco-remote-api   File: NodesImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Node updateNode(String nodeId, Node nodeInfo, Parameters parameters)
{
    retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            NodeRef nodeRef = updateNodeImpl(nodeId, nodeInfo, parameters);
            ActivityInfo activityInfo =  getActivityInfo(getParentNodeRef(nodeRef), nodeRef);
            postActivity(Activity_Type.UPDATED, activityInfo, false);
            
            return null;
        }
    }, false, true);

    return retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Node>()
    {
        @Override
        public Node execute() throws Throwable
        {
            return getFolderOrDocument(nodeId, parameters);
        }
    }, false, false);
}
 
Example 8
Project: alfresco-repository   File: RemoteCredentialsServicesTest.java   Source Code and License 6 votes vote down vote up
/**
 * Deletes the specified NodeRefs, if they exist.
 * @param nodesToDelete
 */
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))
             {
                NODE_SERVICE.deleteNode(node);
             }
          }

          return null;
       }
    });
}
 
Example 9
Project: alfresco-repository   File: AbstractTransferProgressMonitor.java   Source Code and License 6 votes vote down vote up
public void logException(final String transferId, final Object obj, final Throwable ex)
{
    TransferDestinationReportWriter writer = getLogWriter(transferId);
    writer.writeComment(obj.toString());
    if (ex != null)
    {
        transactionService.getRetryingTransactionHelper().doInTransaction(
                new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
                {
                    public Void execute() throws Throwable
                    {
                        storeError(transferId, ex);
                        return null;
                    }
                }, false, true);
        writer.writeException(ex);
    }
}
 
Example 10
Project: alfresco-remote-api   File: QuickShareRestApiTest.java   Source Code and License 6 votes vote down vote up
@Override
public void tearDown() throws Exception
{
    super.tearDown();
    
    AuthenticationUtil.setFullyAuthenticatedUser(USER_ONE);
    
    transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            if (testNode != null && nodeService.exists(testNode))
            {
                nodeService.deleteNode(testNode);
            }
            return null;
        }
    });
    
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
    
    deleteUser(USER_ONE);
    deleteUser(USER_TWO);

    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example 11
Project: alfresco-repository   File: AbstractMimeMessage.java   Source Code and License 6 votes vote down vote up
protected void buildMessage(FileInfo fileInfo, ServiceRegistry serviceRegistry) throws MessagingException
{
    checkParameter(serviceRegistry, "ServiceRegistry");
    this.content = null;
    this.serviceRegistry = serviceRegistry;
    this.imapService = serviceRegistry.getImapService();
    this.messageFileInfo = fileInfo;
    this.isMessageInSitesLibrary = imapService.getNodeSiteContainer(messageFileInfo.getNodeRef()) != null ? true : false;
    RetryingTransactionHelper txHelper = serviceRegistry.getTransactionService().getRetryingTransactionHelper();
    txHelper.setMaxRetries(MAX_RETRIES);
    txHelper.setReadOnly(false);
    txHelper.doInTransaction(new RetryingTransactionCallback<Object>() {
        public Object execute() throws Throwable
        {
            buildMessageInternal();
            return null;
        }
    }, false);
    
}
 
Example 12
Project: alfresco-repository   File: AttachmentsExtractor.java   Source Code and License 6 votes vote down vote up
public void init()
{
    attachmentsFolderRef = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<NodeRef>()
    {
        public NodeRef doWork() throws Exception
        {
            RetryingTransactionHelper helper = serviceRegistry.getTransactionService().getRetryingTransactionHelper();
            helper.setForceWritable(true);
            RetryingTransactionCallback<NodeRef> getDescriptorCallback = new RetryingTransactionCallback<NodeRef>()
            {
                public NodeRef execute() 
                {
                    NodeRef attFolderRef = attachmentsFolder.getOrCreateFolderPath(serviceRegistry.getNamespaceService(), nodeService, serviceRegistry.getSearchService(), fileFolderService);
                    if (attachmentsExtractorMode!=null && attachmentsExtractorMode==AttachmentsExtractorMode.COMMON)
                    {
                       serviceRegistry.getPermissionService().setPermission(attFolderRef , PermissionService.ALL_AUTHORITIES, PermissionService.FULL_CONTROL, true);
                    }
                    return attFolderRef;
                }
            };
            return helper.doInTransaction(getDescriptorCallback, false, false);
        }
    }, AuthenticationUtil.getSystemUserName());
}
 
Example 13
Project: alfresco-repository   File: WorkflowDeployer.java   Source Code and License 6 votes vote down vote up
@Override
  protected void onBootstrap(ApplicationEvent event)
  {
  	RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
  	txnHelper.setForceWritable(true);
  	txnHelper.doInTransaction(new RetryingTransactionCallback<Object>() {

	@Override
	public Object execute() throws Throwable {
		// run as System on bootstrap
        return AuthenticationUtil.runAs(new RunAsWork<Object>()
        {
            public Object doWork()
            {
                init();
                return null;
            }
        }, AuthenticationUtil.getSystemUserName());
	}
  		
}, false, true);
      
      tenantAdminService.register(this);
  }
 
Example 14
Project: alfresco-repository   File: SubscriptionServiceActivitiesTest.java   Source Code and License 6 votes vote down vote up
@BeforeClass public static void setUp() throws Exception
{
    final ApplicationContext ctx = APP_CONTEXT_INIT.getApplicationContext();
    
    // Let's shut down the scheduler so that we aren't competing with the
    // scheduled versions of the post lookup and
    // feed generator jobs
    // Note that to ensure this test class can be run within a suite, that we do not want to actually 'shutdown' the scheduler.
    // It may be needed by other test classes and must be restored to life after this class has run.
    QUARTZ_SCHEDULER = ctx.getBean("schedulerFactory", Scheduler.class);
    QUARTZ_SCHEDULER.standby();
    
    // Get the required services
    subscriptionService = (SubscriptionService) ctx.getBean("SubscriptionService");
    personService = (PersonService) ctx.getBean("PersonService");
    siteService = (SiteService) ctx.getBean("SiteService");
    activityService = (ActivityService) ctx.getBean("activityService");
    nodeService = (NodeService) ctx.getBean("NodeService");
    contentService = (ContentService) ctx.getBean("ContentService");
    nodeArchiveService = (NodeArchiveService)ctx.getBean("nodeArchiveService");
    transactionHelper = (RetryingTransactionHelper) ctx.getBean("retryingTransactionHelper");
    
    ChildApplicationContextFactory activitiesFeed = (ChildApplicationContextFactory) ctx.getBean("ActivitiesFeed");
    ApplicationContext activitiesFeedCtx = activitiesFeed.getApplicationContext();
    postLookup = (PostLookup) activitiesFeedCtx.getBean("postLookup");
    feedGenerator = (FeedGenerator) activitiesFeedCtx.getBean("feedGenerator");
    
    LocalFeedTaskProcessor feedProcessor = (LocalFeedTaskProcessor) activitiesFeedCtx.getBean("feedTaskProcessor");
    
    List<String> templateSearchPaths = new ArrayList<String>(1);
    templateSearchPaths.add(TEST_TEMPLATES_LOCATION);
    feedProcessor.setTemplateSearchPaths(templateSearchPaths);
    feedProcessor.setUseRemoteCallbacks(false);
}
 
Example 15
Project: alfresco-repository   File: MultiTServiceImplTest.java   Source Code and License 6 votes vote down vote up
/**
 * Format of a valid domain string is "@[email protected]" 
 */
@Test
public void testIsTenantName()
{
    RetryingTransactionHelper.RetryingTransactionCallback<Void> work = new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {

    boolean result = tenantService.isTenantName(STRING);
    assertFalse("The string was reported as domain, but it is not", result);
    
    result = tenantService.isTenantName(STRING_WITH_EXISTENT_DOMAIN);
    assertTrue("The string was not reported as domain.", result);
            return null;
        }
    };
    transactionService.getRetryingTransactionHelper().doInTransaction(work);
}
 
Example 16
Project: alfresco-repository   File: CommentsTest.java   Source Code and License 6 votes vote down vote up
@BeforeClass public static void initBasicServices() throws Exception
{
    behaviourFilter = (BehaviourFilter)APP_CONTEXT_INIT.getApplicationContext().getBean("policyBehaviourFilter");
    contentService = (ContentService)APP_CONTEXT_INIT.getApplicationContext().getBean("ContentService");
    nodeService = (NodeService)APP_CONTEXT_INIT.getApplicationContext().getBean("NodeService");
    repositoryHelper = (Repository)APP_CONTEXT_INIT.getApplicationContext().getBean("repositoryHelper");
    siteService = (SiteService)APP_CONTEXT_INIT.getApplicationContext().getBean("SiteService");
    transactionHelper = (RetryingTransactionHelper)APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper");

    authenticationComponent = (AuthenticationComponent)APP_CONTEXT_INIT.getApplicationContext().getBean("authenticationComponent");
    commentService = (CommentService)APP_CONTEXT_INIT.getApplicationContext().getBean("commentService");
    authenticationService = (MutableAuthenticationService)APP_CONTEXT_INIT.getApplicationContext().getBean("AuthenticationService");
    personService = (PersonService)APP_CONTEXT_INIT.getApplicationContext().getBean("PersonService");
    postDAO = (ActivityPostDAO)APP_CONTEXT_INIT.getApplicationContext().getBean("postDAO");
    permissionServiceImpl = (PermissionServiceImpl)APP_CONTEXT_INIT.getApplicationContext().getBean("permissionServiceImpl");
    permissionModelDAO = (ModelDAO)APP_CONTEXT_INIT.getApplicationContext().getBean("permissionsModelDAO");
    lockService = (LockService)APP_CONTEXT_INIT.getApplicationContext().getBean("lockService");

    COMPANY_HOME = repositoryHelper.getCompanyHome();
}
 
Example 17
Project: alfresco-repository   File: NodeArchiveServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * This is the primary purge methd that all purge methods fall back on.  It isolates the delete
 * work in a new transaction.
 */
public void purgeArchivedNode(final NodeRef archivedNodeRef)
{
    RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
    RetryingTransactionCallback<Void> deleteCallback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Exception
        {
            if (!nodeService.exists(archivedNodeRef))
            {
                // Node has disappeared
                return null;
            }
            invokeBeforePurgeNode(archivedNodeRef);
            nodeService.deleteNode(archivedNodeRef);
            return null;
        }
    };
    txnHelper.doInTransaction(deleteCallback, false, true);
}
 
Example 18
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 19
Project: alfresco-repository   File: FileFolderPerformanceTester.java   Source Code and License 6 votes vote down vote up
@Override
public void setUp() throws Exception
{
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    retryingTransactionHelper = (RetryingTransactionHelper) ctx.getBean("retryingTransactionHelper");
    authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
    
    fileFolderService = serviceRegistry.getFileFolderService();
    searchService = serviceRegistry.getSearchService();
    namespaceService = serviceRegistry.getNamespaceService();
    nodeService = getNodeService();
    
    authenticate(USERNAME);
    
    rootFolderRef = getOrCreateRootFolder();
    
    dataFile = AbstractContentTransformerTest.loadQuickTestFile("txt");
}
 
Example 20
Project: alfresco-repository   File: UnitTestInProcessTransmitterImpl.java   Source Code and License 6 votes vote down vote up
public void sendContent(final Transfer transfer, final Set<ContentData> data)
{
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            String transferId = transfer.getTransferId();
    
            for(ContentData content : data)
            {
                String contentUrl = content.getContentUrl();
                String fileName = TransferCommons.URLToPartName(contentUrl);

                InputStream contentStream = getContentService().getRawReader(contentUrl).getContentInputStream();
                receiver.saveContent(transferId, fileName, contentStream);
            }
            return null;
        }
    }, false, true);
}
 
Example 21
Project: alfresco-repository   File: CustomModelRepoRestartTest.java   Source Code and License 6 votes vote down vote up
private void getCtxAndSetBeans()
{
    ApplicationContext ctx = ApplicationContextHelper.getApplicationContext();
    this.customModelService = ctx.getBean("customModelService", CustomModelService.class);
    this.transactionHelper = ctx.getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
}
 
Example 22
Project: alfresco-repository   File: ExecuteAllRulesActionExecuterTest.java   Source Code and License 6 votes vote down vote up
/**
 * Called at the beginning of all tests
 */
@Override
protected void onSetUpInTransaction() throws Exception
{
    this.checkOutCheckInService = (CheckOutCheckInService) this.applicationContext.getBean("checkOutCheckInService");
    this.nodeService = (NodeService)this.applicationContext.getBean("nodeService");
    this.ruleService = (RuleService)this.applicationContext.getBean("ruleService");
    this.actionService = (ActionService)this.applicationContext.getBean("actionService");
    transactionHelper = (RetryingTransactionHelper)applicationContext.getBean("retryingTransactionHelper");
    fileFolderService = applicationContext.getBean("fileFolderService", FileFolderService.class);
    contentService = applicationContext.getBean("contentService", ContentService.class);
    
    AuthenticationComponent authenticationComponent = (AuthenticationComponent)applicationContext.getBean("authenticationComponent");
    authenticationComponent.setCurrentUser(authenticationComponent.getSystemUserName());
    
    // Create the store and get the root node
    this.testStoreRef = this.nodeService.createStore(
            StoreRef.PROTOCOL_WORKSPACE, "Test_"
                    + System.currentTimeMillis());
    this.rootNodeRef = this.nodeService.getRootNode(this.testStoreRef);

    // Get the executer instance 
    this.executer = (ExecuteAllRulesActionExecuter)this.applicationContext.getBean(ExecuteAllRulesActionExecuter.NAME);
}
 
Example 23
Project: alfresco-repository   File: ActivitiTimerExecutionTest.java   Source Code and License 5 votes vote down vote up
/**
 * Delete the deployment, cascading all related processes/history
 */
private void cleanUp()
{
    transactionHelper .doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
        {
    		public Void execute() throws Throwable
    		{
    			try 
    			{
    				personManager.clearPeople();
    			}
    			finally
    			{
    				// Make sure process-definition is still deleted, even when clearing people fails.
    				ProcessDefinition procDef = activitiProcessEngine.getRepositoryService()
    				.createProcessDefinitionQuery()
    				.processDefinitionKey("testTimerTransaction")
    				.latestVersion()
    				.singleResult();
    				
    				if (procDef != null)
    				{
    					activitiProcessEngine.getRepositoryService().deleteDeployment(procDef.getDeploymentId(), true);
    				}
    			}
        		return null;
    		}
        });
}
 
Example 24
Project: alfresco-repository   File: AlfrescoRpcAuthenticator.java   Source Code and License 5 votes vote down vote up
/**
 * Does work in a transaction. This will be a writeable transaction unless the system is in read-only mode.
 * 
 * @param callback
 *            a callback that does the work
 * @return the result, or <code>null</code> if not applicable
 */
protected <T> T doInTransaction(RetryingTransactionHelper.RetryingTransactionCallback<T> callback)
{
    // Get the transaction service
    
    TransactionService txService = getTransactionService(); 
    
    // DEBUG
    
    if ( logger.isDebugEnabled())
        logger.debug("Using " + (txService.isReadOnly() ? "ReadOnly" : "Write") + " transaction");
    
    return txService.getRetryingTransactionHelper().doInTransaction(callback, txService.isReadOnly());
}
 
Example 25
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 26
Project: alfresco-repository   File: CalendarServiceImplTest.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 27
Project: alfresco-repository   File: HashPasswordTransactionListener.java   Source Code and License 5 votes vote down vote up
@Override
public void afterCommit()
{
    // get transaction helper and force it to be writable in case system is in read only mode
    RetryingTransactionHelper txHelper = transactionService.getRetryingTransactionHelper();
    txHelper.setForceWritable(true);
    txHelper.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            AuthenticationUtil.pushAuthentication();
            AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
            try
            {
                if (logger.isDebugEnabled())
                {
                    logger.debug("Re-hashing password for user: " + username);
                }
                
                // update the users password to force a new hash to be generated
                authenticationDao.updateUser(username, password);
                
                if (logger.isDebugEnabled())
                {
                    logger.debug("Password for user '" + username + "' has been re-hashed following login");
                }
                
                return null;
            }
            finally
            {
                AuthenticationUtil.popAuthentication();
            }
        }
    }, false, true);
}
 
Example 28
Project: alfresco-repository   File: UpgradePasswordHashWorker.java   Source Code and License 5 votes vote down vote up
/**
 * @param progress          the thread-safe progress
 */
private synchronized void doWork(UpgradePasswordHashWorkResult progress) throws Exception
{
    // Build batch processor
    BatchProcessWorkProvider<Long> workProvider = new UpgradePasswordHashWorkProvider(progress);
    BatchProcessWorker<Long> worker = new UpgradePasswordHashBatch(progress);
    RetryingTransactionHelper retryingTransactionHelper = transactionService.getRetryingTransactionHelper();
    retryingTransactionHelper.setForceWritable(true);

    //Create the QNames if they don't exist
    retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            qnameDAO.getOrCreateQName(ContentModel.PROP_PASSWORD_HASH);
            qnameDAO.getOrCreateQName(ContentModel.PROP_HASH_INDICATOR);
            return null;
        }
    }, false, true);

    BatchProcessor<Long> batchProcessor = new BatchProcessor<Long>(
            "UpgradePasswordHashWorker",
            retryingTransactionHelper,
            workProvider,
            threadCount,
            batchSize,
            ctx,
            logger,
            1000);
    batchProcessor.process(worker, true);
}
 
Example 29
Project: alfresco-repository   File: SOLRTrackingComponentTest.java   Source Code and License 5 votes vote down vote up
SOLRTest100Nodes(
    RetryingTransactionHelper txnHelper, FileFolderService fileFolderService,
    NodeDAO nodeDAO, QNameDAO qnameDAO, NodeService nodeService, DictionaryService dictionaryService,
    NodeRef rootNodeRef, String containerName, boolean doNodeChecks, boolean doMetaDataChecks)
    {
super(txnHelper, fileFolderService, nodeDAO, qnameDAO, nodeService, dictionaryService, rootNodeRef, containerName, doNodeChecks, doMetaDataChecks);
    }
 
Example 30
Project: alfresco-repository   File: RenditionServiceIntegrationTest.java   Source Code and License 5 votes vote down vote up
/**
 * This method performs an asynchronous rendition and calls back the result to the
 * provided callback object. It uses the provided latch to coordinate the JUnit and
 * the asynchronous action thread and uses the provided MutableString to send back
 * any error messages for JUnit reporting.
 * <P/>
 * This method blocks until the action service thread either completes its work
 * or times out.
 * 
 * @param callback
 * @param latch
 * @param failureMessage
 * @param nodeToRender
 * @throws InterruptedException
 */
private void performAsyncRendition(final NodeRef nodeToRender, final RenderCallback callback, CountDownLatch latch,
        final AsyncResultsHolder failureMessage) throws InterruptedException
{
    setComplete();
    endTransaction();
    
    transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            RenditionDefinition action = makeReformatAction(null, MimetypeMap.MIMETYPE_TEXT_PLAIN);
    
            action.setParameterValue(AbstractRenderingEngine.PARAM_MIME_TYPE, MimetypeMap.MIMETYPE_IMAGE_JPEG);
    
            renditionService.render(nodeToRender, action, callback);
            return null;
        }
    });
    
    // Now wait for the actionService thread to complete the rendering.
    // We'll arbitrarily timeout after 30 seconds, which should be plenty for the
    // action to execute.
    boolean endedNormally = latch.await(30, TimeUnit.SECONDS);
    
    String failedString = failureMessage.getValue();
    if (failedString != null)
    {
        fail(failedString);
    }
    if (endedNormally == false)
    {
        fail("ActionService thread took too long to perform rendering.");
    }
}
 
Example 31
Project: alfresco-repository   File: PersonServiceImpl.java   Source Code and License 5 votes vote down vote up
private void makeHomeFolderIfRequired(NodeRef person)
{
    if ((person != null) && (homeFolderCreationDisabled == false))
    {
        NodeRef homeFolder = DefaultTypeConverter.INSTANCE.convert(NodeRef.class, nodeService.getProperty(person, ContentModel.PROP_HOMEFOLDER));
        if (homeFolder == null)
        {
            final ChildAssociationRef ref = nodeService.getPrimaryParent(person);
            RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
            txnHelper.setForceWritable(true);
            boolean requiresNew = false;
            if (AlfrescoTransactionSupport.getTransactionReadState() != TxnReadState.TXN_READ_WRITE)
            {
                // We can be in a read-only transaction, so force a new transaction
                // Note that the transaction will *always* be in read-only mode if the server read-only veto is there 
                requiresNew = true;
            }
            txnHelper.doInTransaction(new RetryingTransactionCallback<Object>()
            {
                public Object execute() throws Throwable
                {
                    makeHomeFolderAsSystem(ref);
                    return null;
                }
            }, false, requiresNew);
        }
    }
}
 
Example 32
Project: alfresco-repository   File: PreferenceServiceImplTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass public static void initStaticData() throws Exception
{
    CONTENT_SERVICE           = APP_CONTEXT_INIT.getApplicationContext().getBean("ContentService", ContentService.class);
    PERSON_SERVICE            = APP_CONTEXT_INIT.getApplicationContext().getBean("PersonService", PersonService.class);
    PREFERENCE_SERVICE        = APP_CONTEXT_INIT.getApplicationContext().getBean("PreferenceService", PreferenceService.class);
    SCRIPT_SERVICE            = APP_CONTEXT_INIT.getApplicationContext().getBean("ScriptService", ScriptService.class);
    TRANSACTION_HELPER        = APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    
    Repository repositoryHelper = (Repository) APP_CONTEXT_INIT.getApplicationContext().getBean("repositoryHelper");
    COMPANY_HOME = repositoryHelper.getCompanyHome();
}
 
Example 33
Project: alfresco-remote-api   File: CustomModelImportTest.java   Source Code and License 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    authenticationService = getServer().getApplicationContext().getBean("AuthenticationService", MutableAuthenticationService.class);
    authorityService = getServer().getApplicationContext().getBean("AuthorityService", AuthorityService.class);
    personService = getServer().getApplicationContext().getBean("PersonService", PersonService.class);
    transactionHelper = getServer().getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    customModelService = getServer().getApplicationContext().getBean("customModelService", CustomModelService.class);

    AuthenticationUtil.clearCurrentSecurityContext();

    AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            createUser(NON_ADMIN_USER);
            createUser(CUSTOM_MODEL_ADMIN);

            if (!authorityService.getContainingAuthorities(AuthorityType.GROUP, CUSTOM_MODEL_ADMIN, true).contains(
                        CustomModelServiceImpl.GROUP_ALFRESCO_MODEL_ADMINISTRATORS_AUTHORITY))
            {
                authorityService.addAuthority(CustomModelServiceImpl.GROUP_ALFRESCO_MODEL_ADMINISTRATORS_AUTHORITY, CUSTOM_MODEL_ADMIN);
            }
            return null;
        }
    });
    AuthenticationUtil.setFullyAuthenticatedUser(CUSTOM_MODEL_ADMIN);
}
 
Example 34
Project: alfresco-remote-api   File: AbstractTestApi.java   Source Code and License 5 votes vote down vote up
@Before
public void setupTests() throws Exception
{
	TestFixture testFixture = getTestFixture(false);
	this.applicationContext = testFixture.getApplicationContext();
	this.repoService = testFixture.getRepoService();
	this.transactionHelper = (RetryingTransactionHelper)applicationContext.getBean("retryingTransactionHelper");
	
	HttpClientProvider httpClientProvider = (HttpClientProvider)applicationContext.getBean("httpClientProvider");
	
	UserDataService userDataService = new UserDataService()
	{
		@Override
		public UserData findUserByUserName(String userName)
		{
			UserData userData = new UserData();
			TestPerson person = getRepoService().getPerson(userName.toLowerCase());
			userData.setUserName(person.getId());
			userData.setPassword(person.getPassword());
			userData.setId(person.getId());
			return userData;
		}
	};
    AuthenticationDetailsProvider authenticationDetailsProvider = new UserAuthenticationDetailsProviderImpl(userDataService, "admin", "admin");
    AuthenticatedHttp authenticatedHttp = new AuthenticatedHttp(httpClientProvider, authenticationDetailsProvider);
	this.httpClient = new PublicApiHttpClient(TestFixture.HOST, TestFixture.PORT, TestFixture.CONTEXT_PATH,
			TestFixture.PUBLIC_API_SERVLET_NAME, authenticatedHttp);
    this.publicApiClient = new PublicApiClient(httpClient, userDataService);
}
 
Example 35
Project: alfresco-file-transfer-receiver   File: DbHelperImpl.java   Source Code and License 5 votes vote down vote up
public void createNodeInDB(final String nodeRef, final String parentNodeRef, final String path, final String name, 
        final String contentUrl, final boolean isFolder)
{
    RetryingTransactionHelper txHelper = transactionService.getRetryingTransactionHelper();
    txHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
        {
            public Void execute() throws Throwable
            {
                fileTransferInfoDAO.createFileTransferInfo(nodeRef, parentNodeRef, path, name,
                        contentUrl, isFolder, sourceRepoId);
                return null;
            }
        }, false, false);
}
 
Example 36
Project: alfresco-repository   File: TransferTreeWithCancelActionExecuter.java   Source Code and License 5 votes vote down vote up
@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef)
{
    TransferTarget target = serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction(
            new RetryingTransactionHelper.RetryingTransactionCallback<TransferTarget>()
    {
        public TransferTarget execute() throws Throwable
        {
            return TransferTestUtil.getTestTarget(transferService);
        }
    }, false, true);
    
    NodeCrawler crawler = new StandardNodeCrawlerImpl(serviceRegistry);
    crawler.setNodeFinders(new ChildAssociatedNodeFinder(ContentModel.ASSOC_CONTAINS));
    Set<NodeRef> nodes = crawler.crawl(actionedUponNodeRef);
    TransferDefinition td = new TransferDefinition();
    td.setNodes(nodes);
    transferService.transferAsync(target.getName(), td, new TransferCallback(){

        private String transferId;

        public void processEvent(TransferEvent event)
        {
            if (event instanceof TransferEventBegin) 
            {
                transferId = ((TransferEventBegin)event).getTransferId();
            }
            else if (event instanceof TransferEventCommittingStatus)
            {
                transferService.cancelAsync(transferId);
            }
        }
        
    });
}
 
Example 37
Project: alfresco-repository   File: AbstractTransferProgressMonitor.java   Source Code and License 5 votes vote down vote up
@Override
public TransferProgress getProgress(final String transferId) throws TransferException
{
    return transactionService.getRetryingTransactionHelper().doInTransaction(
            new RetryingTransactionHelper.RetryingTransactionCallback<TransferProgress>()
            {
                public TransferProgress execute() throws Throwable
                {
                    return getProgressInternal(transferId);
                }
            }, false, true);
}
 
Example 38
Project: alfresco-repository   File: AbstractTransferProgressMonitor.java   Source Code and License 5 votes vote down vote up
@Override
public void updateProgress(final String transferId, final int currPos, final int endPos) throws TransferException
{
    transactionService.getRetryingTransactionHelper().doInTransaction(
            new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
            {
                public Void execute() throws Throwable
                {
                    updateProgressInternal(transferId, currPos, endPos);
                    return null;
                }
            }, false, true);
}
 
Example 39
Project: alfresco-repository   File: RenditionServiceIntegrationTest.java   Source Code and License 5 votes vote down vote up
protected NodeRef performImageRendition(final Map<String, Serializable> parameterValues, final NodeRef imageToRender)
{
    final NodeRef newRenditionNode = transactionHelper
                .doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
                {
                    public NodeRef execute() throws Throwable
                    {
                        validateRenderingActionDefinition(ImageRenderingEngine.NAME);

                        // Create the rendering action.
                        RenditionDefinition action = renditionService.createRenditionDefinition(
                                    RESCALE_RENDER_DEFN_NAME, ImageRenderingEngine.NAME);

                        // Set the parameters. Can't call
                        // action.setParameterValues as we don't want
                        // to obliterate existing parameters such as the
                        // name
                        for (String s : parameterValues.keySet())
                        {
                            action.setParameterValue(s, parameterValues.get(s));
                        }

                        ChildAssociationRef renditionAssoc = renditionService.render(imageToRender, action);

                        validateRenditionAssociation(renditionAssoc, RESCALE_RENDER_DEFN_NAME);

                        return renditionAssoc.getChildRef();
                    }
                });
    return newRenditionNode;
}
 
Example 40
Project: alfresco-repository   File: AbstractTransferProgressMonitor.java   Source Code and License 5 votes vote down vote up
@Override
public final void updateStatus(final String transferId, final Status status) throws TransferException
{
    Status currentStatus = getProgress(transferId).getStatus();
    
    //If the transfer has already reached a terminal state then we don't allow any further change
    if (!TransferProgress.getTerminalStatuses().contains(currentStatus))
    {
        transactionService.getRetryingTransactionHelper().doInTransaction(
                new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
                {
                    public Void execute() throws Throwable
                    {
                        TransferDestinationReportWriter writer = getLogWriter(transferId);
                        writer.writeChangeState(status.toString());
                        updateStatusInternal(transferId, status);
                        //If the transfer has now reached a terminal state then the make sure that the log channel is
                        //closed for it (if one was open).
                        if (TransferProgress.getTerminalStatuses().contains(status))
                        {
                            log.debug("closing destination transfer report");
                            writer.endTransferReport();
                            transferLogWriters.remove(transferId);
                        }
                        return null;
                    }
                }, false, true);
    }
}
 
Example 41
Project: alfresco-remote-api   File: TestPublicApi128.java   Source Code and License 5 votes vote down vote up
@Before
public void setup()
{
	// note: we don't call super.setup() since we create our own test data here !
	
	// mixed case network
	this.time = System.currentTimeMillis();
	this.networkId = getNetworkId(networkPrefix, networkDomain);

       transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
       {
       	@SuppressWarnings("synthetic-access")
       	public Void execute() throws Throwable
       	{
   	        AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

   	        TestPublicApi128.this.mixedCaseNetwork = repoService.createNetwork(TestPublicApi128.this.networkId, true);
   	        TestPublicApi128.this.mixedCaseNetwork.create();

			// mixed case user
			PersonInfo personInfo = new PersonInfo("Bob", "Jones", TestPublicApi128.userId, "password", null, null, null, null, null, null, null);
			TestPublicApi128.this.person1 = mixedCaseNetwork.createUser(personInfo);

			return null;
       	}
       }, false, true);
}
 
Example 42
Project: alfresco-repository   File: VirtualStoreImpl.java   Source Code and License 5 votes vote down vote up
public VirtualFolderDefinition resolveVirtualFolderDefinition(final Reference reference)
            throws VirtualizationException
{
    ServiceRegistry serviceRegistry = ((AlfrescoEnviroment) environment).getServiceRegistry();
    RetryingTransactionHelper transactionHelper = serviceRegistry.getRetryingTransactionHelper();

    return transactionHelper.doInTransaction(new RetryingTransactionCallback<VirtualFolderDefinition>()
                                             {

                                                 @Override
                                                 public VirtualFolderDefinition execute() throws Throwable
                                                 {
                                                     NodeRef key = reference.toNodeRef();

                                                     Map<NodeRef, VirtualFolderDefinition> definitionsCache = TransactionalResourceHelper
                                                                 .getMap(VIRTUAL_FOLDER_DEFINITION);

                                                     VirtualFolderDefinition virtualFolderDefinition = definitionsCache
                                                                 .get(key);

                                                     if (virtualFolderDefinition == null)
                                                     {

                                                         virtualFolderDefinition = reference
                                                                     .execute(new ApplyTemplateMethod(environment));
                                                         definitionsCache.put(key,
                                                                              virtualFolderDefinition);
                                                     }

                                                     return virtualFolderDefinition;
                                                 }
                                             },
                                             true,
                                             false);
}
 
Example 43
Project: alfresco-repository   File: TenantInterpreter.java   Source Code and License 5 votes vote down vote up
public String interpretCommand(final String line) throws IOException
{
    String currentUserName = getCurrentUserName();
    if (hasAuthority(currentUserName))
    {
       RunAsWork<String> executeWork = new RunAsWork<String>()
       {
           public String doWork() throws Exception
           {
               RetryingTransactionCallback<String> txnWork = new RetryingTransactionCallback<String>()
               {
                   public String execute() throws Exception
                   {
                       return executeCommand(line);
                   }
               };

               // from Thor
               RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
               txnHelper.setMaxRetries(1);
               
               return txnHelper.doInTransaction(txnWork);
           }
       };
       return AuthenticationUtil.runAs(executeWork, AuthenticationUtil.SYSTEM_USER_NAME);
    }
    else
    {
        return("Error: User '"+ currentUserName + "' not authorised");
    }
}
 
Example 44
Project: alfresco-repository   File: ActionFormProcessorTest.java   Source Code and License 5 votes vote down vote up
public void testGenerateDefaultFormForActionWithNodeRefParam() throws Exception
{
    this.transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>() {
        @Override
        public Void execute() throws Throwable {
            Form form = formService.getForm(new Item(ActionFormProcessor.ITEM_KIND, "script"));

            // check a form got returned
            assertNotNull("Expecting form to be present", form);

            // get the fields into a Map
            Collection<FieldDefinition> fieldDefs = form.getFieldDefinitions();

            assertEquals("Wrong number of fieldDefs", 2, fieldDefs.size());
            Map<String, FieldDefinition> fieldDefMap = new HashMap<String, FieldDefinition>(fieldDefs.size());
            for (FieldDefinition fieldDef : fieldDefs) {
                fieldDefMap.put(fieldDef.getName(), fieldDef);
            }

            // First of all, we'll check the fields that come from the Action class.
            validateExecuteAsynchronouslyField(fieldDefMap);

            // One defined parameter for this action.
            PropertyFieldDefinition scriptRef = (PropertyFieldDefinition) fieldDefMap.get("script-ref");
            assertNotNull("'script-ref' field defn was missing.", scriptRef);
            assertEquals("script-ref", scriptRef.getName());
            assertEquals("Script", scriptRef.getLabel());
            assertEquals("script-ref", scriptRef.getDescription());
            assertEquals("text", scriptRef.getDataType());
            assertTrue(scriptRef.isMandatory());
            List<FieldConstraint> constraints = scriptRef.getConstraints();
            assertEquals(1, constraints.size());
            assertEquals("LIST", constraints.get(0).getType());

            return null;
        }
    });
}
 
Example 45
Project: alfresco-repository   File: BatchProcessor.java   Source Code and License 5 votes vote down vote up
/**
 * Instantiates a new batch processor.
 * 
 * @param processName
 *            the process name
 * @param retryingTransactionHelper
 *            the retrying transaction helper
 * @param workProvider
 *            the object providing the work packets
 * @param workerThreads
 *            the number of worker threads
 * @param batchSize
 *            the number of entries we process at a time in a transaction
 * @param applicationEventPublisher
 *            the application event publisher (may be <tt>null</tt>)
 * @param logger
 *            the logger to use (may be <tt>null</tt>)
 * @param loggingInterval
 *            the number of entries to process before reporting progress
 *            
 * @since 3.4 
 */
public BatchProcessor(
        String processName,
        RetryingTransactionHelper retryingTransactionHelper,
        BatchProcessWorkProvider<T> workProvider,
        int workerThreads, int batchSize,
        ApplicationEventPublisher applicationEventPublisher,
        Log logger,
        int loggingInterval)
{
    this.threadFactory = new TraceableThreadFactory();
    this.threadFactory.setNamePrefix(processName);
    this.threadFactory.setThreadDaemon(true);
    
    this.processName = processName;
    this.retryingTransactionHelper = retryingTransactionHelper;
    this.workProvider = workProvider;
    this.workerThreads = workerThreads;
    this.batchSize = batchSize;
    if (logger == null)
    {
        this.logger = LogFactory.getLog(this.getClass());
    }
    else
    {
        this.logger = logger;
    }
    this.loggingInterval = loggingInterval;
    
    // Let the (enterprise) monitoring side know of our presence
    if (applicationEventPublisher != null)
    {
        applicationEventPublisher.publishEvent(new BatchMonitorEvent(this));
    }
}
 
Example 46
Project: alfresco-repository   File: SOLRTrackingComponentTest.java   Source Code and License 5 votes vote down vote up
SOLRTest5(
    RetryingTransactionHelper txnHelper, FileFolderService fileFolderService,
    NodeDAO nodeDAO, QNameDAO qnameDAO, NodeService nodeService, DictionaryService dictionaryService,
    NodeRef rootNodeRef, String containerName, boolean doNodeChecks, boolean doMetaDataChecks)
    {
super(txnHelper, fileFolderService, nodeDAO, qnameDAO, nodeService, dictionaryService, rootNodeRef, containerName, doNodeChecks, doMetaDataChecks);
    }
 
Example 47
Project: alfresco-repository   File: RenditionServiceIntegrationTest.java   Source Code and License 5 votes vote down vote up
public void testRenderFreeMarkerTemplateOneTransaction() throws Exception
{
    this.setComplete();
    this.endTransaction();
    final QName renditionName = QName.createQName(NamespaceService.RENDITION_MODEL_1_0_URI,
                FreemarkerRenderingEngine.NAME);

    this.renditionNode = transactionHelper
                .doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
                {
                    public NodeRef execute() throws Throwable
                    {
                        // create test model
                        RenditionDefinition definition = renditionService.createRenditionDefinition(renditionName,
                                    FreemarkerRenderingEngine.NAME);
                        definition.setParameterValue(FreemarkerRenderingEngine.PARAM_TEMPLATE_NODE,
                                    nodeWithFreeMarkerContent);
                        ChildAssociationRef renditionAssoc = renditionService
                                    .render(nodeWithDocContent, definition);
                        assertNotNull("The rendition association was null", renditionAssoc);
                        String output = readTextContent(renditionAssoc.getChildRef());
                        assertNotNull("The rendition content was null.", output);
                        // check the output contains root node Id as expected.
                        assertTrue(output.contains(nodeWithDocContent.getId()));
                        return null;
                    }
                });
}
 
Example 48
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 49
Project: alfresco-repository   File: SOLRTrackingComponentTest.java   Source Code and License 5 votes vote down vote up
SOLRTest3(
    RetryingTransactionHelper txnHelper, FileFolderService fileFolderService,
    NodeDAO nodeDAO, QNameDAO qnameDAO, NodeService nodeService, DictionaryService dictionaryService, 
    NodeRef rootNodeRef, String containerName, boolean doNodeChecks, boolean doMetaDataChecks)
    {
super(txnHelper, fileFolderService, nodeDAO, qnameDAO, nodeService, dictionaryService, rootNodeRef, containerName, doNodeChecks, doMetaDataChecks);
    }
 
Example 50
Project: alfresco-remote-api   File: FacetRestApiTest.java   Source Code and License 5 votes vote down vote up
@Override protected void setUp() throws Exception
{
    super.setUp();
    authenticationService = getServer().getApplicationContext().getBean("AuthenticationService", MutableAuthenticationService.class);
    authorityService      = getServer().getApplicationContext().getBean("AuthorityService", AuthorityService.class);
    personService         = getServer().getApplicationContext().getBean("PersonService", PersonService.class);
    transactionHelper     = getServer().getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);

    AuthenticationUtil.clearCurrentSecurityContext();
    // Create test users. TODO Create these users @BeforeClass or at a testsuite scope.
    AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
    {
        @Override public Void doWork() throws Exception
        {
            createUser(SEARCH_ADMIN_USER);
            createUser(NON_SEARCH_ADMIN_USER);

            if ( !authorityService.getContainingAuthorities(AuthorityType.GROUP,
                                                            SEARCH_ADMIN_USER,
                                                            true)
                                .contains(SolrFacetServiceImpl.GROUP_ALFRESCO_SEARCH_ADMINISTRATORS_AUTHORITY))
            {
                authorityService.addAuthority(SolrFacetServiceImpl.GROUP_ALFRESCO_SEARCH_ADMINISTRATORS_AUTHORITY,
                                              SEARCH_ADMIN_USER);
            }
            return null;
        }
    });
}
 
Example 51
Project: alfresco-remote-api   File: RepoService.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public RepoService(ApplicationContext applicationContext) throws Exception
   {
   	this.applicationContext = applicationContext;
   	this.publicApiContext = new PublicApiTestContext(applicationContext);
   	this.authenticationService = (MutableAuthenticationService)applicationContext.getBean("AuthenticationService");
   	this.siteService = (SiteService)applicationContext.getBean("SiteService");
   	this.activityService = (ActivityService)applicationContext.getBean("activityService");
   	this.fileFolderService = (FileFolderService)applicationContext.getBean("FileFolderService");
   	this.contentService = (ContentService)applicationContext.getBean("ContentService");
   	this.commentService = (CommentService)applicationContext.getBean("CommentService");
   	this.nodeService = (NodeService)applicationContext.getBean("NodeService");
   	this.preferenceService = (PreferenceService)applicationContext.getBean("PreferenceService");
   	this.taggingService = (TaggingService)applicationContext.getBean("TaggingService");
   	this.ratingService = (RatingService)applicationContext.getBean("RatingService");
   	this.tenantService = (TenantService)applicationContext.getBean("tenantService");
   	this.tenantAdminService = (TenantAdminService)applicationContext.getBean("tenantAdminService");
   	this.personService = (PersonService)applicationContext.getBean("PersonService");
   	this.contentStoreCleaner = (ContentStoreCleaner)applicationContext.getBean("contentStoreCleaner");
   	this.postDAO = (ActivityPostDAO)applicationContext.getBean("postDAO");
   	this.nodeRatingSchemeRegistry = (NamedObjectRegistry<RatingScheme>)applicationContext.getBean("nodeRatingSchemeRegistry");
   	this.cociService = (CheckOutCheckInService)applicationContext.getBean("CheckoutCheckinService");
   	this.favouritesService = (FavouritesService)applicationContext.getBean("FavouritesService");
   	this.dictionaryService =  (DictionaryService)applicationContext.getBean("dictionaryService");
   	this.invitationService = (InvitationService)applicationContext.getBean("InvitationService");
   	this.lockService = (LockService)applicationContext.getBean("LockService");
   	this.cmisConnector = (CMISConnector)applicationContext.getBean("CMISConnector");
   	this.nodeIndexer = (NodeIndexer)applicationContext.getBean("nodeIndexer");
   	this.activities = (Activities)applicationContext.getBean("activities");
   	this.hiddenAspect = (HiddenAspect)applicationContext.getBean("hiddenAspect");
   	this.networksService = (NetworksService)applicationContext.getBean("networksService");
   	this.namespaceService = (NamespaceService)applicationContext.getBean("namespaceService"); 
   	this.transactionHelper = (RetryingTransactionHelper)applicationContext.getBean("retryingTransactionHelper");

       Scheduler scheduler = (Scheduler)applicationContext.getBean("schedulerFactory");
   	
   	JobDetailBean contentStoreCleanerJobDetail = (JobDetailBean)applicationContext.getBean("contentStoreCleanerJobDetail");
       scheduler.pauseJob(contentStoreCleanerJobDetail.getName(), contentStoreCleanerJobDetail.getGroup());

       ChildApplicationContextFactory activitiesFeed = (ChildApplicationContextFactory)applicationContext.getBean("ActivitiesFeed");
       ApplicationContext activitiesFeedCtx = activitiesFeed.getApplicationContext();
       this.postLookup = (PostLookup)activitiesFeedCtx.getBean("postLookup");
       this.feedGenerator = (FeedGenerator)activitiesFeedCtx.getBean("feedGenerator");
       this.feedGeneratorJobDetail = (JobDetailBean)activitiesFeedCtx.getBean("feedGeneratorJobDetail");
       this.postLookupJobDetail = (JobDetailBean)activitiesFeedCtx.getBean("postLookupJobDetail");
       this.feedCleanerJobDetail = (JobDetailBean)activitiesFeedCtx.getBean("feedCleanerJobDetail");
       this.postCleanerJobDetail = (JobDetailBean)activitiesFeedCtx.getBean("postCleanerJobDetail");
       this.feedNotifierJobDetail = (JobDetailBean)activitiesFeedCtx.getBean("feedNotifierJobDetail");
   	this.feedCleaner = (FeedCleaner)activitiesFeedCtx.getBean("feedCleaner");

       // Pause activities jobs so that we aren't competing with their scheduled versions
       scheduler.pauseJob(feedGeneratorJobDetail.getName(), feedGeneratorJobDetail.getGroup());
       scheduler.pauseJob(postLookupJobDetail.getName(), postLookupJobDetail.getGroup());
       scheduler.pauseJob(feedCleanerJobDetail.getName(), feedCleanerJobDetail.getGroup());
       scheduler.pauseJob(postCleanerJobDetail.getName(), postCleanerJobDetail.getGroup());
       scheduler.pauseJob(feedNotifierJobDetail.getName(), feedNotifierJobDetail.getGroup());

       this.systemNetwork = new TestNetwork(TenantService.DEFAULT_DOMAIN, true);
}
 
Example 52
Project: alfresco-repository   File: ActionFormProcessorTest.java   Source Code and License 5 votes vote down vote up
public void testGenerateFormWithSelectedFields() throws Exception
{
    this.transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {
                // request a certain set of fields
                List<String> fields = new ArrayList<String>();
                fields.add(MoveActionExecuter.PARAM_DESTINATION_FOLDER);
                fields.add(ActionFormProcessor.EXECUTE_ASYNCHRONOUSLY);
                
                Form form = formService.getForm(new Item(ActionFormProcessor.ITEM_KIND, "move"), fields);
                
                // check a form got returned
                assertNotNull("Expecting form to be present", form);
                
                // get the fields into a Map
                Collection<FieldDefinition> fieldDefs = form.getFieldDefinitions();
                Map<String, FieldDefinition> fieldDefMap = new HashMap<String, FieldDefinition>(fieldDefs.size());
                for (FieldDefinition fieldDef : fieldDefs)
                {
                    fieldDefMap.put(fieldDef.getName(), fieldDef);
                }
                
                // check there are 2 field
                assertEquals(2, fieldDefMap.size());
                
                // check the 2 fields are the correct ones!
                AssociationFieldDefinition destFolderField = (AssociationFieldDefinition)fieldDefMap.get(MoveActionExecuter.PARAM_DESTINATION_FOLDER);
                assertNotNull(destFolderField);
                PropertyFieldDefinition execAsyncField = (PropertyFieldDefinition)fieldDefMap.get(ActionFormProcessor.EXECUTE_ASYNCHRONOUSLY);
                assertNotNull(execAsyncField);
                
                return null;
            }
        });
}
 
Example 53
Project: alfresco-repository   File: ContentDiskDriverTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test Get File Information
 */
public void testGetFileInformation() throws Exception
{
    logger.debug("testGetFileInformation");
    ServerConfiguration scfg = new ServerConfiguration("testServer");
    TestServer testServer = new TestServer("testServer", scfg);
    final SrvSession testSession = new TestSrvSession(666, testServer, "test", "remoteName");
    DiskSharedDevice share = getDiskSharedDevice();
    
    final TreeConnection testConnection = testServer.getTreeConnection(share);
    final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();
    
    class TestContext
    {     
        NodeRef testNodeRef;    
    };
    
    final TestContext testContext = new TestContext();

    /**
     * Test 1 : Get the root info
     */
    FileInfo finfo = driver.getFileInformation(testSession, testConnection, "");
    assertNotNull("root info is null", finfo);
    assertEquals("root has a unexpected file name", "", finfo.getFileName());
    
}
 
Example 54
Project: alfresco-repository   File: CommentsTest.java   Source Code and License 5 votes vote down vote up
/**
 * This test method tests that nodes whose commentCount is set to -1 have their commentCounts recalculated.
 * This feature (see ALF-8498) is to allow customers to set their counts to -1 thus triggering a recount for that document.
 */
@Test public void testTriggerCommentRecount() throws Exception
{
    transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {
                NodeRef testDoc = testDocs.get(0);
                applyComment(testDoc, "Hello 1");
                applyComment(testDoc, "Hello 2");
                applyComment(testDoc, "Hello 3");

                assertCommentCountIs(testDoc, 3);

                // We'll cheat and just set it to an arbitrary value.
                nodeService.setProperty(testDoc, ForumModel.PROP_COMMENT_COUNT, 42);

                // It should have that value - even though it's wrong.
                assertCommentCountIs(testDoc, 42);

                // Now we'll set it to the trigger value -1.
                nodeService.setProperty(testDoc, ForumModel.PROP_COMMENT_COUNT, ForumPostBehaviours.COUNT_TRIGGER_VALUE);

                // It should have the correct, recalculated value.
                assertCommentCountIs(testDoc, 3);

                return null;
            }
        });
}
 
Example 55
Project: alfresco-remote-api   File: PersonServiceTest.java   Source Code and License 5 votes vote down vote up
private void addUserUsageContent(final String userName, final int stringDataLength)
{
    RetryingTransactionHelper.RetryingTransactionCallback<Void> usageCallback = new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            try
            {
                AuthenticationUtil.pushAuthentication();
                AuthenticationUtil.setFullyAuthenticatedUser(userName);
                String textData = "This is default text added. Add more: ";
                for (int i = 0; i < stringDataLength; i++)
                {
                    textData += "abc";
                }
                NodeRef homeFolder = getHomeSpaceFolderNode(userName);
                NodeRef folder = nodeService.createNode(
                        homeFolder,
                        ContentModel.ASSOC_CONTAINS,
                        QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "testFolder"),
                        ContentModel.TYPE_FOLDER).getChildRef();
                addTextContent(folder, "text1.txt", textData);
            }
            finally
            {
                AuthenticationUtil.popAuthentication();
            }
            return null;
        }
    };

    RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
    txnHelper.doInTransaction(usageCallback);
}
 
Example 56
Project: alfresco-repository   File: LinksServiceImplTest.java   Source Code and License 5 votes vote down vote up
/**
 * Ensures that when we try to write an entry to the
 *  container of a new site, it is correctly setup for us.
 * This test does it's own transactions
 */
@Test public void newContainerSetup() throws Exception
{
   final String TEST_SITE_NAME = "LinksTestNewTestSite";
   
   TRANSACTION_HELPER.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
   {
      @Override
      public Void execute() throws Throwable
      {
         if (SITE_SERVICE.getSite(TEST_SITE_NAME) != null)
         {
            SITE_SERVICE.deleteSite(TEST_SITE_NAME);
         }
         SITE_SERVICE.createSite(
               TEST_SITE_PREFIX, TEST_SITE_NAME, "Test", "Test", SiteVisibility.PUBLIC);

         // Won't have the container to start with
         assertFalse(SITE_SERVICE.hasContainer(TEST_SITE_NAME, LinksServiceImpl.LINKS_COMPONENT));

         // Create a link
         LINKS_SERVICE.createLink(
               TEST_SITE_NAME, "Title", "Description",
               "http://www.alfresco.com/", false);
         
         // It will now exist
         assertTrue(SITE_SERVICE.hasContainer(TEST_SITE_NAME, LinksServiceImpl.LINKS_COMPONENT));

         // It'll be a tag scope too
         NodeRef container = SITE_SERVICE.getContainer(TEST_SITE_NAME, LinksServiceImpl.LINKS_COMPONENT);
         assertTrue(TAGGING_SERVICE.isTagScope(container));

         // Tidy up
         SITE_SERVICE.deleteSite(TEST_SITE_NAME);
         return null;
      }
   });
}
 
Example 57
Project: alfresco-repository   File: TakeOwnershipActionExecuterTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass public static void initStaticData() throws Exception
{
    OWNABLE_SERVICE    = APP_CONTEXT_INIT.getApplicationContext().getBean("OwnableService", OwnableService.class);
    TRANSACTION_HELPER = APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    
    // One user creates a site.
    final String siteShortName = GUID.generate();
    SITE_INFO = TEMP_SITES.createTestSiteWithUserPerRole(siteShortName,
                                                         "sitePreset",
                                                         SiteVisibility.PUBLIC,
                                                         TEST_USER1.getUsername());
    // A site contributor creates a document in it.
    TEST_DOC  = TEMP_NODES.createNode(SITE_INFO.doclib, "userOnesDoc", ContentModel.TYPE_CONTENT, SITE_INFO.siteContributor);
}
 
Example 58
Project: alfresco-repository   File: FeedNotifierJobTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test for MNT-12398
 * @throws JobExecutionException 
 */
@Test
public void testAuthentication() throws Exception
{
    final String activityType = "org.alfresco.profile.status-changed";
    final String siteId = null;
    final String appTool = "profile";
    // Status update
    final String jsonActivityData = "{\"status\":\"test\"}";
    
    // and activity for userName2
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        @SuppressWarnings("synthetic-access")
        public Void execute() throws Throwable
        {
            AuthenticationUtil.pushAuthentication();
            AuthenticationUtil.setFullyAuthenticatedUser(userName1);

            activityService.postActivity(activityType, siteId, appTool, jsonActivityData);

            AuthenticationUtil.popAuthentication();

            return null;
        }
    }, false, true);
    
    generateActivities();
    // Start feed notifier as user2 (the generation should be run as system internally)
    // We should not get the "Unable to get user feed entries for 'user1' - currently logged in as 'user2'"
    AuthenticationUtil.setFullyAuthenticatedUser(userName2);
    feedNotifierJob.execute(jobCtx);
    
    assertNull("The notification failed with error " + userNotifier.getError(), userNotifier.getError());
}
 
Example 59
Project: alfresco-repository   File: RemoteCredentialsServicesTest.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 60
Project: alfresco-remote-api   File: RatingRestApiTest.java   Source Code and License 5 votes vote down vote up
@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();
                }          
            });        
}