Merged DEV/FORMS-REFACTOR branch to HEAD

git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@14000 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Gavin Cornwell
2009-04-18 22:42:15 +00:00
parent 695f606034
commit c379051889
14 changed files with 1044 additions and 879 deletions

View File

@@ -1,4 +1,4 @@
<#macro formJSON form> <#macro formDefJSON form>
<#escape x as jsonUtils.encodeJSONString(x)> <#escape x as jsonUtils.encodeJSONString(x)>
{ {
"data" : "data" :

View File

@@ -0,0 +1,9 @@
<webscript>
<shortname>Form Definition</shortname>
<description>Returns a form definition for the requested item</description>
<url>/api/form/definition/{item_kind}/{item_id}</url>
<format default="json"/>
<authentication>user</authentication>
<transaction>required</transaction>
<lifecycle>internal</lifecycle>
</webscript>

View File

@@ -0,0 +1,2 @@
<#import "definition.lib.ftl" as formDefLib/>
<@formDefLib.formDefJSON form=form/>

View File

@@ -0,0 +1,149 @@
function main()
{
// Extract template args
var itemKind = url.templateArgs['item_kind'];
var itemId = url.templateArgs['item_id'];
if (logger.isLoggingEnabled())
{
logger.log("itemKind = " + itemKind);
logger.log("itemId = " + itemId);
}
// TODO: Return error if item kind and/or id is missing?
// extract optional data from request body (if present)
var count = 0;
var fields = null;
if (json.has("fields"))
{
// convert the JSONArray object into a native JavaScript array
fields = [];
var jsonFields = json.get("fields");
var numFields = jsonFields.length();
for (count = 0; count < numFields; count++)
{
fields.push(jsonFields.get(count));
}
if (logger.isLoggingEnabled())
logger.log("fields = " + fields);
}
var forcedFields = null;
if (json.has("force"))
{
// convert the JSONArray object into a native JavaScript array
forcedFields = [];
var jsonForcedFields = json.get("force");
var numForcedFields = jsonForcedFields.length();
for (count = 0; count < numForcedFields; count++)
{
forcedFields.push(jsonForcedFields.get(count));
}
if (logger.isLoggingEnabled())
logger.log("forcedFields = " + forcedFields);
}
var formScriptObj = null;
try
{
// attempt to get the form for the item
formScriptObj = formService.getForm(itemKind, itemId, fields, forcedFields);
}
catch (error)
{
var msg = error.message;
if (logger.isLoggingEnabled())
logger.log(msg);
// determine if the exception was a FormNotFoundException, if so return
// 404 status code otherwise return 500
if (msg.indexOf("FormNotFoundException") != -1)
{
status.setCode(404, msg);
if (logger.isLoggingEnabled())
logger.log("Returning 404 status code");
}
else
{
status.setCode(500, msg);
if (logger.isLoggingEnabled())
logger.log("Returning 500 status code");
}
return;
}
var formModel = {};
formModel.data = {};
// TODO: retrieve the item URL from the response?
formModel.data.item = '/api/form/definition/' + itemKind + '/' + itemId;
// TODO: look for overridden submission url
formModel.data.submissionUrl = '/api/form/' + itemKind + '/' + itemId;
formModel.data.type = formScriptObj.type;
formModel.data.definition = {};
formModel.data.definition.fields = [];
// We're explicitly listing the object fields of FieldDefinition.java and its subclasses here.
// I don't see a way to get these dynamically at runtime.
var supportedBaseFieldNames = ['name', 'label', 'description', 'binding',
'defaultValue', 'group', 'protectedField'];
var supportedPropertyFieldNames = ['dataType', 'mandatory',
'repeats', 'constraints'];
var supportedAssociationFieldNames = ['endpointType', 'endpointDirection',
'endpointMandatory', 'endpointMany'];
var allSupportedFieldNames = supportedBaseFieldNames
.concat(supportedPropertyFieldNames)
.concat(supportedAssociationFieldNames);
var fieldDefs = formScriptObj.fieldDefinitions;
for (var x = 0; x < fieldDefs.length; x++)
{
var fieldDef = fieldDefs[x];
var field = {};
for (var i = 0; i < allSupportedFieldNames.length; i++)
{
var nextSupportedName = allSupportedFieldNames[i];
var nextValue = fieldDef[nextSupportedName];
if (nextValue != null)
{
field[nextSupportedName] = nextValue;
}
}
field.type = (fieldDef.dataType != null) ? "property" : "association";
formModel.data.definition.fields.push(field);
}
formModel.data.formData = {};
for (var k in formScriptObj.formData.data)
{
var value = formScriptObj.formData.data[k].value;
if (value instanceof java.util.Date)
{
formModel.data.formData[k.replace(/:/g, "_")] = utils.toISO8601(value);
}
// There is no need to handle java.util.List instances here as they are
// returned from ScriptFormData.java as Strings
else
{
formModel.data.formData[k.replace(/:/g, "_")] = value;
}
}
model.form = formModel;
}
main();

View File

@@ -1,10 +0,0 @@
<webscript>
<shortname>Form</shortname>
<description>Get a form to view or edit the metadata of a given node.</description>
<url>/api/forms/node/{store_type}/{store_id}/{id}</url>
<url>/api/forms/node/{path}</url>
<format default="json"/>
<authentication>user</authentication>
<transaction>required</transaction>
<lifecycle>internal</lifecycle>
</webscript>

View File

@@ -1,111 +0,0 @@
function main()
{
// Extract template args
var ta_storeType = url.templateArgs['store_type'];
var ta_storeId = url.templateArgs['store_id'];
var ta_id = url.templateArgs['id'];
var ta_path = url.templateArgs['path'];
if (logger.isLoggingEnabled())
{
logger.log("ta_storeType = " + ta_storeType);
logger.log("ta_storeId = " + ta_storeId);
logger.log("ta_id = " + ta_id);
logger.log("ta_path = " + ta_path);
}
var formUrl = '';
// The template argument 'path' only appears in the second URI template.
if (ta_path != null)
{
//TODO Need to test this path.
formUrl = ta_path;
}
else
{
formUrl = ta_storeType + '://' + ta_storeId + '/' + ta_id;
}
if (logger.isLoggingEnabled())
{
logger.log("formUrl = " + formUrl);
}
var formScriptObj = formService.getForm(formUrl);
if (formScriptObj == null)
{
var message = "The form for item \"" + formUrl + "\" could not be found.";
if (logger.isWarnLoggingEnabled())
{
logger.warn(message);
}
status.setCode(404, message);
return;
}
var formModel = {};
formModel.data = {};
formModel.data.item = '/api/node/' + ta_storeType + '/' + ta_storeId + '/' + ta_id;
formModel.data.submissionUrl = '/api/forms/node/' + ta_storeType + '/' + ta_storeId + '/' + ta_id;
formModel.data.type = formScriptObj.type;
formModel.data.definition = {};
formModel.data.definition.fields = [];
// We're explicitly listing the object fields of FieldDefinition.java and its subclasses here.
// I don't see a way to get these dynamically at runtime.
var supportedBaseFieldNames = ['name', 'label', 'description', 'binding',
'defaultValue', 'group', 'protectedField'];
var supportedPropertyFieldNames = ['dataType', 'mandatory',
'repeats', 'constraints'];
var supportedAssociationFieldNames = ['endpointType', 'endpointDirection',
'endpointMandatory', 'endpointMany'];
var allSupportedFieldNames = supportedBaseFieldNames
.concat(supportedPropertyFieldNames)
.concat(supportedAssociationFieldNames);
var fieldDefs = formScriptObj.fieldDefinitions;
for (var x = 0; x < fieldDefs.length; x++)
{
var fieldDef = fieldDefs[x];
var field = {};
for (var i = 0; i < allSupportedFieldNames.length; i++)
{
var nextSupportedName = allSupportedFieldNames[i];
var nextValue = fieldDef[nextSupportedName];
if (nextValue != null)
{
field[nextSupportedName] = nextValue;
}
}
field.type = (fieldDef.dataType != null) ? "property" : "association";
formModel.data.definition.fields.push(field);
}
formModel.data.formData = {};
for (var k in formScriptObj.formData.data)
{
var value = formScriptObj.formData.data[k].value;
if (value instanceof java.util.Date)
{
formModel.data.formData[k.replace(/:/g, "_")] = utils.toISO8601(value);
}
// There is no need to handle java.util.List instances here as they are
// returned from ScriptFormData.java as Strings
else
{
formModel.data.formData[k.replace(/:/g, "_")] = value;
}
}
model.form = formModel;
}
main();

View File

@@ -1,2 +0,0 @@
<#import "form.lib.ftl" as formLib/>
<@formLib.formJSON form=form/>

View File

@@ -1,8 +1,7 @@
<webscript> <webscript>
<shortname>Form</shortname> <shortname>Form</shortname>
<description>Handles the submission of a form</description> <description>Handles the submission of a form</description>
<url>/api/forms/node/{store_type}/{store_id}/{id}</url> <url>/api/form/{item_kind}/{item_id}</url>
<url>/api/forms/node/{path}</url>
<authentication>user</authentication> <authentication>user</authentication>
<transaction>required</transaction> <transaction>required</transaction>
<lifecycle>internal</lifecycle> <lifecycle>internal</lifecycle>

View File

@@ -1,69 +1,81 @@
function main() function main()
{ {
var ta_storeType = url.templateArgs['store_type']; // Extract template args
var ta_storeId = url.templateArgs['store_id']; var itemKind = url.templateArgs['item_kind'];
var ta_id = url.templateArgs['id']; var itemId = url.templateArgs['item_id'];
var ta_mode = url.templateArgs['mode'];
var ta_path = url.templateArgs['path'];
var nodeRef = '';
// The template argument 'path' only appears in the second URI template.
if (ta_path != null)
{
nodeRef = ta_path;
}
else
{
nodeRef = ta_storeType + '://' + ta_storeId + '/' + ta_id;
}
if (logger.isLoggingEnabled())
{
logger.log("POST request received for nodeRef: " + nodeRef);
}
// TODO: check the given nodeRef is real
// persist the submitted data using the most appropriate data set
if (typeof formdata !== "undefined")
{
// The model.data is set here to allow the rendering of a simple result page.
// TODO This should be removed when the POST is working.
model.data = formdata;
// Note: This formdata is org/alfresco/web/scripts/servlet/FormData.java
if (logger.isLoggingEnabled())
{
logger.log("Saving form with formdata, " + formdata.fields.length + " fields.");
}
// N.B. This repoFormData is a different FormData class to that used above. if (logger.isLoggingEnabled())
var repoFormData = new Packages.org.alfresco.repo.forms.FormData(); {
for (var i = 0; i < formdata.fields.length; i++) logger.log("itemKind = " + itemKind);
{ logger.log("itemId = " + itemId);
// Replace the first 2 underscores with colons. }
var alteredName = formdata.fields[i].name.replaceFirst("_", ":").replaceFirst("_", ":");
repoFormData.addData(alteredName, formdata.fields[i].value); // TODO: Return error if item kind and/or id is missing?
}
try
formService.saveForm(nodeRef, repoFormData); {
} // persist the submitted data using the most appropriate data set
else if (typeof formdata !== "undefined")
{ {
if (logger.isLoggingEnabled()) // The model.data is set here to allow the rendering of a simple result page.
{ // TODO This should be removed when the POST is working.
logger.log("Saving form with args = " + args); model.data = formdata;
}
formService.saveForm(nodeRef, args); // Note: This formdata is org/alfresco/web/scripts/servlet/FormData.java
} if (logger.isLoggingEnabled())
{
model.message = "Successfully updated node " + nodeRef; logger.log("Saving form with formdata, " + formdata.fields.length + " fields.");
}
// N.B. This repoFormData is a different FormData class to that used above.
var repoFormData = new Packages.org.alfresco.repo.forms.FormData();
for (var i = 0; i < formdata.fields.length; i++)
{
// Replace the first 2 underscores with colons.
var alteredName = formdata.fields[i].name.replaceFirst("_", ":").replaceFirst("_", ":");
repoFormData.addData(alteredName, formdata.fields[i].value);
}
formService.saveForm(itemKind, itemId, repoFormData);
}
else
{
if (logger.isLoggingEnabled())
{
logger.log("Saving form with args = " + args);
}
formService.saveForm(itemKind, itemId, args);
}
}
catch (error)
{
var msg = error.message;
if (logger.isLoggingEnabled())
logger.log(msg);
// determine if the exception was a FormNotFoundException, if so return
// 404 status code otherwise return 500
if (msg.indexOf("FormNotFoundException") != -1)
{
status.setCode(404, msg);
if (logger.isLoggingEnabled())
logger.log("Returning 404 status code");
}
else
{
status.setCode(500, msg);
if (logger.isLoggingEnabled())
logger.log("Returning 500 status code");
}
return;
}
model.message = "Successfully updated item [" + itemKind + "]" + itemId;
} }
main(); main();

View File

@@ -1,59 +1,76 @@
function main() function main()
{ {
var ta_storeType = url.templateArgs['store_type']; // Extract template args
var ta_storeId = url.templateArgs['store_id']; var itemKind = url.templateArgs['item_kind'];
var ta_id = url.templateArgs['id']; var itemId = url.templateArgs['item_id'];
var ta_mode = url.templateArgs['mode'];
var ta_path = url.templateArgs['path'];
var nodeRef = '';
// The template argument 'path' only appears in the second URI template.
if (ta_path != null)
{
nodeRef = ta_path;
}
else
{
nodeRef = ta_storeType + '://' + ta_storeId + '/' + ta_id;
}
if (logger.isLoggingEnabled())
{
logger.log("JSON POST request received for nodeRef: " + nodeRef);
}
//TODO Add check whether nodeRef exists. if (logger.isLoggingEnabled())
{
logger.log("itemKind = " + itemKind);
if (typeof json !== "undefined") logger.log("itemId = " + itemId);
{ }
// At this point the field names are e.g. prop_cm_name
// and there are some extra values - hidden fields? These are fields from YUI's datepicker(s)
// e.g. "template_x002e_form-ui_x002e_form-test_prop_my_date-entry":"2/19/2009"
}
else
{
if (logger.isWarnLoggingEnabled())
{
logger.warn("json object was undefined.");
}
status.setCode(501, message);
return;
}
var repoFormData = new Packages.org.alfresco.repo.forms.FormData();
var jsonKeys = json.keys();
for ( ; jsonKeys.hasNext(); )
{
// Replace the first 2 underscores with colons.
var nextKey = jsonKeys.next();
var alteredKey = nextKey.replaceFirst("_", ":").replaceFirst("_", ":");
repoFormData.addData(alteredKey, json.get(nextKey));
}
formService.saveForm(nodeRef, repoFormData); // TODO: Return error if item kind and/or id is missing?
model.message = "Successfully updated node " + nodeRef; if (typeof json !== "undefined")
{
// At this point the field names are e.g. prop_cm_name
// and there are some extra values - hidden fields? These are fields from YUI's datepicker(s)
// e.g. "template_x002e_form-ui_x002e_form-test_prop_my_date-entry":"2/19/2009"
}
else
{
if (logger.isWarnLoggingEnabled())
{
logger.warn("json object was undefined.");
}
status.setCode(501, message);
return;
}
var repoFormData = new Packages.org.alfresco.repo.forms.FormData();
var jsonKeys = json.keys();
for ( ; jsonKeys.hasNext(); )
{
// Replace the first 2 underscores with colons.
var nextKey = jsonKeys.next();
var alteredKey = nextKey.replaceFirst("_", ":").replaceFirst("_", ":");
repoFormData.addData(alteredKey, json.get(nextKey));
}
try
{
formService.saveForm(itemKind, itemId, repoFormData);
}
catch (error)
{
var msg = error.message;
if (logger.isLoggingEnabled())
logger.log(msg);
// determine if the exception was a FormNotFoundException, if so return
// 404 status code otherwise return 500
if (msg.indexOf("FormNotFoundException") != -1)
{
status.setCode(404, msg);
if (logger.isLoggingEnabled())
logger.log("Returning 404 status code");
}
else
{
status.setCode(500, msg);
if (logger.isLoggingEnabled())
logger.log("Returning 500 status code");
}
return;
}
model.message = "Successfully updated item [" + itemKind + "]" + itemId;
} }
main(); main();

View File

@@ -1,14 +1,14 @@
function main() function main()
{ {
//FIXME URL-encoded post of forms data is not yet working. // FIXME URL-encoded post of forms data is not yet working.
if (logger.isLoggingEnabled()) if (logger.isLoggingEnabled())
{ {
logger.log("x-www-form-urlencoded request received for nodeRef"); logger.log("x-www-form-urlencoded request received");
logger.log("decodedparams: " + decodedparams); logger.log("decodedparams: " + decodedparams);
} }
model.message = "Successfully updated node " + "nodeRef"; model.message = "Successfully updated item";
} }
main(); main();

View File

@@ -1,205 +1,219 @@
/* /*
* Copyright (C) 2005-2009 Alfresco Software Limited. * Copyright (C) 2005-2009 Alfresco Software Limited.
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2 * as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. * of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * 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 * 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 * the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's * and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have received a copy of the text describing * FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here: * the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing" * http://www.alfresco.com/legal/licensing"
*/ */
package org.alfresco.repo.web.scripts.forms; package org.alfresco.repo.web.scripts.forms;
import java.io.IOException; import java.io.IOException;
import java.io.Serializable; import java.io.Serializable;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.alfresco.model.ContentModel; import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap; import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.model.Repository; import org.alfresco.repo.model.Repository;
import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.web.scripts.BaseWebScriptTest; import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.service.cmr.model.FileFolderService; import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.model.FileInfo; import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.ContentService; import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter; import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.namespace.NamespaceService; import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName; import org.alfresco.service.namespace.QName;
import org.alfresco.util.GUID; import org.alfresco.util.GUID;
import org.alfresco.web.scripts.TestWebScriptServer.GetRequest; import org.alfresco.web.scripts.TestWebScriptServer.GetRequest;
import org.alfresco.web.scripts.TestWebScriptServer.Response; import org.alfresco.web.scripts.TestWebScriptServer.Response;
public abstract class AbstractTestFormRestApi extends BaseWebScriptTest public abstract class AbstractTestFormRestApi extends BaseWebScriptTest
{ {
protected static final String TEST_FORM_DESCRIPTION = "Test form description"; protected static final String APPLICATION_JSON = "application/json";
protected static final String TEST_FORM_TITLE = "Test form title"; protected static final String TEST_FORM_DESCRIPTION = "Test form description";
protected String referencingNodeUrl; protected static final String TEST_FORM_TITLE = "Test form title";
protected String containingNodeUrl; protected String referencingNodeDefUrl;
protected NodeRef referencingDocNodeRef; protected String referencingNodeUpdateUrl;
protected Map<QName, Serializable> refNodePropertiesAfterCreation; protected String containingNodeDefUrl;
protected NodeRef associatedDoc_A; protected String containingNodeUpdateUrl;
protected NodeRef associatedDoc_B; protected String containingNodeUrl;
protected NodeRef associatedDoc_C; protected NodeRef referencingDocNodeRef;
protected NodeRef associatedDoc_D; protected Map<QName, Serializable> refNodePropertiesAfterCreation;
protected NodeRef associatedDoc_E; protected NodeRef associatedDoc_A;
protected NodeRef childDoc_A; protected NodeRef associatedDoc_B;
protected NodeRef childDoc_B; protected NodeRef associatedDoc_C;
protected NodeRef childDoc_C; protected NodeRef associatedDoc_D;
protected NodeRef childDoc_D; protected NodeRef associatedDoc_E;
protected NodeRef childDoc_E; protected NodeRef childDoc_A;
protected NodeRef testFolderNodeRef; protected NodeRef childDoc_B;
protected NodeRef childDoc_C;
protected NodeService nodeService; protected NodeRef childDoc_D;
private FileFolderService fileFolderService; protected NodeRef childDoc_E;
private ContentService contentService; protected NodeRef testFolderNodeRef;
private Repository repositoryHelper;
protected NodeRef containerNodeRef; protected NodeService nodeService;
private FileFolderService fileFolderService;
@Override private ContentService contentService;
protected void setUp() throws Exception private Repository repositoryHelper;
{ protected NodeRef containerNodeRef;
super.setUp();
this.fileFolderService = (FileFolderService) getServer().getApplicationContext().getBean( @Override
"FileFolderService"); protected void setUp() throws Exception
this.contentService = (ContentService) getServer().getApplicationContext().getBean( {
"ContentService"); super.setUp();
this.repositoryHelper = (Repository) getServer().getApplicationContext().getBean( this.fileFolderService = (FileFolderService) getServer().getApplicationContext().getBean(
"repositoryHelper"); "FileFolderService");
this.nodeService = (NodeService) getServer().getApplicationContext().getBean("NodeService"); this.contentService = (ContentService) getServer().getApplicationContext().getBean(
"ContentService");
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName()); this.repositoryHelper = (Repository) getServer().getApplicationContext().getBean(
"repositoryHelper");
NodeRef companyHomeNodeRef = this.repositoryHelper.getCompanyHome(); this.nodeService = (NodeService) getServer().getApplicationContext().getBean("NodeService");
String guid = GUID.generate(); AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
// Create a test file (not a folder) NodeRef companyHomeNodeRef = this.repositoryHelper.getCompanyHome();
FileInfo referencingDoc = this.fileFolderService.create(companyHomeNodeRef,
"referencingDoc" + guid + ".txt", ContentModel.TYPE_CONTENT); String guid = GUID.generate();
referencingDocNodeRef = referencingDoc.getNodeRef();
// Create a test file (not a folder)
// Add an aspect. FileInfo referencingDoc = this.fileFolderService.create(companyHomeNodeRef,
Map<QName, Serializable> aspectProps = new HashMap<QName, Serializable>(2); "referencingDoc" + guid + ".txt", ContentModel.TYPE_CONTENT);
aspectProps.put(ContentModel.PROP_TITLE, TEST_FORM_TITLE); referencingDocNodeRef = referencingDoc.getNodeRef();
aspectProps.put(ContentModel.PROP_DESCRIPTION, TEST_FORM_DESCRIPTION);
nodeService.addAspect(referencingDocNodeRef, ContentModel.ASPECT_TITLED, aspectProps); // Add an aspect.
Map<QName, Serializable> aspectProps = new HashMap<QName, Serializable>(2);
// Write some content into the node. aspectProps.put(ContentModel.PROP_TITLE, TEST_FORM_TITLE);
ContentWriter contentWriter = this.contentService.getWriter(referencingDoc.getNodeRef(), aspectProps.put(ContentModel.PROP_DESCRIPTION, TEST_FORM_DESCRIPTION);
ContentModel.PROP_CONTENT, true); nodeService.addAspect(referencingDocNodeRef, ContentModel.ASPECT_TITLED, aspectProps);
contentWriter.setEncoding("UTF-8");
contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN); // Write some content into the node.
contentWriter.putContent("The quick brown fox jumped over the lazy dog."); ContentWriter contentWriter = this.contentService.getWriter(referencingDoc.getNodeRef(),
ContentModel.PROP_CONTENT, true);
// Create a folder - will use this for child-association testing contentWriter.setEncoding("UTF-8");
FileInfo associatedDocsFolder = contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
this.fileFolderService.create(companyHomeNodeRef, "testFolder" + guid, ContentModel.TYPE_FOLDER); contentWriter.putContent("The quick brown fox jumped over the lazy dog.");
testFolderNodeRef = associatedDocsFolder.getNodeRef(); // Create a folder - will use this for child-association testing
FileInfo associatedDocsFolder =
this.associatedDoc_A = createTestNode("associatedDoc_A" + guid); this.fileFolderService.create(companyHomeNodeRef, "testFolder" + guid, ContentModel.TYPE_FOLDER);
this.associatedDoc_B = createTestNode("associatedDoc_B" + guid);
this.associatedDoc_C = createTestNode("associatedDoc_C" + guid); testFolderNodeRef = associatedDocsFolder.getNodeRef();
this.associatedDoc_D = createTestNode("associatedDoc_D" + guid);
this.associatedDoc_E = createTestNode("associatedDoc_E" + guid); this.associatedDoc_A = createTestNode("associatedDoc_A" + guid);
this.associatedDoc_B = createTestNode("associatedDoc_B" + guid);
// Now create associations between the referencing and the two node refs. this.associatedDoc_C = createTestNode("associatedDoc_C" + guid);
aspectProps.clear(); this.associatedDoc_D = createTestNode("associatedDoc_D" + guid);
this.nodeService.addAspect(this.referencingDocNodeRef, ContentModel.ASPECT_REFERENCING, aspectProps); this.associatedDoc_E = createTestNode("associatedDoc_E" + guid);
this.nodeService.createAssociation(this.referencingDocNodeRef, associatedDoc_A, ContentModel.ASSOC_REFERENCES);
this.nodeService.createAssociation(this.referencingDocNodeRef, associatedDoc_B, ContentModel.ASSOC_REFERENCES); // Now create associations between the referencing and the two node refs.
// Leave the 3rd, 4th and 5th nodes without associations as they may be created in aspectProps.clear();
// other test code. this.nodeService.addAspect(this.referencingDocNodeRef, ContentModel.ASPECT_REFERENCING, aspectProps);
this.nodeService.createAssociation(this.referencingDocNodeRef, associatedDoc_A, ContentModel.ASSOC_REFERENCES);
// Create a container for the children. this.nodeService.createAssociation(this.referencingDocNodeRef, associatedDoc_B, ContentModel.ASSOC_REFERENCES);
HashMap<QName, Serializable> containerProps = new HashMap<QName, Serializable>(); // Leave the 3rd, 4th and 5th nodes without associations as they may be created in
this.containerNodeRef = nodeService.createNode(companyHomeNodeRef, ContentModel.ASSOC_CONTAINS, // other test code.
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "testContainer" + guid),
ContentModel.TYPE_CONTAINER, // Create a container for the children.
containerProps).getChildRef(); HashMap<QName, Serializable> containerProps = new HashMap<QName, Serializable>();
this.containerNodeRef = nodeService.createNode(companyHomeNodeRef, ContentModel.ASSOC_CONTAINS,
this.childDoc_A = createTestNode("childDoc_A" + guid); QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "testContainer" + guid),
this.childDoc_B = createTestNode("childDoc_B" + guid); ContentModel.TYPE_CONTAINER,
this.childDoc_C = createTestNode("childDoc_C" + guid); containerProps).getChildRef();
this.childDoc_D = createTestNode("childDoc_D" + guid);
this.childDoc_E = createTestNode("childDoc_E" + guid); this.childDoc_A = createTestNode("childDoc_A" + guid);
this.childDoc_B = createTestNode("childDoc_B" + guid);
// Now create the pre-test child-associations. this.childDoc_C = createTestNode("childDoc_C" + guid);
this.nodeService.addChild(containerNodeRef, childDoc_A, ContentModel.ASSOC_CHILDREN, QName.createQName("childA")); this.childDoc_D = createTestNode("childDoc_D" + guid);
this.nodeService.addChild(containerNodeRef, childDoc_B, ContentModel.ASSOC_CHILDREN, QName.createQName("childB")); this.childDoc_E = createTestNode("childDoc_E" + guid);
// The other childDoc nodes will be added as children over the REST API as part
// of later test code. // Now create the pre-test child-associations.
this.nodeService.addChild(containerNodeRef, childDoc_A, ContentModel.ASSOC_CHILDREN, QName.createQName("childA"));
// Create and store the url to the referencingNode this.nodeService.addChild(containerNodeRef, childDoc_B, ContentModel.ASSOC_CHILDREN, QName.createQName("childB"));
StringBuilder builder = new StringBuilder(); // The other childDoc nodes will be added as children over the REST API as part
builder.append("/api/forms/node/workspace/").append(referencingDocNodeRef.getStoreRef().getIdentifier()) // of later test code.
.append("/").append(referencingDocNodeRef.getId());
this.referencingNodeUrl = builder.toString(); // Create and store the urls to the referencingNode
StringBuilder builder = new StringBuilder();
// Create and store the url to the containing node builder.append("/api/form/definition/node/workspace/").append(referencingDocNodeRef.getStoreRef().getIdentifier())
builder = new StringBuilder(); .append("/").append(referencingDocNodeRef.getId());
builder.append("/api/forms/node/workspace/").append(containerNodeRef.getStoreRef().getIdentifier()) this.referencingNodeDefUrl = builder.toString();
.append("/").append(containerNodeRef.getId());
this.containingNodeUrl = builder.toString(); builder = new StringBuilder();
builder.append("/api/form/node/workspace/").append(referencingDocNodeRef.getStoreRef().getIdentifier())
// Store the original properties of this node .append("/").append(referencingDocNodeRef.getId());
this.refNodePropertiesAfterCreation = nodeService.getProperties(referencingDocNodeRef); this.referencingNodeUpdateUrl = builder.toString();
refNodePropertiesAfterCreation.toString(); // Create and store the urls to the containing node
} builder = new StringBuilder();
builder.append("/api/form/definition/node/workspace/").append(containerNodeRef.getStoreRef().getIdentifier())
@Override .append("/").append(containerNodeRef.getId());
public void tearDown() this.containingNodeDefUrl = builder.toString();
{
nodeService.deleteNode(this.referencingDocNodeRef); builder = new StringBuilder();
nodeService.deleteNode(this.associatedDoc_A); builder.append("/api/form/node/workspace/").append(containerNodeRef.getStoreRef().getIdentifier())
nodeService.deleteNode(this.associatedDoc_B); .append("/").append(containerNodeRef.getId());
nodeService.deleteNode(this.associatedDoc_C); this.containingNodeUpdateUrl = builder.toString();
nodeService.deleteNode(this.associatedDoc_D);
nodeService.deleteNode(this.associatedDoc_E); // Store the original properties of this node
nodeService.deleteNode(this.childDoc_A); this.refNodePropertiesAfterCreation = nodeService.getProperties(referencingDocNodeRef);
nodeService.deleteNode(this.childDoc_B);
nodeService.deleteNode(this.childDoc_C); refNodePropertiesAfterCreation.toString();
nodeService.deleteNode(this.childDoc_D); }
nodeService.deleteNode(this.childDoc_E);
nodeService.deleteNode(this.testFolderNodeRef); @Override
nodeService.deleteNode(this.containerNodeRef); public void tearDown()
} {
nodeService.deleteNode(this.referencingDocNodeRef);
protected Response sendGetReq(String url, int expectedStatusCode) nodeService.deleteNode(this.associatedDoc_A);
throws IOException, UnsupportedEncodingException nodeService.deleteNode(this.associatedDoc_B);
{ nodeService.deleteNode(this.associatedDoc_C);
Response result = sendRequest(new GetRequest(url), expectedStatusCode); nodeService.deleteNode(this.associatedDoc_D);
return result; nodeService.deleteNode(this.associatedDoc_E);
} nodeService.deleteNode(this.childDoc_A);
nodeService.deleteNode(this.childDoc_B);
protected NodeRef createTestNode(String associatedDocName) nodeService.deleteNode(this.childDoc_C);
{ nodeService.deleteNode(this.childDoc_D);
Map<QName, Serializable> docProps = new HashMap<QName, Serializable>(1); nodeService.deleteNode(this.childDoc_E);
docProps.put(ContentModel.PROP_NAME, associatedDocName + ".txt"); nodeService.deleteNode(this.testFolderNodeRef);
return this.nodeService.createNode( nodeService.deleteNode(this.containerNodeRef);
testFolderNodeRef, }
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, associatedDocName + ".txt"), protected Response sendGetReq(String url, int expectedStatusCode)
ContentModel.TYPE_CONTENT, throws IOException, UnsupportedEncodingException
docProps).getChildRef(); {
} Response result = sendRequest(new GetRequest(url), expectedStatusCode);
return result;
}
protected NodeRef createTestNode(String associatedDocName)
{
Map<QName, Serializable> docProps = new HashMap<QName, Serializable>(1);
docProps.put(ContentModel.PROP_NAME, associatedDocName + ".txt");
return this.nodeService.createNode(
testFolderNodeRef,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, associatedDocName + ".txt"),
ContentModel.TYPE_CONTENT,
docProps).getChildRef();
}
} }

