Java Code Examples for org.alfresco.service.cmr.action.Action#setParameterValue()

The following examples show how to use org.alfresco.service.cmr.action.Action#setParameterValue() . 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: RuleServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testGetRuleset() throws Exception
{
    JSONObject parentRule = createRule(testWorkNodeRef);
    String[] parentRuleIds = new String[] { parentRule.getJSONObject("data").getString("id") };

    JSONObject jsonRule = createRule(testNodeRef);
    String[] ruleIds = new String[] { jsonRule.getJSONObject("data").getString("id") };

    Action linkRulesAction = actionService.createAction(LinkRules.NAME);
    linkRulesAction.setParameterValue(LinkRules.PARAM_LINK_FROM_NODE, testNodeRef);
    actionService.executeAction(linkRulesAction, testNodeRef2);

    Response linkedFromResponse = sendRequest(new GetRequest(formatRulesetUrl(testNodeRef)), 200);
    JSONObject linkedFromResult = new JSONObject(linkedFromResponse.getContentAsString());
    
    checkRuleset(linkedFromResult, 1, ruleIds, 1, parentRuleIds, true, false);

    Response linkedToResponse = sendRequest(new GetRequest(formatRulesetUrl(testNodeRef2)), 200);
    JSONObject linkedToResult = new JSONObject(linkedToResponse.getContentAsString());
    
    checkRuleset(linkedToResult, 1, ruleIds, 1, parentRuleIds, false, true);
}
 
Example 2
Source File: InviteNominatedSender.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void sendMail(String emailTemplateXpath, String emailSubjectKey, Map<String, String> properties)
{
    checkProperties(properties);
    ParameterCheck.mandatory("Properties", properties);
    NodeRef inviter = personService.getPerson(properties.get(wfVarInviterUserName));
    String inviteeName = properties.get(wfVarInviteeUserName);
    NodeRef invitee = personService.getPerson(inviteeName);
    Action mail = actionService.createAction(MailActionExecuter.NAME);
    mail.setParameterValue(MailActionExecuter.PARAM_FROM, getEmail(inviter));
    mail.setParameterValue(MailActionExecuter.PARAM_TO, getEmail(invitee));
    mail.setParameterValue(MailActionExecuter.PARAM_SUBJECT, emailSubjectKey);
    mail.setParameterValue(MailActionExecuter.PARAM_SUBJECT_PARAMS, new Object[] { ModelUtil.getProductName(repoAdminService), getSiteName(properties) });
    mail.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, getEmailTemplateNodeRef(emailTemplateXpath));
    mail.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, (Serializable) buildMailTextModel(properties));
    mail.setParameterValue(MailActionExecuter.PARAM_IGNORE_SEND_FAILURE, true);
    actionService.executeAction(mail, getWorkflowPackage(properties));
}
 
Example 3
Source File: ThumbnailHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void decorateAction(ThumbnailDefinition thumbnailDef, Action action, ActionService actionService)
{
    final FailureHandlingOptions failureOptions = thumbnailDef.getFailureHandlingOptions();
    long retryPeriod = failureOptions == null ? FailureHandlingOptions.DEFAULT_PERIOD : failureOptions.getRetryPeriod() * 1000l;
    int retryCount = failureOptions == null ? FailureHandlingOptions.DEFAULT_RETRY_COUNT : failureOptions.getRetryCount();
    long quietPeriod = failureOptions == null ? FailureHandlingOptions.DEFAULT_PERIOD : failureOptions.getQuietPeriod() * 1000l;
    boolean quietPeriodRetriesEnabled = failureOptions == null ?
            FailureHandlingOptions.DEFAULT_QUIET_PERIOD_RETRIES_ENABLED : failureOptions.getQuietPeriodRetriesEnabled();
    
    // The thumbnail/action should only be run if it is eligible.
    Map<String, Serializable> failedThumbnailConditionParams = new HashMap<String, Serializable>();
    failedThumbnailConditionParams.put(NodeEligibleForRethumbnailingEvaluator.PARAM_THUMBNAIL_DEFINITION_NAME, thumbnailDef.getName());
    failedThumbnailConditionParams.put(NodeEligibleForRethumbnailingEvaluator.PARAM_RETRY_PERIOD, retryPeriod);
    failedThumbnailConditionParams.put(NodeEligibleForRethumbnailingEvaluator.PARAM_RETRY_COUNT, retryCount);
    failedThumbnailConditionParams.put(NodeEligibleForRethumbnailingEvaluator.PARAM_QUIET_PERIOD, quietPeriod);
    failedThumbnailConditionParams.put(NodeEligibleForRethumbnailingEvaluator.PARAM_QUIET_PERIOD_RETRIES_ENABLED, quietPeriodRetriesEnabled);
    
    ActionCondition thumbnailCondition = actionService.createActionCondition(NodeEligibleForRethumbnailingEvaluator.NAME, failedThumbnailConditionParams);
    

    // If it is run and if it fails, then we want a compensating action to run which will mark
    // the source node as having failed to produce a thumbnail.
    Action applyBrokenThumbnail = actionService.createAction("add-failed-thumbnail");
    applyBrokenThumbnail.setParameterValue(AddFailedThumbnailActionExecuter.PARAM_THUMBNAIL_DEFINITION_NAME, thumbnailDef.getName());
    applyBrokenThumbnail.setParameterValue(AddFailedThumbnailActionExecuter.PARAM_FAILURE_DATETIME, new Date());

    action.addActionCondition(thumbnailCondition);
    action.setCompensatingAction(applyBrokenThumbnail);
}
 
