Rules/Actions REST API - Latest cut with updates to Web Scripts and Unit Tests since last drop

git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@11382 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Glen Johnson
2008-10-16 15:42:38 +00:00
parent 4dc4c0888c
commit 389a6a26e6
20 changed files with 1412 additions and 236 deletions

View File

@@ -74,8 +74,8 @@ public class ActionDefGet extends DeclarativeWebScript
// initialise model to pass on for template to render
Map<String, Object> model = new HashMap<String, Object>();
// get URL parameter
String actionDefName = req.getParameter(REQ_PARAM_ACTION_DEF_NAME);
// get actionDefinitionName URL template variable
String actionDefName = req.getServiceMatch().getTemplateVars().get(REQ_PARAM_ACTION_DEF_NAME);
if ((actionDefName == null) || (actionDefName.length() == 0))
{
throw new WebScriptException(Status.STATUS_BAD_REQUEST,

View File

@@ -108,12 +108,12 @@ public class ActionQueuePost extends DeclarativeWebScript
actionJson = actionQueueItemJson.getJSONObject("action");
// get the action from the action JSON object
action = this.rulesHelper.getActionFromJson(actionJson);
action = this.rulesHelper.getActionFromJson(actionJson, null);
// Get 'checkConditions' and 'executeAsynchronously' properties off action queue item
checkConditions = actionQueueItemJson.optBoolean("checkConditions", true);
executeAsynchronously = actionQueueItemJson.optBoolean(
"executeAsynchronously", action.getExecuteAsychronously());
"executeAsync", action.getExecuteAsychronously());
// get the actioned-upon node reference
String nodeRefStr = actionQueueItemJson.getString("nodeRef");
@@ -145,7 +145,14 @@ public class ActionQueuePost extends DeclarativeWebScript
actionQItemStatus.setActionId(actionId);
// set the status on the action queue item status bean
actionQItemStatus.setStatus(RulesHelper.ACTION_QUEUE_ITEM_STATUS_COMPLETE);
if (executeAsynchronously == true)
{
actionQItemStatus.setStatus(RulesHelper.ACTION_QUEUE_ITEM_STATUS_PENDING);
}
else
{
actionQItemStatus.setStatus(RulesHelper.ACTION_QUEUE_ITEM_STATUS_COMPLETE);
}
// add objects to model for the template to render
model.put(MODEL_PROP_KEY_ACTION_Q_ITEM_STATUS, actionQItemStatus);

View File

@@ -74,8 +74,8 @@ public class ConditionDefGet extends DeclarativeWebScript
// initialise model to pass on for template to render
Map<String, Object> model = new HashMap<String, Object>();
// get URL parameter
String conditionDefName = req.getParameter(REQ_PARAM_CONDITION_DEF_NAME);
// get conditionDefinitionName URL template variable
String conditionDefName = req.getServiceMatch().getTemplateVars().get(REQ_PARAM_CONDITION_DEF_NAME);
if ((conditionDefName == null) || (conditionDefName.length() == 0))
{
throw new WebScriptException(Status.STATUS_BAD_REQUEST,

View File

@@ -45,7 +45,6 @@ public class RuleDelete extends DeclarativeWebScript
private static final String REQ_TEMPL_VAR_STORE_TYPE = "store_type";
private static final String REQ_TEMPL_VAR_STORE_ID = "store_id";
private static final String REQ_TEMPL_VAR_RULE_NODE_ID = "rule_id";
private static final String REQ_TEMPL_VAR_RULE_OWNING_NODE_ID = "id";
// properties for services
private RuleService ruleService;
@@ -106,26 +105,25 @@ public class RuleDelete extends DeclarativeWebScript
{
throw new WebScriptException(Status.STATUS_BAD_REQUEST,
"The 'rule_id' URL template token has not been provided in URL");
}
}
String owningNodeId = req.getServiceMatch().getTemplateVars().get(REQ_TEMPL_VAR_RULE_OWNING_NODE_ID);
// Handle if 'owningNodeId' URL template token not provided
if ((owningNodeId == null) || (owningNodeId.length() == 0))
{
throw new WebScriptException(Status.STATUS_BAD_REQUEST,
"The 'id' URL template token has not been provided in URL");
}
// NOTE -
// that if a value is provided for the 'id' URL template variable {id},
// i.e. either of the following URL patterns have been used
// <url>/api/node/{store_type}/{store_id}/{id}/rules/{rule_id}</url> or
// <url>/api/path/{store_type}/{store_id}/{id}/rules/{rule_id}</url>
// then the rule owning node ref supplied therein will be ignored,
// as these URL templates are just provided for convenience and the
// rule owning node ref is retrieved by using the rule's identifying node
// ref (supplied in {rule_id})
// create the rule's identifying node reference from the given
// URL template tokens
NodeRef ruleNodeRef = this.rulesHelper.getNodeRefFromWebScriptUrl(req, storeType, storeId, ruleNodeId);
// create the rule owning node reference from the given
// URL template tokens
NodeRef ruleOwningNodeRef = this.rulesHelper.getNodeRefFromWebScriptUrl(req, storeType, storeId, owningNodeId);
// get the rule using it's unique identifying node reference
Rule rule = this.ruleService.getRule(ruleNodeRef);
NodeRef ruleOwningNodeRef = this.ruleService.getOwningNodeRef(rule);
// delete rule
this.ruleService.removeRule(ruleOwningNodeRef, rule);

View File

@@ -49,6 +49,7 @@ public class RuleGet extends DeclarativeWebScript
// model property keys
private static final String MODEL_PROP_KEY_RULE = "rule";
private static final String MODEL_PROP_KEY_OWNING_NODE_REF = "owningNodeRef";
// properties for services
private RuleService ruleService;
@@ -118,12 +119,24 @@ public class RuleGet extends DeclarativeWebScript
// URL template tokens
NodeRef ruleNodeRef = this.rulesHelper.getNodeRefFromWebScriptUrl(req, storeType, storeId, ruleNodeId);
// if ruleNodeRef referred to by {store_type} {store_id} {id} is 'null' then the rule identified by that
// given node id or node path no longer exists
if (ruleNodeRef == null)
{
throw new WebScriptException(Status.STATUS_NOT_FOUND, "Rule identified by rule node/path - 'store_type': "
+ storeType + " 'store_id': " + storeId + " and 'id': " + ruleNodeId + " could not be found");
}
// get rule identified by the given rule node reference
Rule rule = this.ruleService.getRule(ruleNodeRef);
// get rule's owning node
NodeRef ruleOwningNodeRef = this.ruleService.getOwningNodeRef(rule);
// add objects to model for the template to render
model.put(MODEL_PROP_KEY_RULE, rule);
model.put(MODEL_PROP_KEY_OWNING_NODE_REF, ruleOwningNodeRef);
return model;
}
}

View File

