org.alfresco.repo.transaction.RetryingTransactionHelper Java Examples

The following examples show how to use org.alfresco.repo.transaction.RetryingTransactionHelper. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EncryptionKeysRegistryImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void removeRegisteredKeys(final Set<String> keys)
{
    RetryingTransactionHelper retryingTransactionHelper = transactionService.getRetryingTransactionHelper();
    final RetryingTransactionCallback<Void> removeKeysCallback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            for(String keyAlias : keys)
            {
                attributeService.removeAttribute(TOP_LEVEL_KEY, keyAlias);
            }

            return null;
        }
    };
    retryingTransactionHelper.doInTransaction(removeKeysCallback, false);
}
 
Example #2
Source File: MultiUserRenditionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@After public void tidyUpUnwantedNodeRefs()
{
    AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER);
    
    txnHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
            {
                public Void execute() throws Throwable
                {
                    for (NodeRef node : nodesToBeTidiedUp)
                    {
                        if (nodeService.exists(node))
                            nodeService.deleteNode(node);
                    }
                    return null;
                }
            });  
    nodesToBeTidiedUp.clear();
}
 
Example #3
Source File: AlfrescoPeople.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 #4
Source File: AbstractTransferProgressMonitor.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 #5
Source File: AbstractMimeMessage.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 #6
Source File: CommentsTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 #7
Source File: NodesImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 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
Source File: WorkflowDeployer.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 #9
Source File: FeedNotifierJobTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@After
public void cleanUp()
{
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        @SuppressWarnings("synthetic-access")
        public Void execute() throws Throwable
        {
            personService.deletePerson(failingPersonNodeRef);
            personService.deletePerson(personNodeRef);
            return null;
        }
    }, false, true);
    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example #10
Source File: DescriptorServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Ensures that a repository Descriptor is available.
 * This is done here to prevent flip-flopping on the license mode
 * during startup i.e. the Enterprise mode will be set once when
 * the real license is validated.
 */
public void verifyLicense() throws LicenseException
{
    synchronized (licenseLock)
    {
        if (isCurrentRepoDescriptorIsNull())
        {
            final RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();

            RetryingTransactionCallback<Void> nopLoadLicense = new RetryingTransactionCallback<Void>()
            {
                @Override
                public Void execute()
                {
                    Descriptor newRepoDescriptor = currentRepoDescriptorDAO.updateDescriptor(serverDescriptor, LicenseMode.UNKNOWN);
                    setCurrentRepoDescriptor(newRepoDescriptor);
                    return null;
                }
            };

            txnHelper.doInTransaction(nopLoadLicense, false, false);
        }
    }
}
 
Example #11
Source File: DiscussionServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 #12
Source File: EncryptionChecker.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void onBootstrap(ApplicationEvent event)
{
    RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
    txnHelper.setForceWritable(true);      // Force write in case server is read-only
    
    txnHelper.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            try
            {
                keyStoreChecker.validateKeyStores();
            }
            catch(Throwable e)
            {
                // Just throw as a runtime exception
                throw new AlfrescoRuntimeException("Keystores are invalid", e);
            }

            return null;
        }
    });
}
 
Example #13
Source File: UnitTestInProcessTransmitterImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void abort(final Transfer transfer) throws TransferException
{
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Transfer>()
    {
        public Transfer execute() throws Throwable
        {
            String transferId = transfer.getTransferId();
            receiver.cancel(transferId);
            return null;
        }
    }, false, true);
}
 