Example 4
Source File: AbstractMailActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void everyoneSending()
{
    Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
    mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, "[email protected]");
    ArrayList<String> toMany = new ArrayList<String>();
    toMany.add(PERMISSION_SERVICE.getAllAuthorities());
    mailAction.setParameterValue(MailActionExecuter.PARAM_TO_MANY, toMany);
    mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Testing MNT-12464");
    mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, "alfresco/templates/mail/test.txt.ftl");
    mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, (Serializable) getModel());

    ACTION_EXECUTER.resetTestSentCount();

    ACTION_SERVICE.executeAction(mailAction, null);
}
 
Example 5
Source File: AbstractMailActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * ALF-21948
 */
@Test
public void testSendingToListOfCarbonCopyAndBlindCarbonCopyUsers() throws MessagingException
{
    List<String> ccList = new ArrayList<String>();
    ccList.add("[email protected]");
    ccList.add("[email protected]");

    List<String> bccList = new ArrayList<String>();
    bccList.add("[email protected]");
    bccList.add("[email protected]");
    bccList.add("[email protected]");

    Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
    mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, "[email protected]");
    mailAction.setParameterValue(MailActionExecuter.PARAM_TO, "[email protected]");
    mailAction.setParameterValue(MailActionExecuter.PARAM_CC, (Serializable) ccList);
    mailAction.setParameterValue(MailActionExecuter.PARAM_BCC, (Serializable) bccList);

    mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Testing (BLIND) CARBON COPY");
    mailAction.setParameterValue(MailActionExecuter.PARAM_TEXT, "mail body here");

    ACTION_EXECUTER.resetTestSentCount();
    ACTION_SERVICE.executeAction(mailAction, null);
    MimeMessage message = ACTION_EXECUTER.retrieveLastTestMessage();
    Assert.assertNotNull(message);

    Address[] all = message.getAllRecipients();
    Address[] ccs = message.getRecipients(RecipientType.CC);
    Address[] bccs = message.getRecipients(RecipientType.BCC);
    Assert.assertEquals(6, all.length);
    Assert.assertEquals(2, ccs.length);
    Assert.assertEquals(3, bccs.length);
    Assert.assertTrue(ccs[0].toString().contains("cc_user1") && ccs[1].toString().contains("cc_user2"));
    Assert.assertTrue(bccs[0].toString().contains("bcc_user3") && bccs[1].toString().contains("bcc_user4")
                      && bccs[2].toString().contains("bcc_user5"));
}
 
Example 6
Source File: AbstractMailActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Test for CC / BCC 
 * @throws Exception 
 */
@Test
public void testSendingToCarbonCopy() throws IOException, MessagingException
{
    // PARAM_TO variant
    Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
    mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, "[email protected]");
    mailAction.setParameterValue(MailActionExecuter.PARAM_TO, "[email protected]");
    mailAction.setParameterValue(MailActionExecuter.PARAM_CC, "[email protected]");
    mailAction.setParameterValue(MailActionExecuter.PARAM_BCC, "[email protected]");

    mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Testing CARBON COPY");
    mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, "alfresco/templates/mail/test.txt.ftl");

    mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, (Serializable) getModel());

    ACTION_SERVICE.executeAction(mailAction, null);

    MimeMessage message = ACTION_EXECUTER.retrieveLastTestMessage();
    Assert.assertNotNull(message);
    Address[] all = message.getAllRecipients();
    Address[] ccs = message.getRecipients(RecipientType.CC);
    Address[] bccs = message.getRecipients(RecipientType.BCC);
    Assert.assertEquals(3, all.length);
    Assert.assertEquals(1, ccs.length);
    Assert.assertEquals(1, bccs.length);
    Assert.assertTrue(ccs[0].toString().contains("some.carbon"));
    Assert.assertTrue(bccs[0].toString().contains("some.blindcarbon"));
}
 