@@ -0,0 +1,865 @@
/*
* Copyright (C) 2005-2007 Alfresco Software Limited.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing"
*/
package org.alfresco.repo.web.scripts.rule;
import java.util.ArrayList;
import java.util.List;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.action.evaluator.ComparePropertyValueEvaluator;
import org.alfresco.repo.action.executer.CompositeActionExecuter;
import org.alfresco.repo.action.executer.CopyActionExecuter;
import org.alfresco.repo.action.executer.MoveActionExecuter;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.service.cmr.action.ActionService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.rule.RuleType;
import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.PropertyMap;
import org.alfresco.web.scripts.Status;
import org.alfresco.web.scripts.TestWebScriptServer.DeleteRequest;
import org.alfresco.web.scripts.TestWebScriptServer.GetRequest;
import org.alfresco.web.scripts.TestWebScriptServer.PostRequest;
import org.alfresco.web.scripts.TestWebScriptServer.Response;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Test Case class with unit tests for Rule REST API
*
* @author Glen Johnson at Alfresco dot com
*/
public class RuleServiceTest extends BaseWebScriptTest
{
// member variables for service instances
private AuthenticationService authenticationService;
private AuthenticationComponent authenticationComponent;
private NodeService nodeService;
private PersonService personService;
private ActionService actionService;
private NodeRef owningNodeRef1;
private NodeRef testDestFolder1;
// private constants
private static final String RULES_USER = "Rules.User";
private static final String RULES_USER_PASSWORD = "password";
private static final String RULES_TEST_OWNING_FOLDER_1 = "rulesTestOwningFolder1";
private static final String RULES_TEST_DEST_FOLDER_1 = "rulesTestDestinationFolder1";
@Override
protected void setUp() throws Exception
{
super.setUp();
// get references to services
this.authenticationService = (AuthenticationService) getServer().getApplicationContext().getBean(
"AuthenticationService");
this.authenticationComponent = (AuthenticationComponent) getServer().getApplicationContext().getBean(
"AuthenticationComponent");
this.nodeService = (NodeService) getServer().getApplicationContext().getBean("NodeService");
this.personService = (PersonService) getServer().getApplicationContext().getBean("PersonService");
this.actionService = (ActionService) getServer().getApplicationContext().getBean("ActionService");
//
// various setup operations which need to be run as system user
//
AuthenticationUtil.runAs(new RunAsWork<Object>()
{
public Object doWork() throws Exception
{
createUserAndAssocPerson(RULES_USER);
return null;
}
}, AuthenticationUtil.getSystemUserName());
// Do tests as inviter user
this.authenticationComponent.setCurrentUser(RULES_USER);
// create a folder (as the rule owning node) under the current user's home space
NodeRef personRef = this.personService.getPerson(RULES_USER);
NodeRef userHomeRef = (NodeRef)nodeService.getProperty(personRef, ContentModel.PROP_HOMEFOLDER);
this.owningNodeRef1 = this.nodeService.createNode(userHomeRef, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, RULES_TEST_OWNING_FOLDER_1),
ContentModel.TYPE_FOLDER).getChildRef();
// create other folders for testing purposes
this.testDestFolder1 = this.nodeService.createNode(userHomeRef, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, RULES_TEST_DEST_FOLDER_1),
ContentModel.TYPE_FOLDER).getChildRef();
}
@Override
protected void tearDown() throws Exception
{
super.tearDown();
// delete the actionable node created in setUp()
// TODO uncomment this when I am no longer comparing
// insync with JSF Web Client
//
// this.nodeService.deleteNode(this.actionableNodeRef);
//
// run various teardown operations which need to be run as 'admin'
//
// TODO uncomment this when I am no longer comparing
// insync with JSF Web Client
//
// RunAsWork<Object> runAsWork = new RunAsWork<Object>()
// {
// public Object doWork() throws Exception
// {
// deleteUserAndAssocPerson(RULES_USER);
//
// return null;
// }
// ;
// AuthenticationUtil.runAs(runAsWork, AuthenticationUtil.getSystemUserName());
}
private void deleteUserAndAssocPerson(String userName)
{
// delete authentication if authentication exists for given user name
if (this.authenticationService.authenticationExists(userName))
{
this.authenticationService.deleteAuthentication(userName);
}
// delete person node associated with given user name
// if one exists
if (this.personService.personExists(userName))
{
this.personService.deletePerson(userName);
}
}
/**
* Get a URL to the Rule Collection associated with the given rule owning
* node
*
* @param ruleOwningNodeRef
* the rule owning node reference
* @return the URL to the rule collection associated with the given
* rule owning node
*/
private String getRulesNodeBasedUrl(NodeRef ruleOwningNodeRef,
Boolean includeInherited, String ruleTypeName)
{
boolean includeInheritedParamGiven = includeInherited != null;
boolean ruleTypeNameParamGiven = (ruleTypeName != null) && (ruleTypeName.length() > 0);
boolean parameterGiven = (includeInheritedParamGiven || ruleTypeNameParamGiven);
String url = "/api/node/"
+ ruleOwningNodeRef.getStoreRef().getProtocol() + "/"
+ ruleOwningNodeRef.getStoreRef().getIdentifier() + "/"
+ ruleOwningNodeRef.getId() + "/rules";
if (parameterGiven)
{
url += "?";
}
if (includeInheritedParamGiven)
{
url += "includeInherited=" + includeInherited.toString();
if (ruleTypeNameParamGiven)
{
url += "&";
}
}
if (ruleTypeNameParamGiven)
{
url += "ruleTypeName=" + ruleTypeName;
}
return url;
}
/**
* Get a URL to the Rule Collection associated with the given rule owning
* node (without adding any parameters)
*
* @param ruleOwningNodeRef
* the rule owning node reference
* @return the URL to the rule collection associated with the given
* rule owning node
*/
private String getRulesNodeBasedUrl(NodeRef ruleOwningNodeRef)
{
return getRulesNodeBasedUrl(ruleOwningNodeRef, null, null);
}
private void createUserAndAssocPerson(String userName)
{
// if user with given user name doesn't already exist then create user
if (this.authenticationService.authenticationExists(userName) == false)
{
// create user
this.authenticationService.createAuthentication(userName,
RULES_USER_PASSWORD.toCharArray());
}
// if person node with given user name doesn't already exist then create
// person
if (this.personService.personExists(userName) == false)
{
// create person properties
PropertyMap personProps = new PropertyMap();
personProps.put(ContentModel.PROP_USERNAME, userName);
personProps.put(ContentModel.PROP_FIRSTNAME, "FirstName123");
personProps.put(ContentModel.PROP_LASTNAME, "LastName123");
personProps.put(ContentModel.PROP_EMAIL, "Test.RulesUser@alfresco.com");
personProps.put(ContentModel.PROP_JOBTITLE, "JobTitle123");
personProps.put(ContentModel.PROP_ORGANIZATION, "Organisation123");
// create person node for user
this.personService.createPerson(personProps);
}
}
/**
* Create and return a Condition JSON object
*
* @param id ID of the condition
* @param parameterValues An associative array (map) of parameter values for the condition.
* Pass in <code>null</code> if there are no parameter values associated with this condition.
* @param conditionDefName The definition name for this condition.
* @param invertCondition Indicates whether the condition result should be inverted/negated.
* @param conditionUrl URL to the condition resource
*
* @return the constructed condition
*/
private JSONObject getConditionJsonObject(String id, JSONObject parameterValues,
String conditionDefName, boolean invertCondition, String conditionUrl)
throws Exception
{
// Construct condition JSON object
JSONObject condition = new JSONObject();
condition.put("id", id);
condition.put("parameterValues", parameterValues);
condition.put("conditionDefinitionName", conditionDefName);
condition.put("invertCondition", invertCondition);
condition.put("url", conditionUrl);
return condition;
}
/**
* Create and return an Action JSON object
*
* @param id ID of the action
* @param actionDefName The name of the action definition that relates to this action.
* @param title The title of the action.
* @param description The description of the action.
* @param executeAsync Indicates whether to run the action asynchronously or not.
* @param parameterValues Associative array (map) of parameter values associated with this action.
* Pass in <code>null</code> if there are no parameter values associated with the action.
* @param conditions Associative array of Condition Details for the condition resources associated with this action.
* Pass in <code>null</code> if there are no conditions associated with the action.
* @param actions Associative array of Action Details for the action resources associated with this action.
* Pass in <code>null</code> if this action is not a composite action (and thus no actions
* are associated with it).
* @param compensatingAction Action Details for the compensating action.
* Pass in <code>null</code> if this action does not have a compensating action
* @param actionUrl URL to the action resource
*
* @return the constructed action
*/
private JSONObject getActionJsonObject (String id, String actionDefName, String title, String description,
boolean executeAsync, JSONObject parameterValues, JSONArray conditions,
JSONArray actions, JSONObject compensatingAction, String actionUrl)
throws Exception
{
// Construct action JSON object
JSONObject action = new JSONObject();
action.put("id", id);
action.put("actionDefinitionName", actionDefName);
action.put("title", title);
action.put("description", description);
action.put("executeAsync", executeAsync);
action.put("parameterValues", parameterValues);
action.put("conditions", conditions);
action.put("actions", actions);
action.put("compensatingAction", compensatingAction);
action.put("url", actionUrl);
return action;
}
/**
* Create and return a Rule JSON object
*
* @param owningNodeRef The owning (actionable) node reference to which this rule applies
* @param ruleNodeRef The node that uniquely represents this rule
* @param title The title of the rule
* @param description The description of the rule
* @param ruleTypes The rule types associated with this rule
* @param action The action associated with this rule
* @param executeAsync Indicates whether the rule should execute the action asynchronously or not
* @param ruleDisabled Indicates whether or not this rule is marked as disabled or not
* @param appliedToChildren Indicates whether the rule is applied to all the children of the associated actionable node
* @param ruleUrl URL to the rule resource
*
* @return the constructed rule
*/
private JSONObject getRuleJsonObject (NodeRef owningNodeRef, NodeRef ruleNodeRef, String title,
String description, List<String> ruleTypes, JSONObject action, boolean executeAsync,
boolean ruleDisabled, boolean appliedToChildren, String ruleUrl)
throws Exception
{
// Construct rule JSON object
JSONObject rule = new JSONObject();
rule.put("owningNodeRef", owningNodeRef);
rule.put("ruleNodeRef", ruleNodeRef);
rule.put("title", title);
rule.put("description", description);
rule.put("ruleTypes", new JSONArray(ruleTypes));
rule.put("action", action);
rule.put("executeAsync", executeAsync);
rule.put("ruleDisabled", ruleDisabled);
rule.put("appliedToChildren", appliedToChildren);
rule.put("url", ruleUrl);
return rule;
}
/**
* Creates a rule in the rule collection associated with the given rule owning node
*
* @param ruleOwningNodeRef the rule owning node with which the rule collection is associated
* @param ruleJson The rule JSON object to POST to the collection
*
* @return the created rule returned as a JSON object
* @throws Exception
*/
private JSONObject postRules(NodeRef ruleOwningNodeRef, JSONObject ruleJson) throws Exception
{
// Construct rule collection URL for POST rules
String rulesURL = getRulesNodeBasedUrl(ruleOwningNodeRef);
Response response = sendRequest(new PostRequest(rulesURL, ruleJson.toString(), "application/json"),
Status.STATUS_OK);
JSONObject result = new JSONObject(response.getContentAsString());
return result;
}
/**
* Check that getting the rule collection resource associated with the given actionable node
* returns with the expected HTTP status code
*
* @param ruleOwningNodeRef the actionable node for which we want to retrieve rules associated with
* it i.e. the rules applied to it
* @param expectedStatus the HTTP status that we expect to be returned by this operation
* @return the rules collection returned as an array of Rule Details encapsulated in a JSON object
* @throws Exception
*/
private JSONArray getRules(NodeRef ruleOwningNodeRef, Boolean includeInherited, String ruleTypeName, int expectedStatus)
throws Exception
{
// Construct rule collection URL for GET rules
String rulesUrl = getRulesNodeBasedUrl(ruleOwningNodeRef, includeInherited, ruleTypeName);
Response response = sendRequest(new GetRequest(rulesUrl), expectedStatus);
JSONArray result = new JSONArray(response.getContentAsString());
return result;
}
public void testDeleteRules() throws Exception
{
//
// First POST a Rule to the Rule Collection associated with rule owning NodeRef - owningNodeRef1
//
// create condition parameters
JSONObject condCompMimeTypeParams = new JSONObject();
condCompMimeTypeParams.put(ComparePropertyValueEvaluator.PARAM_VALUE, "image/png");
// create conditions
JSONObject conditionCompMimeType = getConditionJsonObject(null, condCompMimeTypeParams, "compare-mime-type", false, null);
JSONArray conditions = new JSONArray();
conditions.put(conditionCompMimeType);
// create nested action parameters
JSONObject actionCopyParamsJson = new JSONObject();
actionCopyParamsJson.put(MoveActionExecuter.PARAM_ASSOC_QNAME,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "copy"));
actionCopyParamsJson.put(MoveActionExecuter.PARAM_DESTINATION_FOLDER, this.testDestFolder1);
actionCopyParamsJson.put(MoveActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CONTAINS);
// create nested actions
JSONObject actionCopyJson = getActionJsonObject(null, CopyActionExecuter.NAME, "CopyTitle", "CopyDesc", false,
actionCopyParamsJson, null, null, null, null);
JSONArray nestedActions = new JSONArray();
nestedActions.put(actionCopyJson);
// create rule's composite action
JSONObject compoActionJson = getActionJsonObject(null, CompositeActionExecuter.NAME, "Rule1Action", "Rule1ActionDesc",
false, null, conditions, nestedActions, null, null);
// create rule to POST
List<String> ruleTypes = new ArrayList<String>();
ruleTypes.add(RuleType.UPDATE);
JSONObject ruleJson = getRuleJsonObject(this.owningNodeRef1, null, "Rule1", "Rule1Desc", ruleTypes,
compoActionJson, false, false, false, null);
// POST rule JSON to rules collection resource associated with rule owning node ref owningNodeRef1
postRules(this.owningNodeRef1, ruleJson);
//
// DELETE all Rules owned by NodeRef - owningNodeRef1
// and validate that owningNodeRef1 does not have any
// rules left applied against it thereafter
//
// construct url to the Rule Collection resource that we wish to delete (associated with rule owning node
// NodeRef owningNodeRef1)
String url = "/api/node/" + this.owningNodeRef1.getStoreRef().getProtocol() + "/"
+ this.owningNodeRef1.getStoreRef().getIdentifier() + "/" + this.owningNodeRef1.getId() + "/rules";
// DELETE all rules owned by NodeRef owningNodeRef1
sendRequest(new DeleteRequest(url), Status.STATUS_OK);
// make sure that there are no rules associated with
// rule owning NodeRef owningNodeRef1 anymore
Response responseGetRules = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONArray getRulesJson = new JSONArray(responseGetRules.getContentAsString());
assertTrue(getRulesJson.length() == 0);
}
public void testDeleteRule() throws Exception
{
//
// First POST a Rule and get the identifying rule node ref
// from the Rule Details returned
//
// create condition parameters
JSONObject condCompMimeTypeParams = new JSONObject();
condCompMimeTypeParams.put(ComparePropertyValueEvaluator.PARAM_VALUE, "image/png");
// create conditions
JSONObject conditionCompMimeType = getConditionJsonObject(null, condCompMimeTypeParams, "compare-mime-type", false, null);
JSONArray conditions = new JSONArray();
conditions.put(conditionCompMimeType);
// create nested action parameters
JSONObject actionCopyParamsJson = new JSONObject();
actionCopyParamsJson.put(MoveActionExecuter.PARAM_ASSOC_QNAME,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "copy"));
actionCopyParamsJson.put(MoveActionExecuter.PARAM_DESTINATION_FOLDER, this.testDestFolder1);
actionCopyParamsJson.put(MoveActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CONTAINS);
// create nested action
JSONObject actionCopyJson = getActionJsonObject(null, CopyActionExecuter.NAME, "CopyTitle", "CopyDesc", false,
actionCopyParamsJson, null, null, null, null);
JSONArray nestedActions = new JSONArray();
nestedActions.put(actionCopyJson);
// create rule's composite action
JSONObject compoActionJson = getActionJsonObject(null, CompositeActionExecuter.NAME, "Rule1Action", "Rule1ActionDesc",
false, null, conditions, nestedActions, null, null);
// create rule to POST
List<String> ruleTypes = new ArrayList<String>();
ruleTypes.add(RuleType.UPDATE);
JSONObject ruleJson = getRuleJsonObject(this.owningNodeRef1, null, "Rule1", "Rule1Desc", ruleTypes,
compoActionJson, false, false, false, null);
// POST rule JSON to rules collection resource
JSONObject resultPostRule = postRules(this.owningNodeRef1, ruleJson);
String ruleNodeRefStr = resultPostRule.getString("ruleNodeRef");
NodeRef ruleNodeRef = new NodeRef(ruleNodeRefStr);
//
// DELETE Rule with rule node ref of Rule just POSTed
// and validate that the Rule has been deleted
//
// construct url to Rule resource we wish to delete
String url = "/api/rules/" + ruleNodeRef.getStoreRef().getProtocol() + "/"
+ ruleNodeRef.getStoreRef().getIdentifier() + "/" + ruleNodeRef.getId();
// delete the rule just POSTed
sendRequest(new DeleteRequest(url), Status.STATUS_OK);
// make sure that the rule just deleted no longer exists
sendRequest(new GetRequest(url), Status.STATUS_NOT_FOUND);
}
public void testGetRule() throws Exception
{
//
// First POST a Rule and get the identifying rule node ref
// from the Rule Details returned
//
// create condition parameters
JSONObject condCompMimeTypeParams = new JSONObject();
condCompMimeTypeParams.put(ComparePropertyValueEvaluator.PARAM_VALUE, "image/png");
// create conditions
JSONObject conditionCompMimeType = getConditionJsonObject(null, condCompMimeTypeParams, "compare-mime-type", false, null);
JSONArray conditions = new JSONArray();
conditions.put(conditionCompMimeType);
// create parameters for nested actions
JSONObject actionCopyParamsJson = new JSONObject();
actionCopyParamsJson.put(MoveActionExecuter.PARAM_ASSOC_QNAME,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "copy"));
actionCopyParamsJson.put(MoveActionExecuter.PARAM_DESTINATION_FOLDER, this.testDestFolder1);
actionCopyParamsJson.put(MoveActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CONTAINS);
// create nested actions
JSONObject actionCopyJson = getActionJsonObject(null, CopyActionExecuter.NAME, "CopyTitle", "CopyDesc", false,
actionCopyParamsJson, null, null, null, null);
JSONArray nestedActions = new JSONArray();
nestedActions.put(actionCopyJson);
// create rule's composite action
JSONObject compoActionJson = getActionJsonObject(null, CompositeActionExecuter.NAME, "Rule1Action", "Rule1ActionDesc",
false, null, conditions, nestedActions, null, null);
// create rule to POST
List<String> ruleTypes = new ArrayList<String>();
ruleTypes.add(RuleType.UPDATE);
JSONObject ruleJson = getRuleJsonObject(this.owningNodeRef1, null, "Rule1", "Rule1Desc", ruleTypes,
compoActionJson, false, false, false, null);
// POST rule JSON to rules collection resource
JSONObject resultPostRule = postRules(this.owningNodeRef1, ruleJson);
String ruleNodeRefStr = resultPostRule.getString("ruleNodeRef");
NodeRef ruleNodeRef = new NodeRef(ruleNodeRefStr);
//
// GET Rule with rule node ref of Rule just POSTed
// and validate that the Rule returned by GET Rule
// is the same as that for the rule just POSTed
//
String getRuleRulesBasedUrl = "/api/rules/" + ruleNodeRef.getStoreRef().getProtocol() + "/"
+ ruleNodeRef.getStoreRef().getIdentifier() + "/" + ruleNodeRef.getId();
Response response = sendRequest(new GetRequest(getRuleRulesBasedUrl), Status.STATUS_OK);
JSONObject resultGetRule = new JSONObject(response.getContentAsString());
String resultRuleNodeRefStr = resultGetRule.getString("ruleNodeRef");
assertEquals(ruleNodeRefStr, resultRuleNodeRefStr);
}
public void testGetRules() throws Exception
{
//
// First POST a Rule
//
// create condition parameters
JSONObject condCompMimeTypeParams = new JSONObject();
condCompMimeTypeParams.put(ComparePropertyValueEvaluator.PARAM_VALUE, "image/png");
// create conditions
JSONObject conditionCompMimeType = getConditionJsonObject(null, condCompMimeTypeParams, "compare-mime-type", false, null);
JSONArray conditions = new JSONArray();
conditions.put(conditionCompMimeType);
// create parameters for nested actions
JSONObject actionCopyParamsJson = new JSONObject();
actionCopyParamsJson.put(MoveActionExecuter.PARAM_ASSOC_QNAME,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "copy"));
actionCopyParamsJson.put(MoveActionExecuter.PARAM_DESTINATION_FOLDER, this.testDestFolder1);
actionCopyParamsJson.put(MoveActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CONTAINS);
// create nested actions
JSONObject actionCopyJson = getActionJsonObject(null, CopyActionExecuter.NAME, "CopyTitle", "CopyDesc", false,
actionCopyParamsJson, null, null, null, null);
JSONArray nestedActions = new JSONArray();
nestedActions.put(actionCopyJson);
// create rule's composite action
JSONObject compoActionJson = getActionJsonObject(null, CompositeActionExecuter.NAME, "Rule1Action", "Rule1ActionDesc",
false, null, conditions, nestedActions, null, null);
// create rule to POST
List<String> ruleTypes = new ArrayList<String>();
ruleTypes.add(RuleType.UPDATE);
JSONObject ruleJson = getRuleJsonObject(this.owningNodeRef1, null, "Rule1", "Rule1Desc", ruleTypes,
compoActionJson, false, false, false, null);
// POST rule JSON to rules collection resource
postRules(this.owningNodeRef1, ruleJson);
//
// GET Rules and test to make sure that POSTed rule is in return Rules collection
//
JSONArray result = getRules(this.owningNodeRef1, null, null, Status.STATUS_OK);
boolean postedRuleFound = false;
for (int i=0; i < result.length(); i++)
{
JSONObject resultRuleJson = result.getJSONObject(i);
String ruleTitle = resultRuleJson.getString("title");
if (ruleTitle.equals("Rule1"))
{
postedRuleFound = true;
}
}
assertTrue(postedRuleFound == true);
}
public void testPostRules()
throws Exception
{
// create condition parameters for compare MIME type condition
JSONObject condCompMimeTypeParams = new JSONObject();
condCompMimeTypeParams.put(ComparePropertyValueEvaluator.PARAM_VALUE, "image/png");
// create compare MIME type condition
JSONObject conditionCompMimeType = getConditionJsonObject(null, condCompMimeTypeParams, "compare-mime-type", false, null);
JSONArray conditions = new JSONArray();
conditions.put(conditionCompMimeType);
// create action parameters for copy action
JSONObject actionCopyParamsJson = new JSONObject();
actionCopyParamsJson.put(MoveActionExecuter.PARAM_ASSOC_QNAME,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "copy").toString());
actionCopyParamsJson.put(MoveActionExecuter.PARAM_DESTINATION_FOLDER, this.testDestFolder1.toString());
actionCopyParamsJson.put(MoveActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CONTAINS.toString());
// create copy action and add to nested actions
JSONObject actionCopyJson = getActionJsonObject(null, CopyActionExecuter.NAME, "CopyActionTitle", "CopyActionDesc", false,
actionCopyParamsJson, null, null, null, null);
JSONArray nestedActions = new JSONArray();
nestedActions.put(actionCopyJson);
// create rule's composite action
JSONObject compoActionJson = getActionJsonObject(null, CompositeActionExecuter.NAME, "Rule1Action", "Rule1ActionDesc",
false, null, conditions, nestedActions, null, null);
// create rule to POST
List<String> ruleTypes = new ArrayList<String>();
ruleTypes.add(RuleType.UPDATE);
JSONObject ruleJson = getRuleJsonObject(this.owningNodeRef1, null, "Rule1", "Rule1Desc", ruleTypes,
compoActionJson, false, false, false, null);
// POST RuleJson to Rules Collection
JSONObject resultRule = postRules(this.owningNodeRef1, ruleJson);
//
// validate rule result
//
NodeRef resultRuleNodeRef = new NodeRef(resultRule.getString("ruleNodeRef"));
assertEquals(this.owningNodeRef1.toString(), resultRule.getString("owningNodeRef"));
assertEquals("Rule1", resultRule.getString("title"));
assertEquals("Rule1Desc", resultRule.getString("description"));
// validate that rule types sent in rule JSON are the same as that returned
// there should only be one, namely "update"
JSONArray resultRuleTypes = resultRule.getJSONArray("ruleTypes");
assertTrue(resultRuleTypes.length() == 1);
assertEquals(RuleType.UPDATE, resultRuleTypes.getString(0));
assertEquals(false, resultRule.getBoolean("executeAsync"));
assertEquals(false, resultRule.getBoolean("ruleDisabled"));
assertEquals(false, resultRule.getBoolean("appliedToChildren"));
// validate rule's composite action from rule in result JSON
JSONObject resultCompoAction = resultRule.getJSONObject("action");
assertEquals(CompositeActionExecuter.NAME, resultCompoAction.getString("actionDefinitionName"));
assertEquals("Rule1Action", resultCompoAction.getString("title"));
assertEquals("Rule1ActionDesc", resultCompoAction.getString("description"));
assertEquals(false, resultCompoAction.getBoolean("executeAsync"));
// validate condition in rule's composite action from the result JSON
// there should only be one, namely the compare MIME type condition
JSONObject resultConditions = resultCompoAction.getJSONObject("conditions");
String resultcondCompMimeTypeKey = resultConditions.names().getString(0);
JSONObject resultcondCompMimeType = resultConditions.getJSONObject(resultcondCompMimeTypeKey);
assertEquals("compare-mime-type", resultcondCompMimeType.getString("conditionDefinitionName"));
assertEquals(false, resultcondCompMimeType.getBoolean("invertCondition"));
// validate parameter values in compare MIME type condition
JSONObject resultCondParamVals = resultcondCompMimeType.getJSONObject("parameterValues");
assertEquals("image/png", resultCondParamVals.getString(ComparePropertyValueEvaluator.PARAM_VALUE));
// validate nested action in rule's composite action from the result JSON
// there should only be one nested action, namely the copy action
JSONObject resultNestedActions = resultCompoAction.getJSONObject("actions");
String resultActionCopyKey = resultNestedActions.names().getString(0);
JSONObject resultCopyAction = resultNestedActions.getJSONObject(resultActionCopyKey);
assertEquals(CopyActionExecuter.NAME, resultCopyAction.getString("actionDefinitionName"));
assertEquals("CopyActionTitle", resultCopyAction.getString("title"));
assertEquals("CopyActionDesc", resultCopyAction.getString("description"));
assertEquals(false, resultCopyAction.getBoolean("executeAsync"));
// validate parameter values in copy action
JSONObject resultActionParamVals = resultCopyAction.getJSONObject("parameterValues");
assertEquals(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "copy").toString(),
resultActionParamVals.getString(MoveActionExecuter.PARAM_ASSOC_QNAME));
assertEquals(this.testDestFolder1.toString(),
resultActionParamVals.getString(MoveActionExecuter.PARAM_DESTINATION_FOLDER));
assertEquals(ContentModel.ASSOC_CONTAINS.toString(),
resultActionParamVals.getString(MoveActionExecuter.PARAM_ASSOC_TYPE_QNAME));
}
public void testPostActionQueue() throws Exception
{
// construct ActionQueue resource URL
String url = "/api/actionqueue";
//
// construct action JSON to put into action queue item
// (which will, in turn, be posted to the action queue)
//
// create action parameters for copy action
JSONObject actionCopyParamsJson = new JSONObject();
actionCopyParamsJson.put(MoveActionExecuter.PARAM_ASSOC_QNAME,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "copy").toString());
actionCopyParamsJson.put(MoveActionExecuter.PARAM_DESTINATION_FOLDER, this.testDestFolder1.toString());
actionCopyParamsJson.put(MoveActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CONTAINS.toString());
// create copy action
JSONObject actionCopyJson = getActionJsonObject(null, CopyActionExecuter.NAME, "CopyActionTitle",
"CopyActionDesc", false, actionCopyParamsJson, null, null, null, null);
//
// create action queue item json
//
JSONObject actionQueueItemJson = new JSONObject();
actionQueueItemJson.put("action", actionCopyJson);
actionQueueItemJson.put("nodeRef", this.testDestFolder1.toString());
actionQueueItemJson.put("checkConditions", true);
actionQueueItemJson.put("executeAsync", false);
Response response = sendRequest(new PostRequest(url, actionQueueItemJson.toString(), "application/json"),
Status.STATUS_OK);
JSONObject result = new JSONObject(response.getContentAsString());
assertNotNull(result);
assertEquals("COMPLETE", result.getString("status"));
}
public void testGetConditionDefs() throws Exception
{
// construct condition definition collection resource URL
String url = "/api/rules/conditiondefs";
Response response = sendRequest(new GetRequest(url),
Status.STATUS_OK);
JSONArray result = new JSONArray(response.getContentAsString());
assertTrue(result.length() > 0);
System.out.println(result);
}
public void testGetConditionDef() throws Exception
{
String conditionDefName = "compare-property-value";
// construct condition definition resource URL
String url = "/api/rules/conditiondefs/" + conditionDefName;
Response response = sendRequest(new GetRequest(url),
Status.STATUS_OK);
JSONObject result = new JSONObject(response.getContentAsString());
assertNotNull(result);
assertEquals("compare-property-value", result.getString("name"));
assertEquals(false, result.getBoolean("adhocPropertiesAllowed"));
}
public void testGetActionDefs() throws Exception
{
// construct action definition collection resource URL
String url = "/api/rules/actiondefs";
Response response = sendRequest(new GetRequest(url),
Status.STATUS_OK);
JSONArray result = new JSONArray(response.getContentAsString());
assertTrue(result.length() > 0);
}
public void testGetActionDef() throws Exception
{
String actionDefName = "transform";
// construct action definition resource URL
String url = "/api/rules/actiondefs/" + actionDefName;
Response response = sendRequest(new GetRequest(url),
Status.STATUS_OK);
JSONObject result = new JSONObject(response.getContentAsString());
assertNotNull(result);
// validate applicable types in returned action definition
boolean applicableTypeContentFound = false;
JSONArray applicableTypes = result.getJSONArray("applicableTypes");
for (int i=0; i < applicableTypes.length(); i++)
{
String applicableType = applicableTypes.getString(i);
if (applicableType.equals("content"))
{
applicableTypeContentFound = true;
}
}
assertTrue(applicableTypeContentFound == true);
assertEquals("transform", result.getString("name"));
assertEquals(false, result.getBoolean("adhocPropertiesAllowed"));
}
}