Example #14
Source File: CustomModelImportTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 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 #15
Source File: MultiTServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void deleteTenant(final String tenantDomain)
{
    AuthenticationUtil.runAs(new RunAsWork<Object>()
    {
        public Object doWork() throws Exception
        {
            RetryingTransactionHelper.RetryingTransactionCallback<Void> work = new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
            {
                public Void execute() throws Throwable
                {
                    // delete tenant (if it exists)
                    if (tenantAdminService.existsTenant(tenantDomain))
                    {
                        // TODO: WARNING: HACK for ALF-19155: MT deleteTenant does not work
                        //       PersonService prevents 'guest' authorities from being deleted
                        {
                            BehaviourFilter behaviourFilter = (BehaviourFilter) applicationContext.getBean("policyBehaviourFilter");
                            behaviourFilter.disableBehaviour(ContentModel.TYPE_PERSON);
                            behaviourFilter.disableBehaviour(ContentModel.ASPECT_UNDELETABLE);
                        }
                        tenantAdminService.deleteTenant(tenantDomain);
                    }
                    return null;
                }
            };
            transactionService.getRetryingTransactionHelper().doInTransaction(work);
            return null;
        }
    }, AuthenticationUtil.getSystemUserName());
}
 
Example #16
Source File: TakeOwnershipActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 #17
Source File: EncryptionKeysRegistryImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void registerKey(String keyAlias, Key key)
{
    if(isKeyRegistered(keyAlias))
    {
        throw new IllegalArgumentException("Key " + keyAlias + " is already registered");
    }

    // register the key by creating an attribute that stores a guid and its encrypted value
    String guid = GUID.generate();

    KeyMap keys = new KeyMap();
    keys.setKey(keyAlias, key);
    Encryptor encryptor = getEncryptor(keys);
    Serializable encrypted = encryptor.sealObject(keyAlias, null, guid);
    Pair<String, Serializable> keyCheck = new Pair<String, Serializable>(guid, encrypted);
    RetryingTransactionHelper retryingTransactionHelper = transactionService.getRetryingTransactionHelper();
    final RetryingTransactionCallback<Void> createAttributeCallback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
        	attributeService.createAttribute(keyCheck, TOP_LEVEL_KEY, keyAlias);
            return null;
        }
    };
    retryingTransactionHelper.doInTransaction(createAttributeCallback, false);

    logger.info("Registered key " + keyAlias);
}
 
Example #18
Source File: BaseAuthenticationFilter.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Executes a callback in a transaction as the system user
 * 
 * @param callback
 *            the callback
 * @return the return value from the callback
 */
protected <T> T doInSystemTransaction(final RetryingTransactionHelper.RetryingTransactionCallback<T> callback)
{
    return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<T>()
    {
        public T doWork() throws Exception
        {
            return transactionService.getRetryingTransactionHelper().doInTransaction(callback, transactionService.isReadOnly());
        }
    }, AuthenticationUtil.SYSTEM_USER_NAME);
}
 
Example #19
Source File: DescriptorServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String loadLicense()
{
    // Ensure that we force a writable txn for this operation
    final RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
    txnHelper.setForceWritable(true);
    
    final RetryingTransactionCallback<String> loadCallback = new RetryingTransactionCallback<String>()
    {
        @Override
        public String execute() throws Throwable
        {
            return licenseService.loadLicense();      
        }
    };
    // ... and we have to be 'system' for this, too
    String result = AuthenticationUtil.runAs(new RunAsWork<String>()
    {
        public String doWork() throws Exception
        {
            return txnHelper.doInTransaction(loadCallback, false, true);
        }
    }, AuthenticationUtil.getSystemUserName());

    if (logger.isDebugEnabled())
    {
        logger.debug("Load license call returning: " + result);
    }
    return result;
}
 
Example #20
Source File: DiscussionServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 #21
Source File: TemporaryNodes.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 #22
Source File: BatchProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 #23
Source File: SubscriptionServiceActivitiesTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 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 #24
Source File: BaseAuthenticationFilter.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Callback to create the User environment as appropriate for a filter impl
 * 
 * @param session
 *            HttpSession
 * @param userName
 *            String
 * @return SessionUser
 * @throws IOException
 * @throws ServletException
 */
protected SessionUser createUserEnvironment(final HttpSession session, final String userName) throws IOException,
        ServletException
{
    return this.transactionService.getRetryingTransactionHelper().doInTransaction(
            new RetryingTransactionHelper.RetryingTransactionCallback<SessionUser>()
            {

                public SessionUser execute() throws Throwable
                {
                    authenticationComponent.setCurrentUser(userName);
                    return createUserEnvironment(session, userName, authenticationService.getCurrentTicket(), true);
                }
            }, transactionService.isReadOnly());
}
 