Example 7
Source File: ActionServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Test the action result parameter
 */
@Test
public void testActionResult()
{
    // We need to run this test as Administrator. The ScriptAction has to run as a full user (instead of as System)
    // so that we can setup the Person object in the ScriptNode
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    try
    {
        // Create the script node reference
        NodeRef script = this.nodeService.createNode(
                this.folder,
                ContentModel.ASSOC_CONTAINS,
                QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "testScript.js"),
                ContentModel.TYPE_CONTENT).getChildRef();
        this.nodeService.setProperty(script, ContentModel.PROP_NAME, "testScript.js");
        ContentWriter contentWriter = this.contentService.getWriter(script, ContentModel.PROP_CONTENT, true);
        contentWriter.setMimetype("text/plain");
        contentWriter.setEncoding("UTF-8");
        contentWriter.putContent("\"VALUE\";");

        // Create the action
        Action action1 = this.actionService.createAction(ScriptActionExecuter.NAME);
        action1.setParameterValue(ScriptActionExecuter.PARAM_SCRIPTREF, script);

        // Execute the action
        this.actionService.executeAction(action1, this.nodeRef);

        // Get the result
        String result = (String)action1.getParameterValue(ActionExecuter.PARAM_RESULT);
        assertNotNull(result);
        assertEquals("VALUE", result);
    }
    finally
    {
        AuthenticationUtil.clearCurrentSecurityContext();
    }
}
 
Example 8
Source File: ActionServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * http://issues.alfresco.com/jira/browse/ALF-5027
 */
@Test
public void testALF5027() throws Exception
{
    String userName = "bob" + GUID.generate();
    createUser(userName);
    PermissionService permissionService = (PermissionService)applicationContext.getBean("PermissionService");
    permissionService.setPermission(rootNodeRef, userName, PermissionService.COORDINATOR, true);
    
    AuthenticationUtil.setRunAsUser(userName);
    
    NodeRef myNodeRef = nodeService.createNode(
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}myTestNode" + GUID.generate()),
            ContentModel.TYPE_CONTENT).getChildRef();
    
    CheckOutCheckInService coci = (CheckOutCheckInService)applicationContext.getBean("CheckoutCheckinService");
    NodeRef workingcopy = coci.checkout(myNodeRef);
    assertNotNull(workingcopy);
    
    assertFalse(nodeService.hasAspect(myNodeRef, ContentModel.ASPECT_DUBLINCORE));
    
    Action action1 = this.actionService.createAction(AddFeaturesActionExecuter.NAME);
    action1.setParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_DUBLINCORE);        
    actionService.executeAction(action1, myNodeRef);
    
    // The action should have been ignored since the node is locked
    assertFalse(nodeService.hasAspect(myNodeRef, ContentModel.ASPECT_DUBLINCORE));
    
    coci.checkin(workingcopy, null);
    actionService.executeAction(action1, myNodeRef);
    
    assertTrue(nodeService.hasAspect(myNodeRef, ContentModel.ASPECT_DUBLINCORE));
}
 
Example 9
Source File: InviteModeratedSender.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void sendMail(String emailTemplatePath, String emailSubjectKey, Map<String, String> properties)
{
    checkProperties(properties);
    NodeRef invitee = personService.getPerson(properties.get(WorkflowModelModeratedInvitation.wfVarInviteeUserName));
    Action mail = actionService.createAction(MailActionExecuter.NAME);
    mail.setParameterValue(MailActionExecuter.PARAM_FROM, (String) nodeService.getProperty(invitee, ContentModel.PROP_EMAIL));
    mail.setParameterValue(MailActionExecuter.PARAM_TO_MANY, properties.get(bpmGroupAssignee));
    mail.setParameterValue(MailActionExecuter.PARAM_SUBJECT, emailSubjectKey);
    mail.setParameterValue(MailActionExecuter.PARAM_SUBJECT_PARAMS, new Object[] { getSiteName(properties) });
    mail.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, getEmailTemplate(emailTemplatePath));
    mail.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, (Serializable) buildMailTextModel(properties));
    mail.setParameterValue(MailActionExecuter.PARAM_IGNORE_SEND_FAILURE, true);
    actionService.executeAction(mail, new NodeRef(properties.get(WF_PACKAGE)));
}
 