View File

@@ -37,14 +37,15 @@ import org.alfresco.web.scripts.WebScriptException;
import org.alfresco.web.scripts.WebScriptRequest;
/**
* Web Script to GET the rule collection associated with the given actionable node.
* Web Script to GET the rule collection associated with the given rule owning node.
* The following optional parameters can be provided:
*
* - includeInherited: if provided, then this parameter indicates whether or not to include rules
* inherited from the actionable node's parents. If this parameter is not provided , then rules
* inherited from the owning node's parents. If this parameter is not provided , then rules
* inherited from the node's parents are included by default.
*
* - ruleTypeName: if this parameter is provided, then only rules of this given rule type are returned.
* - ruleTypeName: if this parameter is provided, then only rules of this given rule type are returned.
* If this parameter is not provided then rules of all types will be returned.
*
* @author glen johnson at alfresco dot com
*/
@@ -60,6 +61,7 @@ public class RulesGet extends DeclarativeWebScript
// model property keys
private static final String MODEL_PROP_KEY_RULES = "rules";
private static final String MODEL_PROP_KEY_OWNING_NODE_REF = "owningNodeRef";
// properties for services
private RuleService ruleService;
@@ -123,39 +125,37 @@ public class RulesGet extends DeclarativeWebScript
"The 'nodeId' URL template token has not been provided in URL");
}
//
// get URL parameters
String includeInherited = req.getParameter(REQ_PARAM_INCLUDE_INHERITED);
boolean includeInheritedParamGiven = ((includeInherited != null) && (includeInherited.length() > 0));
//
String ruleTypeName = req.getParameter(REQ_PARAM_RULE_TYPE_NAME);
boolean ruleTypeNameParamGiven = ((ruleTypeName != null) && (ruleTypeName.length() > 0));
// get the 'includeInherited' parameter. The value defaults to 'true' if
// the parameter has not been provided
boolean includeInherited = true;
String includeInheritedParam = req.getParameter(REQ_PARAM_INCLUDE_INHERITED);
if ((includeInheritedParam != null) && (includeInheritedParam.length() > 0))
{
includeInherited = Boolean.parseBoolean(includeInheritedParam);
}
// create the actionable node reference from the given
// URL template tokens
NodeRef actionableNodeRef = this.rulesHelper.getNodeRefFromWebScriptUrl(req, storeType, storeId, nodeId);
// get the 'ruleTypeName' parameter. The value defaults to 'null' if
// the parameter has not been provided
String ruleTypeName = null;
String ruleTypeNameParam = req.getParameter(REQ_PARAM_RULE_TYPE_NAME);
if ((ruleTypeNameParam != null) && (ruleTypeNameParam.length() > 0))
{
ruleTypeName = ruleTypeNameParam;
}
// get rule collection associated with the actionable node
List<Rule> rules = null;
if ((includeInheritedParamGiven == false) && (ruleTypeNameParamGiven == false))
{
rules = this.ruleService.getRules(actionableNodeRef);
}
else if ((includeInheritedParamGiven == true) && (ruleTypeNameParamGiven == false))
{
rules = this.ruleService.getRules(actionableNodeRef, Boolean.parseBoolean(includeInherited));
}
else if ((includeInheritedParamGiven == false) && (ruleTypeNameParamGiven == true))
{
rules = this.ruleService.getRules(actionableNodeRef, true, ruleTypeName);
}
else
// both 'includeInherited' and 'ruleTypeName' parameter values have been given
{
rules = this.ruleService.getRules(actionableNodeRef, Boolean.parseBoolean(includeInherited), ruleTypeName);
}
// create the rule owning node reference from the given URL template tokens
NodeRef owningNodeRef = this.rulesHelper.getNodeRefFromWebScriptUrl(req, storeType, storeId, nodeId);
// get rule collection associated with the rule owning node
List<Rule> rules = this.ruleService.getRules(owningNodeRef, includeInherited, ruleTypeName);
// add objects to model for the template to render
model.put(MODEL_PROP_KEY_RULES, rules);
model.put(MODEL_PROP_KEY_OWNING_NODE_REF, owningNodeRef);
return model;
}