View File

@@ -28,30 +28,41 @@ import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.web.scripts.TestWebScriptServer.PostRequest;
import org.alfresco.web.scripts.TestWebScriptServer.Response; import org.alfresco.web.scripts.TestWebScriptServer.Response;
import org.alfresco.web.scripts.json.JSONUtils; import org.alfresco.web.scripts.json.JSONUtils;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import org.json.JSONTokener; import org.json.JSONTokener;
public class FormRestApiGet_Test extends AbstractTestFormRestApi { public class FormRestApiGet_Test extends AbstractTestFormRestApi
{
public void testResponseContentType() throws Exception public void testResponseContentType() throws Exception
{ {
Response rsp = sendGetReq(referencingNodeUrl, 200); JSONObject jsonPostData = new JSONObject();
String jsonPostString = jsonPostData.toString();
Response rsp = sendRequest(new PostRequest(referencingNodeDefUrl,
jsonPostString, APPLICATION_JSON), 200);
assertEquals("application/json;charset=UTF-8", rsp.getContentType()); assertEquals("application/json;charset=UTF-8", rsp.getContentType());
} }
public void testGetFormForNonExistentNode() throws Exception public void testGetFormForNonExistentNode() throws Exception
{ {
// Replace all digits with an 'x' char - this should make for a non-existent node. // Replace all digits with an 'x' char - this should make for a non-existent node.
Response rsp = sendGetReq(referencingNodeUrl.replaceAll("\\d", "x"), 404); JSONObject jsonPostData = new JSONObject();
String jsonPostString = jsonPostData.toString();
Response rsp = sendRequest(new PostRequest(referencingNodeDefUrl.replaceAll("\\d", "x"),
jsonPostString, APPLICATION_JSON), 404);
assertEquals("application/json;charset=UTF-8", rsp.getContentType()); assertEquals("application/json;charset=UTF-8", rsp.getContentType());
} }
public void testJsonContentParsesCorrectly() throws Exception public void testJsonContentParsesCorrectly() throws Exception
{ {
Response rsp = sendGetReq(referencingNodeUrl, 200); JSONObject jsonPostData = new JSONObject();
String jsonPostString = jsonPostData.toString();
Response rsp = sendRequest(new PostRequest(referencingNodeDefUrl,
jsonPostString, APPLICATION_JSON), 200);
String jsonResponseString = rsp.getContentAsString(); String jsonResponseString = rsp.getContentAsString();
Object jsonObject = new JSONUtils().toObject(jsonResponseString); Object jsonObject = new JSONUtils().toObject(jsonResponseString);
@@ -60,7 +71,10 @@ public class FormRestApiGet_Test extends AbstractTestFormRestApi {
public void testJsonUpperStructure() throws Exception public void testJsonUpperStructure() throws Exception
{ {
Response rsp = sendGetReq(referencingNodeUrl, 200); JSONObject jsonPostData = new JSONObject();
String jsonPostString = jsonPostData.toString();
Response rsp = sendRequest(new PostRequest(referencingNodeDefUrl,
jsonPostString, APPLICATION_JSON), 200);
String jsonResponseString = rsp.getContentAsString(); String jsonResponseString = rsp.getContentAsString();
JSONObject jsonParsedObject = new JSONObject(new JSONTokener(jsonResponseString)); JSONObject jsonParsedObject = new JSONObject(new JSONTokener(jsonResponseString));
@@ -87,7 +101,10 @@ public class FormRestApiGet_Test extends AbstractTestFormRestApi {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testJsonFormData() throws Exception public void testJsonFormData() throws Exception
{ {
Response rsp = sendGetReq(referencingNodeUrl, 200); JSONObject jsonPostData = new JSONObject();
String jsonPostString = jsonPostData.toString();
Response rsp = sendRequest(new PostRequest(referencingNodeDefUrl,
jsonPostString, APPLICATION_JSON), 200);
String jsonResponseString = rsp.getContentAsString(); String jsonResponseString = rsp.getContentAsString();
// At this point the formData names have underscores // At this point the formData names have underscores
@@ -118,7 +135,10 @@ public class FormRestApiGet_Test extends AbstractTestFormRestApi {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testJsonDefinitionFields() throws Exception public void testJsonDefinitionFields() throws Exception
{ {
Response rsp = sendGetReq(referencingNodeUrl, 200); JSONObject jsonPostData = new JSONObject();
String jsonPostString = jsonPostData.toString();
Response rsp = sendRequest(new PostRequest(referencingNodeDefUrl,
jsonPostString, APPLICATION_JSON), 200);
String jsonResponseString = rsp.getContentAsString(); String jsonResponseString = rsp.getContentAsString();
JSONObject jsonParsedObject = new JSONObject(new JSONTokener(jsonResponseString)); JSONObject jsonParsedObject = new JSONObject(new JSONTokener(jsonResponseString));
@@ -149,4 +169,71 @@ public class FormRestApiGet_Test extends AbstractTestFormRestApi {
} }
} }
} }
public void testJsonSelectedFields() throws Exception
{
JSONObject jsonPostData = new JSONObject();
JSONArray jsonFields = new JSONArray();
jsonFields.put("cm:name");
jsonFields.put("cm:title");
jsonFields.put("cm:publisher");
jsonPostData.put("fields", jsonFields);
// Submit the JSON request.
String jsonPostString = jsonPostData.toString();
Response rsp = sendRequest(new PostRequest(referencingNodeDefUrl, jsonPostString,
APPLICATION_JSON), 200);
String jsonResponseString = rsp.getContentAsString();
JSONObject jsonParsedObject = new JSONObject(new JSONTokener(jsonResponseString));
assertNotNull(jsonParsedObject);
JSONObject rootDataObject = (JSONObject)jsonParsedObject.get("data");
JSONObject definitionObject = (JSONObject)rootDataObject.get("definition");
JSONArray fieldsArray = (JSONArray)definitionObject.get("fields");
assertEquals("Expected 2 fields", 2, fieldsArray.length());
// get the data and check it
JSONObject formDataObject = (JSONObject)rootDataObject.get("formData");
assertNotNull("Expected to find cm:name data", formDataObject.get("prop_cm_name"));
assertNotNull("Expected to find cm:title data", formDataObject.get("prop_cm_title"));
assertEquals(TEST_FORM_TITLE, formDataObject.get("prop_cm_title"));
}
public void testJsonForcedFields() throws Exception
{
JSONObject jsonPostData = new JSONObject();
JSONArray jsonFields = new JSONArray();
jsonFields.put("cm:name");
jsonFields.put("cm:title");
jsonFields.put("cm:publisher");
jsonFields.put("cm:wrong");
jsonPostData.put("fields", jsonFields);
JSONArray jsonForcedFields = new JSONArray();
jsonForcedFields.put("cm:publisher");
jsonForcedFields.put("cm:wrong");
jsonPostData.put("force", jsonForcedFields);
// Submit the JSON request.
String jsonPostString = jsonPostData.toString();
Response rsp = sendRequest(new PostRequest(referencingNodeDefUrl, jsonPostString,
APPLICATION_JSON), 200);
String jsonResponseString = rsp.getContentAsString();
JSONObject jsonParsedObject = new JSONObject(new JSONTokener(jsonResponseString));
assertNotNull(jsonParsedObject);
JSONObject rootDataObject = (JSONObject)jsonParsedObject.get("data");
JSONObject definitionObject = (JSONObject)rootDataObject.get("definition");
JSONArray fieldsArray = (JSONArray)definitionObject.get("fields");
assertEquals("Expected 3 fields", 3, fieldsArray.length());
// get the data and check it
JSONObject formDataObject = (JSONObject)rootDataObject.get("formData");
assertNotNull("Expected to find cm:name data", formDataObject.get("prop_cm_name"));
assertNotNull("Expected to find cm:title data", formDataObject.get("prop_cm_title"));
assertEquals(TEST_FORM_TITLE, formDataObject.get("prop_cm_title"));
}
} }

View File

@@ -1,424 +1,423 @@
/* /*
* Copyright (C) 2005-2009 Alfresco Software Limited. * Copyright (C) 2005-2009 Alfresco Software Limited.
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2 * as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. * of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * 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 * 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 * the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's * and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have received a copy of the text describing * FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here: * the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing" * http://www.alfresco.com/legal/licensing"
*/ */
package org.alfresco.repo.web.scripts.forms; package org.alfresco.repo.web.scripts.forms;
import java.io.IOException; import java.io.IOException;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.alfresco.model.ContentModel; import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap; import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.repository.AssociationRef; import org.alfresco.service.cmr.repository.AssociationRef;
import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.ContentData; import org.alfresco.service.cmr.repository.ContentData;
import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.RegexQNamePattern; import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.web.scripts.TestWebScriptServer.GetRequest; import org.alfresco.web.scripts.TestWebScriptServer.PostRequest;
import org.alfresco.web.scripts.TestWebScriptServer.PostRequest; import org.alfresco.web.scripts.TestWebScriptServer.Response;
import org.alfresco.web.scripts.TestWebScriptServer.Response; import org.json.JSONException;
import org.json.JSONException; import org.json.JSONObject;
import org.json.JSONObject;
public class FormRestApiJsonPost_Test extends AbstractTestFormRestApi
public class FormRestApiJsonPost_Test extends AbstractTestFormRestApi {
{ private static final String PROP_CM_DESCRIPTION = "prop_cm_description";
private static final String PROP_CM_DESCRIPTION = "prop_cm_description"; private static final String PROP_MIMETYPE = "prop_mimetype";
private static final String PROP_MIMETYPE = "prop_mimetype"; private static final String ASSOC_CM_REFERENCES = "assoc_cm_references";
private static final String APPLICATION_JSON = "application/json"; private static final String ASSOC_CM_REFERENCES_ADDED = "assoc_cm_references_added";
private static final String ASSOC_CM_REFERENCES = "assoc_cm_references"; private static final String ASSOC_CM_REFERENCES_REMOVED = "assoc_cm_references_removed";
private static final String ASSOC_CM_REFERENCES_ADDED = "assoc_cm_references_added"; private static final String ASSOC_SYS_CHILDREN = "assoc_sys_children";
private static final String ASSOC_CM_REFERENCES_REMOVED = "assoc_cm_references_removed"; private static final String ASSOC_SYS_CHILDREN_ADDED = "assoc_sys_children_added";
private static final String ASSOC_SYS_CHILDREN = "assoc_sys_children"; private static final String ASSOC_SYS_CHILDREN_REMOVED = "assoc_sys_children_removed";
private static final String ASSOC_SYS_CHILDREN_ADDED = "assoc_sys_children_added";
private static final String ASSOC_SYS_CHILDREN_REMOVED = "assoc_sys_children_removed"; public void testSimpleJsonPostRequest() throws IOException, JSONException
{
public void testSimpleJsonPostRequest() throws IOException, JSONException // Retrieve and store the original property value.
{ Serializable originalDescription =
// Retrieve and store the original property value. nodeService.getProperty(referencingDocNodeRef, ContentModel.PROP_DESCRIPTION);
Serializable originalDescription = assertEquals(TEST_FORM_DESCRIPTION, originalDescription);
nodeService.getProperty(referencingDocNodeRef, ContentModel.PROP_DESCRIPTION);
assertEquals(TEST_FORM_DESCRIPTION, originalDescription); // get the original mimetype
String originalMimetype = null;
// get the original mimetype ContentData content = (ContentData)this.nodeService.getProperty(referencingDocNodeRef, ContentModel.PROP_CONTENT);
String originalMimetype = null; if (content != null)
ContentData content = (ContentData)this.nodeService.getProperty(referencingDocNodeRef, ContentModel.PROP_CONTENT); {
if (content != null) originalMimetype = content.getMimetype();
{ }
originalMimetype = content.getMimetype();
} // Construct some JSON to represent a new value.
JSONObject jsonPostData = new JSONObject();
// Construct some JSON to represent a new value. final String proposedNewDescription = "Modified Description";
JSONObject jsonPostData = new JSONObject(); jsonPostData.put(PROP_CM_DESCRIPTION, proposedNewDescription);
final String proposedNewDescription = "Modified Description"; jsonPostData.put(PROP_MIMETYPE, MimetypeMap.MIMETYPE_HTML);
jsonPostData.put(PROP_CM_DESCRIPTION, proposedNewDescription);
jsonPostData.put(PROP_MIMETYPE, MimetypeMap.MIMETYPE_HTML); // Submit the JSON request.
String jsonPostString = jsonPostData.toString();
// Submit the JSON request. Response ignoredRsp = sendRequest(new PostRequest(referencingNodeUpdateUrl, jsonPostString,
String jsonPostString = jsonPostData.toString(); APPLICATION_JSON), 200);
Response ignoredRsp = sendRequest(new PostRequest(referencingNodeUrl, jsonPostString,
APPLICATION_JSON), 200); // The nodeService should give us the modified property.
Serializable modifiedDescription =
// The nodeService should give us the modified property. nodeService.getProperty(referencingDocNodeRef, ContentModel.PROP_DESCRIPTION);
Serializable modifiedDescription = assertEquals(proposedNewDescription, modifiedDescription);
nodeService.getProperty(referencingDocNodeRef, ContentModel.PROP_DESCRIPTION);
assertEquals(proposedNewDescription, modifiedDescription); // get the modified mimetype
String modifiedMimetype = null;
// get the original mimetype content = (ContentData)this.nodeService.getProperty(referencingDocNodeRef, ContentModel.PROP_CONTENT);
String modifiedMimetype = null; if (content != null)
content = (ContentData)this.nodeService.getProperty(referencingDocNodeRef, ContentModel.PROP_CONTENT); {
if (content != null) modifiedMimetype = content.getMimetype();
{ }
modifiedMimetype = content.getMimetype(); assertEquals(MimetypeMap.MIMETYPE_HTML, modifiedMimetype);
}
assertEquals(MimetypeMap.MIMETYPE_HTML, modifiedMimetype); // The Rest API should also give us the modified property.
/*
// The Rest API should also give us the modified property. Response response = sendRequest(new GetRequest(referencingNodeUpdateUrl), 200);
Response response = sendRequest(new GetRequest(referencingNodeUrl), 200); JSONObject jsonGetResponse = new JSONObject(response.getContentAsString());
JSONObject jsonGetResponse = new JSONObject(response.getContentAsString()); JSONObject jsonDataObj = (JSONObject)jsonGetResponse.get("data");
JSONObject jsonDataObj = (JSONObject)jsonGetResponse.get("data"); assertNotNull(jsonDataObj);
assertNotNull(jsonDataObj);
JSONObject formData = (JSONObject)jsonDataObj.get("formData");
JSONObject formData = (JSONObject)jsonDataObj.get("formData"); assertNotNull(formData);
assertNotNull(formData); String retrievedValue = (String)formData.get(PROP_CM_DESCRIPTION);
String retrievedValue = (String)formData.get(PROP_CM_DESCRIPTION); assertEquals(modifiedDescription, retrievedValue);
assertEquals(modifiedDescription, retrievedValue); String retrievedMimetype = (String)formData.get(PROP_MIMETYPE);
String retrievedMimetype = (String)formData.get(PROP_MIMETYPE); assertEquals(MimetypeMap.MIMETYPE_HTML, modifiedMimetype);*/
assertEquals(MimetypeMap.MIMETYPE_HTML, modifiedMimetype); }
}
/**
/** * This test method attempts to add new associations between existing nodes.
* This test method attempts to add new associations between existing nodes. */
*/ public void testAddNewAssociationsToNode() throws Exception
public void testAddNewAssociationsToNode() throws Exception {
{ List<NodeRef> associatedNodes;
List<NodeRef> associatedNodes; checkOriginalAssocsBeforeChanges();
checkOriginalAssocsBeforeChanges();
// Add three additional associations
// Add three additional associations JSONObject jsonPostData = new JSONObject();
JSONObject jsonPostData = new JSONObject(); String assocsToAdd = associatedDoc_C + "," + associatedDoc_D + "," + associatedDoc_E;
String assocsToAdd = associatedDoc_C + "," + associatedDoc_D + "," + associatedDoc_E; jsonPostData.put(ASSOC_CM_REFERENCES_ADDED, assocsToAdd);
jsonPostData.put(ASSOC_CM_REFERENCES_ADDED, assocsToAdd); String jsonPostString = jsonPostData.toString();
String jsonPostString = jsonPostData.toString();
sendRequest(new PostRequest(referencingNodeUpdateUrl, jsonPostString, APPLICATION_JSON), 200);
sendRequest(new PostRequest(referencingNodeUrl, jsonPostString, APPLICATION_JSON), 200);
// Check the now updated associations via the node service
// Check the now updated associations via the node service List<AssociationRef> modifiedAssocs = nodeService.getTargetAssocs(referencingDocNodeRef, RegexQNamePattern.MATCH_ALL);
List<AssociationRef> modifiedAssocs = nodeService.getTargetAssocs(referencingDocNodeRef, RegexQNamePattern.MATCH_ALL); assertEquals(5, modifiedAssocs.size());
assertEquals(5, modifiedAssocs.size());
// Extract the target nodeRefs to make them easier to examine
// Extract the target nodeRefs to make them easier to examine associatedNodes = new ArrayList<NodeRef>(5);
associatedNodes = new ArrayList<NodeRef>(5); for (AssociationRef assocRef : modifiedAssocs)
for (AssociationRef assocRef : modifiedAssocs) {
{ associatedNodes.add(assocRef.getTargetRef());
associatedNodes.add(assocRef.getTargetRef()); }
}
assertTrue(associatedNodes.contains(associatedDoc_A));
assertTrue(associatedNodes.contains(associatedDoc_A)); assertTrue(associatedNodes.contains(associatedDoc_B));
assertTrue(associatedNodes.contains(associatedDoc_B)); assertTrue(associatedNodes.contains(associatedDoc_C));
assertTrue(associatedNodes.contains(associatedDoc_C)); assertTrue(associatedNodes.contains(associatedDoc_D));
assertTrue(associatedNodes.contains(associatedDoc_D)); assertTrue(associatedNodes.contains(associatedDoc_E));
assertTrue(associatedNodes.contains(associatedDoc_E));
// The Rest API should also give us the modified assocs.
// The Rest API should also give us the modified assocs. /*Response response = sendRequest(new GetRequest(referencingNodeUpdateUrl), 200);
Response response = sendRequest(new GetRequest(referencingNodeUrl), 200); String jsonRspString = response.getContentAsString();
String jsonRspString = response.getContentAsString(); JSONObject jsonGetResponse = new JSONObject(jsonRspString);
JSONObject jsonGetResponse = new JSONObject(jsonRspString); JSONObject jsonData = (JSONObject)jsonGetResponse.get("data");
JSONObject jsonData = (JSONObject)jsonGetResponse.get("data"); assertNotNull(jsonData);
assertNotNull(jsonData);
JSONObject jsonFormData = (JSONObject)jsonData.get("formData");
JSONObject jsonFormData = (JSONObject)jsonData.get("formData"); assertNotNull(jsonFormData);
assertNotNull(jsonFormData);
String jsonAssocs = (String)jsonFormData.get(ASSOC_CM_REFERENCES);
String jsonAssocs = (String)jsonFormData.get(ASSOC_CM_REFERENCES);
// We expect exactly 5 assocs on the test node
// We expect exactly 5 assocs on the test node assertEquals(5, jsonAssocs.split(",").length);
assertEquals(5, jsonAssocs.split(",").length); for (AssociationRef assocRef : modifiedAssocs)
for (AssociationRef assocRef : modifiedAssocs) {
{ assertTrue(jsonAssocs.contains(assocRef.getTargetRef().toString()));
assertTrue(jsonAssocs.contains(assocRef.getTargetRef().toString())); }*/
} }
}
/**
/** * This test method attempts to remove an existing association between two existing
* This test method attempts to remove an existing association between two existing * nodes.
* nodes. */
*/ public void testRemoveAssociationsFromNode() throws Exception
public void testRemoveAssociationsFromNode() throws Exception {
{ List<NodeRef> associatedNodes;
List<NodeRef> associatedNodes; checkOriginalAssocsBeforeChanges();
checkOriginalAssocsBeforeChanges();
// Remove an association
// Remove an association JSONObject jsonPostData = new JSONObject();
JSONObject jsonPostData = new JSONObject(); String assocsToRemove = associatedDoc_B.toString();
String assocsToRemove = associatedDoc_B.toString(); jsonPostData.put(ASSOC_CM_REFERENCES_REMOVED, assocsToRemove);
jsonPostData.put(ASSOC_CM_REFERENCES_REMOVED, assocsToRemove); String jsonPostString = jsonPostData.toString();
String jsonPostString = jsonPostData.toString();
sendRequest(new PostRequest(referencingNodeUpdateUrl, jsonPostString, APPLICATION_JSON), 200);
sendRequest(new PostRequest(referencingNodeUrl, jsonPostString, APPLICATION_JSON), 200);
// Check the now updated associations via the node service
// Check the now updated associations via the node service List<AssociationRef> modifiedAssocs = nodeService.getTargetAssocs(referencingDocNodeRef, RegexQNamePattern.MATCH_ALL);
List<AssociationRef> modifiedAssocs = nodeService.getTargetAssocs(referencingDocNodeRef, RegexQNamePattern.MATCH_ALL); assertEquals(1, modifiedAssocs.size());
assertEquals(1, modifiedAssocs.size());
// Extract the target nodeRefs to make them easier to examine
// Extract the target nodeRefs to make them easier to examine associatedNodes = new ArrayList<NodeRef>(5);
associatedNodes = new ArrayList<NodeRef>(5); for (AssociationRef assocRef : modifiedAssocs)
for (AssociationRef assocRef : modifiedAssocs) {
{ associatedNodes.add(assocRef.getTargetRef());
associatedNodes.add(assocRef.getTargetRef()); }
}
assertTrue(associatedNodes.contains(associatedDoc_A));
assertTrue(associatedNodes.contains(associatedDoc_A));
// The Rest API should also give us the modified assocs.
// The Rest API should also give us the modified assocs. /*Response response = sendRequest(new GetRequest(referencingNodeUpdateUrl), 200);
Response response = sendRequest(new GetRequest(referencingNodeUrl), 200); String jsonRspString = response.getContentAsString();
String jsonRspString = response.getContentAsString(); JSONObject jsonGetResponse = new JSONObject(jsonRspString);
JSONObject jsonGetResponse = new JSONObject(jsonRspString); JSONObject jsonData = (JSONObject)jsonGetResponse.get("data");
JSONObject jsonData = (JSONObject)jsonGetResponse.get("data"); assertNotNull(jsonData);
assertNotNull(jsonData);
JSONObject jsonFormData = (JSONObject)jsonData.get("formData");
JSONObject jsonFormData = (JSONObject)jsonData.get("formData"); assertNotNull(jsonFormData);
assertNotNull(jsonFormData);
String jsonAssocs = (String)jsonFormData.get(ASSOC_CM_REFERENCES);
String jsonAssocs = (String)jsonFormData.get(ASSOC_CM_REFERENCES);
// We expect exactly 1 assoc on the test node
// We expect exactly 1 assoc on the test node assertEquals(1, jsonAssocs.split(",").length);
assertEquals(1, jsonAssocs.split(",").length); for (AssociationRef assocRef : modifiedAssocs)
for (AssociationRef assocRef : modifiedAssocs) {
{ assertTrue(jsonAssocs.contains(assocRef.getTargetRef().toString()));
assertTrue(jsonAssocs.contains(assocRef.getTargetRef().toString())); }*/
} }
}
/**
/** * This test method attempts to add the same association twice. This attempt will
* This test method attempts to add the same association twice. This attempt will * not succeed, but the test case is to confirm that there is no exception thrown
* not succeed, but the test case is to confirm that there is no exception thrown * back across the REST API.
* back across the REST API. */
*/ public void testAddAssocThatAlreadyExists() throws Exception
public void testAddAssocThatAlreadyExists() throws Exception {
{ checkOriginalAssocsBeforeChanges();
checkOriginalAssocsBeforeChanges();
// Add an association
// Add an association JSONObject jsonPostData = new JSONObject();
JSONObject jsonPostData = new JSONObject(); String assocsToAdd = associatedDoc_C.toString();
String assocsToAdd = associatedDoc_C.toString(); jsonPostData.put(ASSOC_CM_REFERENCES_ADDED, assocsToAdd);
jsonPostData.put(ASSOC_CM_REFERENCES_ADDED, assocsToAdd); String jsonPostString = jsonPostData.toString();
String jsonPostString = jsonPostData.toString();
sendRequest(new PostRequest(referencingNodeUpdateUrl, jsonPostString, APPLICATION_JSON), 200);
sendRequest(new PostRequest(referencingNodeUrl, jsonPostString, APPLICATION_JSON), 200);
// Try to add the same association again
// Try to add the same association again sendRequest(new PostRequest(referencingNodeUpdateUrl, jsonPostString, APPLICATION_JSON), 200);
sendRequest(new PostRequest(referencingNodeUrl, jsonPostString, APPLICATION_JSON), 200); }
}
/**
/** * This test method attempts to remove an association that does not exist. This
* This test method attempts to remove an association that does not exist. This * attempt will not succeed, but the test case is to confirm that there is no
* attempt will not succeed, but the test case is to confirm that there is no * exception thrown back across the REST API.
* exception thrown back across the REST API. */
*/ public void testRemoveAssocThatDoesNotExist() throws Exception
public void testRemoveAssocThatDoesNotExist() throws Exception {
{ checkOriginalAssocsBeforeChanges();
checkOriginalAssocsBeforeChanges();
// Remove a non-existent association
// Remove a non-existent association JSONObject jsonPostData = new JSONObject();
JSONObject jsonPostData = new JSONObject(); String assocsToRemove = associatedDoc_E.toString();
String assocsToRemove = associatedDoc_E.toString(); jsonPostData.put(ASSOC_CM_REFERENCES_REMOVED, assocsToRemove);
jsonPostData.put(ASSOC_CM_REFERENCES_REMOVED, assocsToRemove); String jsonPostString = jsonPostData.toString();
String jsonPostString = jsonPostData.toString();
sendRequest(new PostRequest(referencingNodeUpdateUrl, jsonPostString, APPLICATION_JSON), 200);
sendRequest(new PostRequest(referencingNodeUrl, jsonPostString, APPLICATION_JSON), 200); }
}
/**
/** * This test method attempts to add new associations between existing nodes.
* This test method attempts to add new associations between existing nodes. */
*/ public void testAddNewChildAssociationsToNode() throws Exception
public void testAddNewChildAssociationsToNode() throws Exception {
{ List<NodeRef> associatedNodes;
List<NodeRef> associatedNodes; checkOriginalChildAssocsBeforeChanges();
checkOriginalChildAssocsBeforeChanges();
// Add three additional associations
// Add three additional associations JSONObject jsonPostData = new JSONObject();
JSONObject jsonPostData = new JSONObject(); String assocsToAdd = childDoc_C + "," + childDoc_D + "," + childDoc_E;
String assocsToAdd = childDoc_C + "," + childDoc_D + "," + childDoc_E; jsonPostData.put(ASSOC_SYS_CHILDREN_ADDED, assocsToAdd);
jsonPostData.put(ASSOC_SYS_CHILDREN_ADDED, assocsToAdd); String jsonPostString = jsonPostData.toString();
String jsonPostString = jsonPostData.toString();
sendRequest(new PostRequest(containingNodeUpdateUrl.toString(), jsonPostString, APPLICATION_JSON), 200);
sendRequest(new PostRequest(containingNodeUrl.toString(), jsonPostString, APPLICATION_JSON), 200);
// Check the now updated child associations via the node service
// Check the now updated child associations via the node service List<ChildAssociationRef> modifiedAssocs = nodeService.getChildAssocs(containerNodeRef);
List<ChildAssociationRef> modifiedAssocs = nodeService.getChildAssocs(containerNodeRef); assertEquals(5, modifiedAssocs.size());
assertEquals(5, modifiedAssocs.size());
// Extract the target nodeRefs to make them easier to examine
// Extract the target nodeRefs to make them easier to examine associatedNodes = new ArrayList<NodeRef>(5);
associatedNodes = new ArrayList<NodeRef>(5); for (ChildAssociationRef assocRef : modifiedAssocs)
for (ChildAssociationRef assocRef : modifiedAssocs) {
{ associatedNodes.add(assocRef.getChildRef());
associatedNodes.add(assocRef.getChildRef()); }
}
assertTrue(associatedNodes.contains(childDoc_A));
assertTrue(associatedNodes.contains(childDoc_A)); assertTrue(associatedNodes.contains(childDoc_B));
assertTrue(associatedNodes.contains(childDoc_B)); assertTrue(associatedNodes.contains(childDoc_C));
assertTrue(associatedNodes.contains(childDoc_C)); assertTrue(associatedNodes.contains(childDoc_D));
assertTrue(associatedNodes.contains(childDoc_D)); assertTrue(associatedNodes.contains(childDoc_E));
assertTrue(associatedNodes.contains(childDoc_E));
// The Rest API should also give us the modified assocs.
// The Rest API should also give us the modified assocs. /*Response response = sendRequest(new GetRequest(containingNodeUpdateUrl), 200);
Response response = sendRequest(new GetRequest(containingNodeUrl), 200); String jsonRspString = response.getContentAsString();
String jsonRspString = response.getContentAsString();
JSONObject jsonGetResponse = new JSONObject(jsonRspString);
JSONObject jsonGetResponse = new JSONObject(jsonRspString); JSONObject jsonData = (JSONObject)jsonGetResponse.get("data");
JSONObject jsonData = (JSONObject)jsonGetResponse.get("data"); assertNotNull(jsonData);
assertNotNull(jsonData);
JSONObject jsonFormData = (JSONObject)jsonData.get("formData");
JSONObject jsonFormData = (JSONObject)jsonData.get("formData"); assertNotNull(jsonFormData);
assertNotNull(jsonFormData);
String jsonAssocs = (String)jsonFormData.get(ASSOC_SYS_CHILDREN);
String jsonAssocs = (String)jsonFormData.get(ASSOC_SYS_CHILDREN);
// We expect exactly 5 assocs on the test node
// We expect exactly 5 assocs on the test node assertEquals(5, jsonAssocs.split(",").length);
assertEquals(5, jsonAssocs.split(",").length); for (ChildAssociationRef assocRef : modifiedAssocs)
for (ChildAssociationRef assocRef : modifiedAssocs) {
{ String childNodeRef = assocRef.getChildRef().toString();
String childNodeRef = assocRef.getChildRef().toString(); assertTrue(jsonAssocs.contains(childNodeRef));
assertTrue(jsonAssocs.contains(childNodeRef)); assertTrue(NodeRef.isNodeRef(childNodeRef));
assertTrue(NodeRef.isNodeRef(childNodeRef)); }*/
} }
}
/**
/** * This test method attempts to remove an existing child association between two
* This test method attempts to remove an existing child association between two * existing nodes.
* existing nodes. */
*/ public void testRemoveChildAssociationsFromNode() throws Exception
public void testRemoveChildAssociationsFromNode() throws Exception {
{ List<NodeRef> associatedNodes;
List<NodeRef> associatedNodes; checkOriginalChildAssocsBeforeChanges();
checkOriginalChildAssocsBeforeChanges();
// Remove an association
// Remove an association JSONObject jsonPostData = new JSONObject();
JSONObject jsonPostData = new JSONObject(); String assocsToRemove = childDoc_B.toString();
String assocsToRemove = childDoc_B.toString(); jsonPostData.put(ASSOC_SYS_CHILDREN_REMOVED, assocsToRemove);
jsonPostData.put(ASSOC_SYS_CHILDREN_REMOVED, assocsToRemove); String jsonPostString = jsonPostData.toString();
String jsonPostString = jsonPostData.toString();
sendRequest(new PostRequest(containingNodeUpdateUrl, jsonPostString, APPLICATION_JSON), 200);
sendRequest(new PostRequest(containingNodeUrl, jsonPostString, APPLICATION_JSON), 200);
// Check the now updated child associations via the node service
// Check the now updated child associations via the node service List<ChildAssociationRef> modifiedAssocs = nodeService.getChildAssocs(containerNodeRef);
List<ChildAssociationRef> modifiedAssocs = nodeService.getChildAssocs(containerNodeRef); assertEquals(1, modifiedAssocs.size());
assertEquals(1, modifiedAssocs.size());
// Extract the target nodeRefs to make them easier to examine
// Extract the target nodeRefs to make them easier to examine associatedNodes = new ArrayList<NodeRef>(5);
associatedNodes = new ArrayList<NodeRef>(5); for (ChildAssociationRef assocRef : modifiedAssocs)
for (ChildAssociationRef assocRef : modifiedAssocs) {
{ associatedNodes.add(assocRef.getChildRef());
associatedNodes.add(assocRef.getChildRef()); }
}
assertTrue(associatedNodes.contains(childDoc_A));
assertTrue(associatedNodes.contains(childDoc_A));
// The Rest API should also give us the modified assocs.
// The Rest API should also give us the modified assocs. /*Response response = sendRequest(new GetRequest(containingNodeUpdateUrl), 200);
Response response = sendRequest(new GetRequest(containingNodeUrl), 200); String jsonRspString = response.getContentAsString();
String jsonRspString = response.getContentAsString(); JSONObject jsonGetResponse = new JSONObject(jsonRspString);
JSONObject jsonGetResponse = new JSONObject(jsonRspString); JSONObject jsonData = (JSONObject)jsonGetResponse.get("data");
JSONObject jsonData = (JSONObject)jsonGetResponse.get("data"); assertNotNull(jsonData);
assertNotNull(jsonData);
JSONObject jsonFormData = (JSONObject)jsonData.get("formData");
JSONObject jsonFormData = (JSONObject)jsonData.get("formData"); assertNotNull(jsonFormData);
assertNotNull(jsonFormData);
String jsonAssocs = (String)jsonFormData.get(ASSOC_SYS_CHILDREN);
String jsonAssocs = (String)jsonFormData.get(ASSOC_SYS_CHILDREN);
// We expect exactly 1 assoc on the test node
// We expect exactly 1 assoc on the test node assertEquals(1, jsonAssocs.split(",").length);
assertEquals(1, jsonAssocs.split(",").length); for (ChildAssociationRef assocRef : modifiedAssocs)
for (ChildAssociationRef assocRef : modifiedAssocs) {
{ assertTrue(jsonAssocs.contains(assocRef.getChildRef().toString()));
assertTrue(jsonAssocs.contains(assocRef.getChildRef().toString())); }*/
} }
}
/**
/** * This test method attempts to add the same child association twice. This attempt
* This test method attempts to add the same child association twice. This attempt * will not succeed, but the test case is to confirm that there is no exception thrown
* will not succeed, but the test case is to confirm that there is no exception thrown * back across the REST API.
* back across the REST API. */
*/ public void testAddChildAssocThatAlreadyExists() throws Exception
public void testAddChildAssocThatAlreadyExists() throws Exception {
{ checkOriginalChildAssocsBeforeChanges();
checkOriginalChildAssocsBeforeChanges();
// Add an association
// Add an association JSONObject jsonPostData = new JSONObject();
JSONObject jsonPostData = new JSONObject(); String assocsToAdd = this.childDoc_C.toString();
String assocsToAdd = this.childDoc_C.toString(); jsonPostData.put(ASSOC_SYS_CHILDREN_ADDED, assocsToAdd);
jsonPostData.put(ASSOC_SYS_CHILDREN_ADDED, assocsToAdd); String jsonPostString = jsonPostData.toString();
String jsonPostString = jsonPostData.toString();
sendRequest(new PostRequest(referencingNodeUpdateUrl, jsonPostString, APPLICATION_JSON), 200);
sendRequest(new PostRequest(referencingNodeUrl, jsonPostString, APPLICATION_JSON), 200);
// Try to add the same child association again
// Try to add the same child association again sendRequest(new PostRequest(referencingNodeUpdateUrl, jsonPostString, APPLICATION_JSON), 200);
sendRequest(new PostRequest(referencingNodeUrl, jsonPostString, APPLICATION_JSON), 200); }
}
/**
/** * This test method attempts to remove a child association that does not exist. This
* This test method attempts to remove a child association that does not exist. This * attempt will not succeed, but the test case is to confirm that there is no
* attempt will not succeed, but the test case is to confirm that there is no * exception thrown back across the REST API.
* exception thrown back across the REST API. */
*/ public void testRemoveChildAssocThatDoesNotExist() throws Exception
public void testRemoveChildAssocThatDoesNotExist() throws Exception {
{ checkOriginalChildAssocsBeforeChanges();
checkOriginalChildAssocsBeforeChanges();
// Remove a non-existent child association
// Remove a non-existent child association JSONObject jsonPostData = new JSONObject();
JSONObject jsonPostData = new JSONObject(); String assocsToRemove = childDoc_E.toString();
String assocsToRemove = childDoc_E.toString(); jsonPostData.put(ASSOC_SYS_CHILDREN_REMOVED, assocsToRemove);
jsonPostData.put(ASSOC_SYS_CHILDREN_REMOVED, assocsToRemove); String jsonPostString = jsonPostData.toString();
String jsonPostString = jsonPostData.toString();
sendRequest(new PostRequest(referencingNodeUpdateUrl, jsonPostString, APPLICATION_JSON), 200);
sendRequest(new PostRequest(referencingNodeUrl, jsonPostString, APPLICATION_JSON), 200); }
}
private void checkOriginalAssocsBeforeChanges()
private void checkOriginalAssocsBeforeChanges() {
{ List<AssociationRef> originalAssocs = nodeService.getTargetAssocs(referencingDocNodeRef, RegexQNamePattern.MATCH_ALL);
List<AssociationRef> originalAssocs = nodeService.getTargetAssocs(referencingDocNodeRef, RegexQNamePattern.MATCH_ALL); assertEquals(2, originalAssocs.size());
assertEquals(2, originalAssocs.size());
List<NodeRef> associatedNodes = new ArrayList<NodeRef>(2);
List<NodeRef> associatedNodes = new ArrayList<NodeRef>(2); associatedNodes.add(originalAssocs.get(0).getTargetRef());
associatedNodes.add(originalAssocs.get(0).getTargetRef()); associatedNodes.add(originalAssocs.get(1).getTargetRef());
associatedNodes.add(originalAssocs.get(1).getTargetRef());
assertTrue(associatedNodes.contains(associatedDoc_A));
assertTrue(associatedNodes.contains(associatedDoc_A)); assertTrue(associatedNodes.contains(associatedDoc_B));
assertTrue(associatedNodes.contains(associatedDoc_B)); }
}
private void checkOriginalChildAssocsBeforeChanges()
private void checkOriginalChildAssocsBeforeChanges() {
{ List<ChildAssociationRef> originalChildAssocs = nodeService.getChildAssocs(containerNodeRef);
List<ChildAssociationRef> originalChildAssocs = nodeService.getChildAssocs(containerNodeRef); assertEquals(2, originalChildAssocs.size());
assertEquals(2, originalChildAssocs.size());
List<NodeRef> associatedNodes = new ArrayList<NodeRef>(2);
List<NodeRef> associatedNodes = new ArrayList<NodeRef>(2); associatedNodes.add(originalChildAssocs.get(0).getChildRef());
associatedNodes.add(originalChildAssocs.get(0).getChildRef()); associatedNodes.add(originalChildAssocs.get(1).getChildRef());
associatedNodes.add(originalChildAssocs.get(1).getChildRef());
assertTrue(associatedNodes.contains(childDoc_A));
assertTrue(associatedNodes.contains(childDoc_A)); assertTrue(associatedNodes.contains(childDoc_B));
assertTrue(associatedNodes.contains(childDoc_B)); }
} }
}