Example 10
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, Serializable recipients, String subject, String template)
{
    Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
    mailAction.setParameterValue(MailActionExecuter.PARAM_TO_MANY, recipients);

    return sendMessage(from, subject, template, mailAction);
}
 
Example 11
Source File: ErrorProneUserNotifier.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
	protected void notifyUser(NodeRef personNodeRef, String subjectText, Object[] subjectParams,
			Map<String, Object> model, String templateNodeRef)
	{
//		super.notifyUser(personNodeRef, subjectText, model, templateNodeRef);

		String userName = (String)nodeService.getProperty(personNodeRef, ContentModel.PROP_USERNAME);

        Action action = actionService.createAction(ErrorProneActionExecutor.NAME);

        action.setParameterValue(ErrorProneActionExecutor.PARAM_FAILING_PERSON_NODEREF, failingPersonNodeRef);
        action.setParameterValue(ErrorProneActionExecutor.PARAM_PERSON_NODEREF, personNodeRef);
        action.setParameterValue(ErrorProneActionExecutor.PARAM_USERNAME, userName);

        actionService.executeAction(action, null);
//		String userName = (String)nodeService.getProperty(personNodeRef, ContentModel.PROP_USERNAME);
//
//		System.out.println("userName = " + userName);
//
//		if(personNodeRef.equals(failingPersonNodeRef))
//		{
//			numFailed.incrementAndGet();
//			throw new AlfrescoRuntimeException("");
//		}
//
//		numSuccessful.incrementAndGet();
	}
 
Example 12
Source File: AbstractMailActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testPrepareEmailSubjectParams()
{
    Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
    mailAction.setParameterValue(MailActionExecuter.PARAM_TO, "[email protected]");
    mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, "alfresco/templates/mail/test.txt.ftl");
    mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Test Subject Params");
    mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, getModel());
    Pair<String, Locale> recipient = new Pair<String, Locale>("test", Locale.ENGLISH);
    
    mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT_PARAMS, new Object[] {"Test", "Subject", "Params", "Object", "Array"});
    Assert.assertNotNull("We should support Object[] value for PARAM_SUBJECT_PARAMS", ACTION_EXECUTER.prepareEmail(mailAction, null, recipient, null));
    
    ArrayList<Object> params = new ArrayList<Object>();
    params.add("Test");
    params.add("Subject");
    params.add("Params");
    params.add("ArrayList");
    
    mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT_PARAMS, params);
    Assert.assertNotNull("We should support List<Object> value for PARAM_SUBJECT_PARAMS", ACTION_EXECUTER.prepareEmail(mailAction, null, recipient, null));
    
    mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT_PARAMS, "Test Subject Params Single String");
    Assert.assertNotNull("We should support String value for PARAM_SUBJECT_PARAMS", ACTION_EXECUTER.prepareEmail(mailAction, null, recipient, null));
    
    mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT_PARAMS, null);
    Assert.assertNotNull("We should support null value for PARAM_SUBJECT_PARAMS", ACTION_EXECUTER.prepareEmail(mailAction, null, recipient, null));
}
 
Example 13
Source File: ThumbnailHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Action createCreateThumbnailAction(ThumbnailDefinition thumbnailDef, ServiceRegistry services)
{
    ActionService actionService = services.getActionService();
    
    Action action = actionService.createAction(CreateThumbnailActionExecuter.NAME);
    action.setParameterValue(CreateThumbnailActionExecuter.PARAM_THUMBANIL_NAME, thumbnailDef.getName());
    
    decorateAction(thumbnailDef, action, actionService);
    
    return action;
}
 