View File

@@ -26,8 +26,10 @@ package org.alfresco.repo.web.scripts.rule;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.alfresco.repo.model.Repository;
import org.alfresco.service.ServiceRegistry;
@@ -69,6 +71,7 @@ public class RulesHelper
private static final String COMPOSITE_ACTION_DEF_NAME = "composite-action";
private static final String REQ_URL_PART_NODE_REF = "/api/node";
private static final String REQ_URL_PART_NODE_PATH = "/api/path";
private static final String REQ_URL_PART_RULE_NODE_REF = "/api/rules";
// service dependencies
private ServiceRegistry serviceRegistry;
@@ -128,7 +131,7 @@ public class RulesHelper
}
/**
* Return a Rule object created/updated from a given rule JSON object.
* Return a Rule object created/updated from a given rule JSON object (Rule Details sent).
*
* If a node reference is passed into the <pre>ruleNodeRefToUpdate</pre> parameter,
* then this indicates that an existing rule (identified by that node
@@ -174,55 +177,42 @@ public class RulesHelper
// set rule properties
//
if ((ruleJson.isNull("title") == true) && (update == true))
if ((ruleJson.isNull("title") == true) && (update == false))
{
// this field is 'null' and we are doing an update
// so don't do anything
// the "title" field is mandatory, it is missing in the rule details,
// and we are creating a new rule, so throw an exception
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "A new rule is being created but the 'title' "
+ "field, which is mandatory, has not been included in the rule details");
}
else
// otherwise go ahead and set the value if the field is present
else if (ruleJson.isNull("title") == false)
{
String ruleTitle = ruleJson.getString("title");
rule.setTitle(ruleTitle);
}
if ((ruleJson.isNull("description") == true) && (update == true))
if (ruleJson.isNull("description") == false)
{
// this field is 'null' and we are doing an update
// so don't do anything
}
else
{
rule.setDescription(ruleJson.optString("description", ""));
rule.setDescription(ruleJson.getString("description"));
}
if ((ruleJson.isNull("executeAsync") == true) && (update == true))
{
// this field is 'null' and we are doing an update
// so don't do anything
}
else
// set values from the respective Boolean fields below, but if the
// if the value given for a field does not equate to either
// 'true' or 'false', then set it to a default value of false
if (ruleJson.isNull("executeAsync") == false)
{
rule.setExecuteAsynchronously(ruleJson.optBoolean("executeAsync", false));
}
if ((ruleJson.isNull("ruleDisabled") == true) && (update == true))
{
// this field is 'null' and we are doing an update
// so don't do anything
}
else
if (ruleJson.isNull("ruleDisabled") == false)
{
rule.setRuleDisabled(ruleJson.optBoolean("ruleDisabled", false));
}
if ((ruleJson.isNull("appliedToChildren") == true) && (update == true))
{
// this field is 'null' and we are doing an update
// so don't do anything
}
else
if (ruleJson.isNull("appliedToChildren") == false)
{
rule.applyToChildren(ruleJson.optBoolean("appliedToChildren", false));
}
@@ -231,12 +221,14 @@ public class RulesHelper
// set rule types present in the rule details onto the rule
//
if ((ruleJson.isNull("ruleTypes") == true) && (update == true))
if ((ruleJson.isNull("ruleTypes") == true) && (update == false))
{
// this field is 'null' and we are doing an update
// so don't do anything
// the "ruleTypes" field is mandatory, it is missing in the rule details,
// and we are creating a new rule so throw an exception
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "A new rule is being created but the 'ruleTypes' "
+ "field, which is mandatory, has not been included in the rule details");
}
else
else if (ruleJson.isNull("ruleTypes") == false)
{
List<String> ruleTypes = new ArrayList<String>();
JSONArray ruleTypesJson = ruleJson.getJSONArray("ruleTypes");
@@ -267,16 +259,44 @@ public class RulesHelper
rule.setRuleTypes(ruleTypes);
}
if ((ruleJson.isNull("action") == true) && (update == true))
if ((ruleJson.isNull("action") == true) && (update == false))
{
// this field is 'null' and we are doing an update
// so don't do anything
// the "action" field is mandatory, it is missing in the rule details,
// and we are creating a new rule so throw an exception
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "A new rule is being created but the 'action' "
+ "field, which is mandatory, has not been included in the rule details");
}
else
{
// set the action supplied in the rule details onto the rule
JSONObject actionJson = ruleJson.getJSONObject("action");
Action action = getActionFromJson(actionJson);
JSONObject ruleActionJson = ruleJson.getJSONObject("action");
// if we're doing an update then the rule should already have
// this action set on it, so get the action object already on
// the rule
Action ruleActionToUpdate = null;
if (update == true)
{
String ruleActionJsonId = ruleActionJson.getString("id");
ruleActionToUpdate = rule.getAction();
// throw a web script exception if the ID of the rule's action,
// already persisted to the repository, is not the same as the one
// given for the rule action's ID in the rule details that we
// wish to perform the rule update with
if (ruleActionToUpdate.getId().equals(ruleActionJsonId) == false)
{
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "The ID sent in the rule details "
+ "of the action directly associated with the rule we wish to update does not match "
+ " the rule's action already persisted in the repository. The rule's nodeRef is: '"
+ ruleNodeRefToUpdate + "', the action ID provided in the rule details is '"
+ ruleActionJsonId + "', and the ID for the rule's action already persisted in the"
+ " repository is '" + ruleActionToUpdate.getId() + "'");
}
}
Action action = getActionFromJson(ruleActionJson, ruleActionToUpdate);
rule.setAction(action);
}
}
@@ -290,18 +310,37 @@ public class RulesHelper
}
/**
* Create and return an Action object from a given action JSON object
* Return an Action object created/updated from a given action JSON object (Action Details sent).
*
* @param actionJson the action JSON object to create the action from
* If an action object is passed into the <pre>actionToUpdate</pre> parameter,
* then this indicates that this action is to be updated from the action details
* provided in the given JSON object and then returned.
* If a 'null' is passed into this parameter, then this indicates that a new action is to
* be created from scratch and returned.
*
* @return The action object created from the given action JSON object
* @param actionJson the action JSON object used to create/update the action with
* @param actionToUpdate The action to be updated.
* Set to <pre>null</pre> if a new action is to be created from scratch.
*
* @return The action created/updated from the given action JSON object
*/
@SuppressWarnings("unchecked")
public Action getActionFromJson(JSONObject actionJson)
public Action getActionFromJson(JSONObject actionJson, Action actionToUpdate)
{
Action action = null;
ActionService actionService = this.serviceRegistry.getActionService();
//
// if we are doing an update then set the action, to be returned, to
// the given actionToUpdate (which will then be updated by the action
// details provided in the action JSON - containing the action details sent)
//
Action action = null;
if (actionToUpdate != null)
{
action = actionToUpdate;
}
try
{
//
@@ -309,26 +348,80 @@ public class RulesHelper
//
String actionDefinitionName = actionJson.getString("actionDefinitionName");
JSONObject nestedActionsJson = actionJson.optJSONObject("actions");
JSONArray nestedActionsJson = actionJson.optJSONArray("actions");
// if action's definition name denotes that it is a composite action and the
// action JSON object has nested actions, then treat it as a composite action
if ((actionDefinitionName.equals(COMPOSITE_ACTION_DEF_NAME)) == true && (nestedActionsJson != null))
{
// create composite action object
action = actionService.createCompositeAction();
// if we are updating an existing action and the given
// actionToUpdate is not a composite action, then throw a
// web script exception
if ((actionToUpdate != null) && ((actionToUpdate instanceof CompositeAction) == false))
{
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "The action directly associated with the "
+ "rule you wish to update is not a composite action. Thus this action could not be updated with "
+ "the given action JSON - the action details sent");
}
// TODO remove this look-up map when the back-end provides an easy way to lookup actions
// on a composite action by ID
// if we are updating an existing composite action then create a map to easily look up the
// nested action objects for each nested action details provided in the action JSON object
Map<String, Action> nestedActionsMap = new HashMap<String, Action>();
if ((actionToUpdate != null) && ((actionToUpdate instanceof CompositeAction) == true))
{
List<Action> nestedActions = ((CompositeAction)action).getActions();
for (Action nestedAction: nestedActions)
{
nestedActionsMap.put(nestedAction.getId(), nestedAction);
}
}
// else if we are not updating then create composite action object
// for scratch
else if (actionToUpdate == null)
{
action = actionService.createCompositeAction();
}
// recursively add nested actions to this composite action
// as some of those nested actions could also be composite actions
Iterator<String> nestedActionsIteractor = nestedActionsJson.keys();
while (nestedActionsIteractor.hasNext())
int numNestedActionsJson = nestedActionsJson.length();
for (int i=0; i < numNestedActionsJson; i++)
{
String nestedActionKey = nestedActionsIteractor.next();
JSONObject nestedActionJson = nestedActionsJson.optJSONObject(nestedActionKey);
JSONObject nestedActionJson = nestedActionsJson.optJSONObject(i);
if (nestedActionJson != null)
{
Action nestedAction = getActionFromJson(nestedActionJson);
Action nestedAction = null;
// if we are doing an action update, then update the nested actions from
// the nested action JSON
if (actionToUpdate != null)
{
String nestedActionJsonID = nestedActionJson.getString("id");
// lookup to see if nested action from nested action JSON
// already exists on composite action, in which case, update
// the nested action with the nested action details provided in the
// nested action JSON
Action nestedActionToUpdate = nestedActionsMap.get(nestedActionJsonID);
if (nestedActionToUpdate != null)
{
// remove the existing nested action to then be updated below with the
// updated one
nestedAction = getActionFromJson(nestedActionJson, nestedActionToUpdate);
}
}
// else we are not doing an action update so just pass in the
// actionToUpdate as 'null'
else
{
nestedAction = getActionFromJson(nestedActionJson, null);
}
((CompositeAction)action).addAction(nestedAction);
}
}
@@ -356,19 +449,48 @@ public class RulesHelper
// set action properties
//
action.setTitle(actionJson.getString("title"));
String descriptionDefault = actionJson.getString("title");
action.setDescription(actionJson.optString("description", descriptionDefault));
if ((actionJson.isNull("title") == true) && (actionToUpdate == null))
{
// the "title" field is mandatory, it is missing in the rule details,
// and we are creating a new rule, so throw an exception
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "A new rule is being created but the 'title' "
+ "field, which is mandatory, has not been included in the rule details");
}
// otherwise go ahead and set the value if the field is present
else if (actionJson.isNull("title") == false)
{
action.setTitle(actionJson.getString("title"));
}
action.setExecuteAsynchronously(actionJson.optBoolean("executeAsync", false));
if (actionJson.isNull("description") == false)
{
action.setDescription(actionJson.optString("description"));
}
// If a value has been provided in the action details for the "executeAsync" field
// then set it to the action object.
// If the value given for a field does not equate to either
// 'true' or 'false', then set it to a default value of false
if (actionJson.isNull("executeAsync") == false)
{
action.setExecuteAsynchronously(actionJson.optBoolean("executeAsync", false));
}
// set compensating action on current action if a compensating action is present
// in the action JSON Object
JSONObject compActionJson = actionJson.optJSONObject("compensatingAction");
if (compActionJson != null)
if (actionJson.isNull("compensatingAction") == false)
{
Action compAction = getActionFromJson(compActionJson);
JSONObject compActionJson = actionJson.getJSONObject("compensatingAction");
Action compActionToUpdate = null;
if (actionToUpdate != null)
{
compActionToUpdate = action.getCompensatingAction();
}
Action compAction = getActionFromJson(compActionJson, compActionToUpdate);
action.setCompensatingAction(compAction);
}
@@ -388,44 +510,101 @@ public class RulesHelper
// set conditions on the current action
//
JSONObject conditionsJson = actionJson.optJSONObject("conditions");
Iterator<String> conditionIterator = conditionsJson.keys();
// get each condition and add it to the action
while (conditionIterator.hasNext())
if (actionJson.isNull("conditions") == false)
{
String conditionKey = conditionIterator.next();
JSONObject conditionJson = conditionsJson.getJSONObject(conditionKey);
JSONArray conditionsJson = actionJson.getJSONArray("conditions");
// create the condition using the given condition definition name
String conditionDefName = conditionJson.getString("conditionDefinitionName");
ActionCondition condition = actionService.createActionCondition(conditionDefName);
// if we are doing an update then build up a condition map
// do be able to do a condition look-up by ID for each condition included
// in the condition JSON - the condition details
// get the condition definition
ParameterizedItemDefinition conditionDef = actionService.getActionConditionDefinition(conditionDefName);
//
// set the condition's properties
//
condition.setInvertCondition(conditionJson.optBoolean("invertCondition", false));
//
// if there are parameter values on the condition JSON object
// then apply them to the condition object
//
JSONObject condParamValuesJson = conditionJson.optJSONObject("parameterValues");
if (condParamValuesJson != null)
Map<String, ActionCondition> conditionsMap = new HashMap<String, ActionCondition>();
if (actionToUpdate != null)
{
setParameterValuesOnParameterizedItemFromJson(condition, conditionDef, condParamValuesJson);
List<ActionCondition> actionConditions = actionToUpdate.getActionConditions();
for (ActionCondition actionCondition : actionConditions)
{
conditionsMap.put(actionCondition.getId(), actionCondition);
}
}
// add condition to action object
action.addActionCondition(condition);
// get each condition and add it to the action
int numConditionsJson = conditionsJson.length();
for (int conditionJsonIndex = 0; conditionJsonIndex < numConditionsJson; conditionJsonIndex++)
{
ActionCondition condition = null;
JSONObject conditionJson = conditionsJson.getJSONObject(conditionJsonIndex);
String conditionDefName = null;
// if we are doing an update, then get the existing condition matching
// the condition ID given in the condition JSON, and update that with
// the condition fields given therein
if (actionToUpdate != null)
{
String conditionJsonId = conditionJson.getString("id");
condition = conditionsMap.get(conditionJsonId);
conditionDefName = condition.getActionConditionDefinitionName();
}
// we are not doing an update, so create the condition using the given condition
// definition name and then populate this new condition from the fields given in
// the condition JSON
else
{
// we are not doing an update, so if the conditionDefinitionName has not been provided
// in the condition JSON then throw a web script exception
if (conditionJson.isNull("conditionDefinitionName"))
{
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "A condition details at index: '"
+ conditionJsonIndex + "' for action ID '" + action.getId() + " could not be created "
+ "because the 'conditionDefinitionName' field is missing from the condition details sent");
}
// else condition def name has been provided in the condition details
else
{
conditionDefName = conditionJson.getString("conditionDefinitionName");
}
condition = actionService.createActionCondition(conditionDefName);
}
// get the condition definition object
ParameterizedItemDefinition conditionDef = actionService.getActionConditionDefinition(conditionDefName);
//
// set the condition's properties
//
// Set the value for the 'invertCondition' field if that field is sent
// in the condition JSON. If the value is sent, but it does not equate to
// either 'true' or 'false', then set it to a default value of false
if (conditionJson.isNull("invertCondition") == false)
{
condition.setInvertCondition(conditionJson.getBoolean("invertCondition"));
}
//
// if there are parameter values on the condition JSON object
// then apply them to the condition object
//
JSONObject condParamValuesJson = conditionJson.optJSONObject("parameterValues");
if (condParamValuesJson != null)
{
setParameterValuesOnParameterizedItemFromJson(condition, conditionDef, condParamValuesJson);
}
// add condition to action object
action.addActionCondition(condition);
// increment the condition JSON index
conditionJsonIndex++;
}
}
}
catch (JSONException je)
{
throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR,
"Problem creating rule from JSON passed into Web Script.", je);
}
@@ -620,7 +799,8 @@ public class RulesHelper
{
// see if given ID is part of either a node reference or a node path
String urlTemplateMatch = req.getServiceMatch().getPath();
boolean nodeRefGiven = urlTemplateMatch.startsWith(REQ_URL_PART_NODE_REF);
boolean nodeRefGiven = urlTemplateMatch.startsWith(REQ_URL_PART_NODE_REF) ||
urlTemplateMatch.startsWith(REQ_URL_PART_RULE_NODE_REF);
boolean nodePathGiven = urlTemplateMatch.startsWith(REQ_URL_PART_NODE_PATH);
String referenceType = null;

View File

@@ -50,7 +50,7 @@ public class RulesPost extends DeclarativeWebScript
// model property keys
private static final String MODEL_PROP_KEY_RULE = "rule";
private static final String MODEL_PROP_KEY_ACTIONABLE_NODE_REF = "actionableNodeRef";
private static final String MODEL_PROP_KEY_OWNING_NODE_REF = "owningNodeRef";
// properties for services
private RuleService ruleService;
@@ -131,14 +131,14 @@ public class RulesPost extends DeclarativeWebScript
// create the actionable node reference from the given
// URL template tokens
NodeRef actionableNodeRef = this.rulesHelper.getNodeRefFromWebScriptUrl(req, storeType, storeId, id);
NodeRef owningNodeRef = this.rulesHelper.getNodeRefFromWebScriptUrl(req, storeType, storeId, id);
// apply rule to actionable node
this.ruleService.saveRule(actionableNodeRef, rule);
this.ruleService.saveRule(owningNodeRef, rule);
// add objects to model for the template to render
model.put(MODEL_PROP_KEY_RULE, rule);
model.put(MODEL_PROP_KEY_ACTIONABLE_NODE_REF, actionableNodeRef);
model.put(MODEL_PROP_KEY_OWNING_NODE_REF, owningNodeRef.toString());
return model;
}