Example #25
Source File: ActionFormProcessorTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testGenerateDefaultFormForParameterlessAction() throws Exception
{
    this.transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {
                Form form = formService.getForm(new Item(ActionFormProcessor.ITEM_KIND, "extract-metadata"));
                
                // 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", 1, fieldDefs.size());
                
                Map<String, FieldDefinition> fieldDefMap = new HashMap<String, FieldDefinition>(fieldDefs.size());
                for (FieldDefinition fieldDef : fieldDefs)
                {
                    fieldDefMap.put(fieldDef.getName(), fieldDef);
                }
                
                validateExecuteAsynchronouslyField(fieldDefMap);
                
                return null;
            }
        });
}
 
Example #26
Source File: LinksServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 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))
             {
                // 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
Source File: InvitationCleanupTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@BeforeClass public static void initStaticData() throws Exception
{
    INVITATION_SERVICE = APP_CONTEXT_INIT.getApplicationContext().getBean("InvitationService", InvitationService.class);
    SITE_SERVICE       = APP_CONTEXT_INIT.getApplicationContext().getBean("SiteService", SiteService.class);
    TRANSACTION_HELPER = APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    WORKFLOW_SERVICE   = APP_CONTEXT_INIT.getApplicationContext().getBean("WorkflowService", WorkflowService.class);
    NODE_ARCHIVE_SERVICE = APP_CONTEXT_INIT.getApplicationContext().getBean("nodeArchiveService", NodeArchiveService.class);
}
 
Example #28
Source File: AbstractMailActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected MimeMessage sendMessage(String from, String subject, String template, String bodyText, final Action mailAction)
{
    if (from != null)
    {
        mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, from);
    }
    mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, subject);
    if (template != null)
    {
        mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, template);
        mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, getModel());
    }
    else
    {
        mailAction.setParameterValue(MailActionExecuter.PARAM_TEXT, bodyText);
    }

    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 #29
Source File: AbstractContextTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception
{
    Map<String, Object> entityResourceBeans = applicationContext.getBeansWithAnnotation(EntityResource.class);
    Map<String, Object> relationResourceBeans = applicationContext.getBeansWithAnnotation(RelationshipResource.class);
    locator.setDictionary(ResourceDictionaryBuilder.build(entityResourceBeans.values(), relationResourceBeans.values()));
    AbstractResourceWebScript executor = (AbstractResourceWebScript) applicationContext.getBean("executorOfGets");
    AbstractResourceWebScript postExecutor = (AbstractResourceWebScript) applicationContext.getBean("executorOfPost");
    AbstractResourceWebScript putExecutor = (AbstractResourceWebScript) applicationContext.getBean("executorOfPut");
    AbstractResourceWebScript deleteExecutor = (AbstractResourceWebScript) applicationContext.getBean("executorOfDelete");

    //Mock transaction service
    TransactionService transerv = mock(TransactionService.class);
    RetryingTransactionHelper tHelper = mock(RetryingTransactionHelper.class);
    when(transerv.getRetryingTransactionHelper()).thenReturn(tHelper);
    when(tHelper.doInTransaction(any(RetryingTransactionHelper.RetryingTransactionCallback.class), anyBoolean(), anyBoolean())).thenAnswer(new Answer<Object>() {
        @SuppressWarnings("rawtypes")
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            RetryingTransactionHelper.RetryingTransactionCallback cb = (RetryingTransactionHelper.RetryingTransactionCallback) args[0];
            return cb.execute();
        }
    });
    executor.setTransactionService(transerv);
    postExecutor.setTransactionService(transerv);
    putExecutor.setTransactionService(transerv);
    deleteExecutor.setTransactionService(transerv);
}
 
Example #30
Source File: AlfrescoRpcAuthenticator.java    From alfresco-repository with GNU Lesser General Public License v3.0 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());
}