Example 14
Source File: RuleServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void executeRule(Rule rule, NodeRef actionedUponNodeRef, Set<ExecutedRuleData> executedRules)
{
    // Get the action associated with the rule
    Action action = rule.getAction();
    if (action == null)
    {
        throw new RuleServiceException("Attempting to execute a rule that does not have a rule specified.");
    }
    
    // Evaluate the condition
    if (this.actionService.evaluateAction(action, actionedUponNodeRef) == true)
    {
        if (executedRules != null)
        {
            // Add the rule to the executed rule list
            // (do this before this is executed to prevent rules being added to the pending list) 
            executedRules.add(new ExecutedRuleData(actionedUponNodeRef, rule));
            if (logger.isDebugEnabled() == true)
            {
                logger.debug(" ... Adding rule (" + rule.getTitle() + ") and nodeRef (" + actionedUponNodeRef.getId() + ") to executed list");
            }
        }
        
        // Execute the rule
        boolean executeAsync = rule.getExecuteAsynchronously();
        // ALF-718: Treats email actions as a special case where they may be performed after the
        // current transaction is committed. This only deals with the bug fix and a more thorough approach
        // (but one with potentially wide ranging consequences) is to replace the boolean executeAsynchronously
        // property on Rules and Actions with an ExecutionTime property - which would
        // be an enumerated type with members SYNCHRONOUSLY, SYNCRHONOUSLY_AFTER_COMMIT and ASYNCHRONOUSLY.
        //
        // NOTE: this code is not at the Action level (i.e. ActionService) since the logic of sending after
        // successful commit works in the context of a Rule but not for the InvitationService.
        if (action.getActionDefinitionName().equals(CompositeActionExecuter.NAME))
        {
            for (Action subAction : ((CompositeAction)action).getActions())
            {
                if (subAction.getActionDefinitionName().equals(MailActionExecuter.NAME))
                {
                    subAction.setParameterValue(MailActionExecuter.PARAM_SEND_AFTER_COMMIT, true);
                }
            }
        }
        else if (action.getActionDefinitionName().equals(MailActionExecuter.NAME))
        {
            action.setParameterValue(MailActionExecuter.PARAM_SEND_AFTER_COMMIT, true);
        }

        executeAction(action, actionedUponNodeRef, executeAsync);
    }
}
 
Example 15
Source File: TaggingServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Triggers an async update of all the relevant tag scopes when a tag is 
 *  added or removed from a node.
 * Uses the audit service as a persisted queue to hold the list of changes,
 *  and triggers an sync action to work on the entries in the queue for us.
 *  This should avoid contention problems and race conditions.
 * 
 * @param nodeRef       node reference
 * @param updates Map<String, Boolean>
 */
private void updateTagScope(NodeRef nodeRef, Map<String, Boolean> updates)
{
   // First up, locate all the tag scopes for this node
   // (Need to do a recursive search up to the root)
   ArrayList<NodeRef> tagScopeNodeRefs = new ArrayList<NodeRef>(3);
   getTagScopes(nodeRef, tagScopeNodeRefs);
   
   if(tagScopeNodeRefs.size() == 0)
   {
      if(logger.isDebugEnabled())
      {
         logger.debug("No tag scopes found for " + nodeRef + " so no scope updates needed");
      }
      return;
   }
   
   // Turn from tag+yes/no into tag+1/-1
   // (Later we may roll things up better to be tag+#/-#)
   HashMap<String,Integer> changes = new HashMap<String, Integer>(updates.size());
   for(String tag : updates.keySet())
   {
      int val = -1;
      if(updates.get(tag))
         val = 1;
      changes.put(tag, val);
   }
   
   // Next, queue the updates for each tag scope
   for(NodeRef tagScopeNode : tagScopeNodeRefs)
   {
      Map<String,Serializable> auditValues = new HashMap<String, Serializable>();
      auditValues.put(TAGGING_AUDIT_KEY_TAGS, changes);
      auditValues.put(TAGGING_AUDIT_KEY_NODEREF, tagScopeNode.toString());
      auditComponent.recordAuditValues(TAGGING_AUDIT_ROOT_PATH, auditValues);
   }
   if(logger.isDebugEnabled())
   {
      logger.debug("Queueing async tag scope updates to tag scopes " + tagScopeNodeRefs + " of " + changes);
   }
   
   // Finally, trigger the action to process the updates
   // This will happen asynchronously
   Action action = this.actionService.createAction(UpdateTagScopesActionExecuter.NAME);
   action.setParameterValue(UpdateTagScopesActionExecuter.PARAM_TAG_SCOPES, tagScopeNodeRefs); 
   this.actionService.executeAction(action, null, false, true);
}
 
Example 16
Source File: RuleServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * MNT-9885. Testing rule trigger after removing Temporary Aspect from the node.
 * 
 * @throws Exception
 */
@Test
public void testRuleTriggerWithTemporaryFiles() throws Exception
{
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();

    NodeRef parentNodeRef = this.nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN,
            QName.createQName("parentnode" + GUID.generate()), ContentModel.TYPE_FOLDER).getChildRef();

    QName actionedQName = QName.createQName("actioneduponnode" + GUID.generate());
    // New child node
    NodeRef actionedUponNodeRef = this.nodeService.createNode(parentNodeRef, ContentModel.ASSOC_CHILDREN,
            actionedQName, ContentModel.TYPE_CONTENT).getChildRef();

    // Add Temporary Aspect to the child Node
    this.nodeService.addAspect(actionedUponNodeRef, ContentModel.ASPECT_TEMPORARY, null);

    // Write some content to the child node
    ContentWriter writer = this.contentService.getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true);
    writer.setMimetype("text/plain");
    writer.putContent("TestContent");

    // Create rule for Versionable Aspect
    Rule testRule = new Rule();
    testRule.setRuleTypes(Collections.singletonList(RuleType.INBOUND));
    testRule.setTitle("RuleServiceTest" + GUID.generate());
    testRule.setDescription(DESCRIPTION);
    testRule.applyToChildren(true);

    Action action = this.actionService.createAction(AddFeaturesActionExecuter.NAME);
    action.setParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_VERSIONABLE);
    testRule.setAction(action);

    this.ruleService.saveRule(parentNodeRef, testRule);
    assertNotNull("Rule was not saved", testRule.getNodeRef());

    // Search rules
    List<Rule> rules = this.ruleService.getRules(parentNodeRef, true, testRule.getRuleTypes().get(0));
    assertNotNull("No rules found", rules);
    assertTrue("Created rule is not found", new HashSet<>(rules).contains(testRule));

    txn.commit();

    // Remove Temporary Aspect from child node
    txn = transactionService.getUserTransaction();
    txn.begin();

    assertTrue("Node has Temporary aspect: ", this.nodeService.hasAspect(actionedUponNodeRef, ContentModel.ASPECT_TEMPORARY));
    assertFalse("Node with Temporary aspect has versionable aspect: ", this.nodeService.hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE));

    // Removing Tempporary aspect
    this.nodeService.removeAspect(actionedUponNodeRef, ContentModel.ASPECT_TEMPORARY);

    txn.commit();

    // Add rule for parent Node
    ((RuntimeRuleService) ruleService).addRulePendingExecution(parentNodeRef, actionedUponNodeRef, testRule);
    ((RuntimeRuleService) ruleService).executePendingRules();

    assertTrue("Pending rule was not executed",
            this.nodeService.hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE));
    assertFalse("Node has temporary aspect",
            this.nodeService.hasAspect(actionedUponNodeRef, ContentModel.ASPECT_TEMPORARY));
    assertTrue("Node has versionable aspect",
            this.nodeService.hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE));

    this.nodeService.deleteNode(actionedUponNodeRef);
    this.nodeService.deleteNode(parentNodeRef);
}
 
Example 17
Source File: ActionServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test the compensating action
 */
@Test
public void testCompensatingAction()
{
    // Create actions that are going to fail
    final Action fatalAction = createFailingMoveAction(true);
    final Action nonfatalAction = createFailingMoveAction(false);
    fatalAction.setTitle("fatal title");
    nonfatalAction.setTitle("non-fatal title");
    
    // Create the compensating actions
    Action compensatingAction = actionService.createAction(AddFeaturesActionExecuter.NAME);
    compensatingAction.setParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_CLASSIFIABLE);
    compensatingAction.setTitle("title");
    fatalAction.setCompensatingAction(compensatingAction);
    
    Action compensatingAction2 = actionService.createAction(AddFeaturesActionExecuter.NAME);
    compensatingAction2.setParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_TEMPORARY);
    compensatingAction2.setTitle("title");
    nonfatalAction.setCompensatingAction(compensatingAction2);
    
    
    // Set the actions to execute asynchronously
    fatalAction.setExecuteAsynchronously(true);
    nonfatalAction.setExecuteAsynchronously(true);
    
    this.actionService.executeAction(fatalAction, this.nodeRef);
    this.actionService.executeAction(nonfatalAction, this.nodeRef);

    TestTransaction.flagForCommit();
    TestTransaction.end();
    
    postAsyncActionTest(
            this.transactionService,
            1000, 
            10, 
            new AsyncTest()
            {
                public String executeTest() 
                {
                    boolean fatalCompensatingActionRun = ActionServiceImplTest.this.nodeService.hasAspect(nodeRef, ContentModel.ASPECT_CLASSIFIABLE);
                    
                    boolean nonFatalCompensatingActionRun = ActionServiceImplTest.this.nodeService.hasAspect(nodeRef, ContentModel.ASPECT_TEMPORARY);
                    
                    StringBuilder result = new StringBuilder();
                    if (!fatalCompensatingActionRun)
                    {
                        result.append("Expected aspect Classifiable.");
                    }
                    if (nonFatalCompensatingActionRun)
                    {
                        result.append(" Did not expect aspect Temporary");
                    }
                    
                    return ( !fatalCompensatingActionRun || nonFatalCompensatingActionRun ? result.toString() : null);
                };
            });
    
    // Modify the compensating action so that it will also fail
    compensatingAction.setParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, QName.createQName("{test}badAspect"));
    
    this.transactionService.getRetryingTransactionHelper().doInTransaction(
            new RetryingTransactionCallback<Object>()
            {
                public Object execute()
                {                        
                    try
                    {
                        ActionServiceImplTest.this.actionService.executeAction(fatalAction, ActionServiceImplTest.this.nodeRef);
                    }
                    catch (RuntimeException exception)
                    {
                        // The exception should have been ignored and execution continued
                        exception.printStackTrace();
                        fail("An exception should not have been raised here.");
                    }
                    return null;
                }
                
            });
    
}
 
Example 18
Source File: ActionServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test saving an action with no conditions.  Includes testing storage and retrieval 
 * of compensating actions.
 */
@Test
public void testSaveActionNoCondition()
{
    // Create the action
    Action action = this.actionService.createAction(AddFeaturesActionExecuter.NAME);
    String actionId = action.getId();
    
    // Set the parameters of the action
    action.setParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_VERSIONABLE);
    
    // Set the title and description of the action
    action.setTitle("title");
    action.setDescription("description");
    action.setExecuteAsynchronously(true);
            
    // Save the action
    this.actionService.saveAction(this.nodeRef, action);
    
    // Get the action
    Action savedAction = this.actionService.getAction(this.nodeRef, actionId);
    
    // Check the action 
    assertEquals(action.getId(), savedAction.getId());
    assertEquals(action.getActionDefinitionName(), savedAction.getActionDefinitionName());
    
    // Check the properties
    assertEquals("title", savedAction.getTitle());
    assertEquals("description", savedAction.getDescription());
    assertTrue(savedAction.getExecuteAsychronously());
    
    // Check that the compensating action has not been set
    assertNull(savedAction.getCompensatingAction());
    
    // Check the properties
    assertEquals(1, savedAction.getParameterValues().size());
    assertEquals(ContentModel.ASPECT_VERSIONABLE, savedAction.getParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME));
            
    // Check the conditions
    assertNotNull(savedAction.getActionConditions());
    assertEquals(0, savedAction.getActionConditions().size());
    
    // Edit the properties of the action        
    Map<QName, Serializable> properties = new HashMap<QName, Serializable>(1);
    properties.put(ContentModel.PROP_NAME, "testName");
    action.setParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_AUDITABLE);
    
    // Set the compensating action
    Action compensatingAction = this.actionService.createAction(AddFeaturesActionExecuter.NAME);
    compensatingAction.setParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_VERSIONABLE);
    action.setCompensatingAction(compensatingAction);
    
    this.actionService.saveAction(this.nodeRef, action);
    Action savedAction2 = this.actionService.getAction(this.nodeRef, actionId);
    
    // Check the updated properties
    assertEquals(1, savedAction2.getParameterValues().size());
    assertEquals(ContentModel.ASPECT_AUDITABLE, savedAction2.getParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME));
    
    // Check the compensating action
    Action savedCompensatingAction = savedAction2.getCompensatingAction();
    assertNotNull(savedCompensatingAction);
    assertEquals(compensatingAction, savedCompensatingAction);
    assertEquals(AddFeaturesActionExecuter.NAME, savedCompensatingAction.getActionDefinitionName());
    assertEquals(ContentModel.ASPECT_VERSIONABLE, savedCompensatingAction.getParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME));
    
    // Change the details of the compensating action (edit and remove)
    compensatingAction.setParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_CLASSIFIABLE);
    this.actionService.saveAction(this.nodeRef, action);
    Action savedAction3 = this.actionService.getAction(this.nodeRef, actionId);
    Action savedCompensatingAction2 = savedAction3.getCompensatingAction();
    assertNotNull(savedCompensatingAction2);
    assertEquals(compensatingAction, savedCompensatingAction2);
    assertEquals(AddFeaturesActionExecuter.NAME, savedCompensatingAction2.getActionDefinitionName());
    assertEquals(ContentModel.ASPECT_CLASSIFIABLE, savedCompensatingAction2.getParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME));
    action.setCompensatingAction(null);
    this.actionService.saveAction(this.nodeRef, action);
    Action savedAction4 = this.actionService.getAction(this.nodeRef, actionId);
    assertNull(savedAction4.getCompensatingAction());
    
    //System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef));
}
 
Example 19
Source File: AbstractMailActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test for MNT-17970
 * @throws IOException
 * @throws MessagingException
 */
@Test
public void testGetToUsersWhenSendingToGroup() throws IOException, MessagingException
{
    String groupName = null;
    final String USER1 = "test_user1";
    final String USER2 = "test_user2";
    try
    {
        // Create users and add them to a group
        createUser(USER1, null);
        createUser(USER2, null);
        groupName = AUTHORITY_SERVICE.createAuthority(AuthorityType.GROUP, "testgroup1");
        AUTHORITY_SERVICE.addAuthority(groupName, USER1);
        AUTHORITY_SERVICE.addAuthority(groupName, USER2);

        // Create mail
        final Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
        mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, "[email protected]");
        mailAction.setParameterValue(MailActionExecuter.PARAM_TO_MANY, groupName);
        mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Testing");
        mailAction.setParameterValue(MailActionExecuter.PARAM_TEXT, "Testing");
        mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, "alfresco/templates/mail/testSentTo.txt.ftl");

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

        // Send mail
        MimeMessage message = txHelper.doInTransaction(new RetryingTransactionCallback<MimeMessage>()
        {
            @Override
            public MimeMessage execute() throws Throwable
            {
                ACTION_EXECUTER.executeImpl(mailAction, null);
                return ACTION_EXECUTER.retrieveLastTestMessage();
            }
        }, true);

        // Check that both users are displayed in message body
        String recipients = USER1 + "@email.com" + "," + USER2 + "@email.com";
        Assert.assertNotNull(message);
        Assert.assertEquals("This email was sent to " + recipients, (String) message.getContent());
    }
    finally
    {
        if (groupName != null)
        {
            AUTHORITY_SERVICE.deleteAuthority(groupName, true);
        }
        PERSON_SERVICE.deletePerson(USER1);
        PERSON_SERVICE.deletePerson(USER2);
    }
}
 
Example 20
Source File: RuleServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * ALF-12726
 * use FileFolderService to rename
 */
@Test
public void testOutboundRuleTriggeredAfterRename1() throws Exception
{
    String newName = "newName" + GUID.generate();

    // Create 2 folders
    NodeRef folder1NodeRef = this.nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("parentnode" + GUID.generate()), ContentModel.TYPE_FOLDER)
            .getChildRef();
    NodeRef folder2NodeRef = this.nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("parentnode" + GUID.generate()), ContentModel.TYPE_FOLDER)
            .getChildRef();

    // Create rule for folder1
    Rule testRule = new Rule();
    testRule.setRuleTypes(Collections.singletonList(RuleType.OUTBOUND));
    testRule.setTitle("RuleServiceTest" + GUID.generate());
    testRule.setDescription(DESCRIPTION);
    testRule.applyToChildren(true);
    Action action = this.actionService.createAction(CopyActionExecuter.NAME);
    action.setParameterValue(CopyActionExecuter.PARAM_DESTINATION_FOLDER, folder2NodeRef);
    testRule.setAction(action);
    this.ruleService.saveRule(folder1NodeRef, testRule);
    assertNotNull("Rule was not saved", testRule.getNodeRef());

    QName actionedQName = QName.createQName("actioneduponnode" + GUID.generate());
    // New node
    NodeRef actionedUponNodeRef = this.nodeService.createNode(folder1NodeRef, ContentModel.ASSOC_CHILDREN, actionedQName,
            ContentModel.TYPE_CONTENT).getChildRef();
    ContentWriter writer = this.contentService.getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true);
    writer.setMimetype("text/plain");
    writer.putContent("TestContent");

    // Rename the node
    this.fileFolderService.rename(actionedUponNodeRef, newName);

    // Check that the rule was not executed
    List<ChildAssociationRef> childAssoc = this.nodeService.getChildAssocs(folder2NodeRef, RegexQNamePattern.MATCH_ALL, actionedQName);
    assertEquals("The rule should not be triggered and no document should be present.", 0, childAssoc.size());

    // Check that the content is still in folder1
    childAssoc = this.nodeService.getChildAssocs(folder1NodeRef, RegexQNamePattern.MATCH_ALL, QName.createQName(newName));
    assertEquals("The rule should not be triggered and the document should be in folder1.", 1, childAssoc.size());

    this.nodeService.deleteNode(folder1NodeRef);
    this.nodeService.deleteNode(folder2NodeRef);
}