First check-in of JSON POST

git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@13311 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Neil McErlean
2009-02-20 20:19:07 +00:00
parent a41b3bda05
commit 3762bb104b
6 changed files with 401 additions and 207 deletions

View File

@@ -31,6 +31,7 @@ function main()
// Note: This formdata is org/alfresco/web/scripts/servlet/FormData.java
logger.log("Saving form with formdata, " + formdata.fields.length + " fields.");
//TODO At this point, for multipart, the field names are e.g. prop_cm_name
// N.B. This repoFormData is a different FormData class to that used above.
var repoFormData = new Packages.org.alfresco.repo.forms.FormData();
@@ -42,11 +43,6 @@ function main()
//TODO How to handle false booleans? They are omitted from POST
formService.saveForm(nodeRef, repoFormData);
}
else if (typeof json !== "undefined")
{
logger.log("Saving form with json = " + json);
formService.saveForm(nodeRef, json);
}
else
{
logger.log("Saving form with args = " + args);

View File

@@ -0,0 +1,50 @@
function main()
{
var ta_storeType = url.templateArgs['store_type'];
var ta_storeId = url.templateArgs['store_id'];
var ta_id = url.templateArgs['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;
}
logger.log("POST request received for nodeRef: " + nodeRef);
if (typeof json !== "undefined")
{
logger.log("Saving form with json = " + json);
// 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"
//TODO Need to remove the extra fields.
}
else
{
logger.log("json object was undefined.");
return;
}
var repoFormData = new Packages.org.alfresco.repo.forms.FormData();
var jsonKeys = json.keys();
for ( ; jsonKeys.hasNext(); )
{
var nextKey = jsonKeys.next();
repoFormData.addData(nextKey, json.get(nextKey));
}
formService.saveForm(nodeRef, repoFormData);
model.message = "Successfully updated node " + nodeRef;
}
main();

View File

@@ -0,0 +1,124 @@
/*
* Copyright (C) 2005-2009 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.forms;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.model.Repository;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.GUID;
import org.alfresco.web.scripts.TestWebScriptServer.GetRequest;
import org.alfresco.web.scripts.TestWebScriptServer.Response;
public abstract class AbstractTestFormRestApi extends BaseWebScriptTest
{
protected static final String TEST_FORM_DESCRIPTION = "Test form description";
protected static final String TEST_FORM_TITLE = "Test form title";
protected String testNodeUrl;
protected NodeRef testNodeRef;
protected Map<QName, Serializable> testNodePropertiesAfterCreation;
protected NodeService nodeService;
private FileFolderService fileFolderService;
private ContentService contentService;
private Repository repositoryHelper;
public AbstractTestFormRestApi()
{
super();
}
@Override
protected void setUp() throws Exception
{
super.setUp();
this.fileFolderService = (FileFolderService) getServer().getApplicationContext().getBean(
"FileFolderService");
this.contentService = (ContentService) getServer().getApplicationContext().getBean(
"ContentService");
this.repositoryHelper = (Repository) getServer().getApplicationContext().getBean(
"repositoryHelper");
this.nodeService = (NodeService) getServer().getApplicationContext().getBean("NodeService");
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
NodeRef companyHomeNodeRef = this.repositoryHelper.getCompanyHome();
String guid = GUID.generate();
FileInfo fileInfoTestNode = this.fileFolderService.create(companyHomeNodeRef,
"test_forms_doc" + guid + ".txt", ContentModel.TYPE_CONTENT);
testNodeRef = fileInfoTestNode.getNodeRef();
// Add an aspect.
Map<QName, Serializable> aspectProps = new HashMap<QName, Serializable>(2);
aspectProps.put(ContentModel.PROP_TITLE, TEST_FORM_TITLE);
aspectProps.put(ContentModel.PROP_DESCRIPTION, TEST_FORM_DESCRIPTION);
nodeService.addAspect(testNodeRef, ContentModel.ASPECT_TITLED, aspectProps);
// Write some content into the node.
ContentWriter contentWriter = this.contentService.getWriter(fileInfoTestNode.getNodeRef(),
ContentModel.PROP_CONTENT, true);
contentWriter.setEncoding("UTF-8");
contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
contentWriter.putContent("The quick brown fox jumped over the lazy dog.");
// Create and store the path
StringBuilder builder = new StringBuilder();
builder.append("/api/forms/node/workspace/").append(testNodeRef.getStoreRef().getIdentifier())
.append("/").append(testNodeRef.getId());
this.testNodeUrl = builder.toString();
// Store the original properties of this node
this.testNodePropertiesAfterCreation = nodeService.getProperties(testNodeRef);
}
@Override
public void tearDown()
{
nodeService.deleteNode(testNodeRef);
}
protected Response sendGetReq(String url, int expectedStatusCode)
throws IOException, UnsupportedEncodingException
{
Response result = sendRequest(new GetRequest(url), expectedStatusCode);
return result;
}
}

View File

@@ -1,202 +0,0 @@
package org.alfresco.repo.web.scripts.forms;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.model.Repository;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.repo.web.scripts.thumbnail.ThumbnailServiceTest;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.GUID;
import org.alfresco.web.scripts.TestWebScriptServer.GetRequest;
import org.alfresco.web.scripts.TestWebScriptServer.Response;
import org.alfresco.web.scripts.json.JSONUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
public class TestFormRestAPI extends BaseWebScriptTest {
private FileFolderService fileFolderService;
private ContentService contentService;
private NodeService nodeService;
private Repository repositoryHelper;
private Response response;
private String jsonResponseString;
private NodeRef testRoot;
private NodeRef testPdfNode;
private String pathToTestPdfNode;
@Override
protected void setUp() throws Exception
{
super.setUp();
this.fileFolderService = (FileFolderService)getServer().getApplicationContext().getBean("FileFolderService");
this.contentService = (ContentService)getServer().getApplicationContext().getBean("ContentService");
this.repositoryHelper = (Repository)getServer().getApplicationContext().getBean("repositoryHelper");
this.nodeService = (NodeService)getServer().getApplicationContext().getBean("NodeService");
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
this.testRoot = this.repositoryHelper.getCompanyHome();
// Create a dummy node purely for test purposes.
InputStream pdfStream = ThumbnailServiceTest.class.getClassLoader().getResourceAsStream("org/alfresco/repo/web/scripts/forms/test_doc.pdf");
assertNotNull(pdfStream);
String guid = GUID.generate();
FileInfo fileInfoPdf = this.fileFolderService.create(this.testRoot, "test_forms_doc" + guid + ".pdf", ContentModel.TYPE_CONTENT);
this.testPdfNode = fileInfoPdf.getNodeRef();
// Add an aspect.
Map<QName, Serializable> aspectProps = new HashMap<QName, Serializable>(2);
aspectProps.put(ContentModel.PROP_TITLE, "Test form title");
aspectProps.put(ContentModel.PROP_DESCRIPTION, "Test form description");
nodeService.addAspect(testPdfNode, ContentModel.ASPECT_TITLED, aspectProps);
ContentWriter contentWriter = this.contentService.getWriter(fileInfoPdf.getNodeRef(), ContentModel.PROP_CONTENT, true);
contentWriter.setEncoding("UTF-8");
contentWriter.setMimetype(MimetypeMap.MIMETYPE_PDF);
contentWriter.putContent(pdfStream);
StringBuilder builder = new StringBuilder();
builder.append("/api/forms/node/workspace/")
.append(testPdfNode.getStoreRef().getIdentifier())
.append("/")
.append(testPdfNode.getId());
this.pathToTestPdfNode = builder.toString();
}
//TODO Add a tearDown which deletes the temporary pdf file above.
public void testResponseContentType() throws Exception
{
sendGetReqAndInitRspData(pathToTestPdfNode, 200);
assertEquals("application/json;charset=UTF-8", response.getContentType());
//TODO Remove this.
System.out.println(jsonResponseString);
}
//TODO Perhaps separate positive and negative test cases into two JUnit classes.
public void testGetFormForNonExistentNode() throws Exception
{
sendGetReqAndInitRspData(pathToTestPdfNode.replaceAll("\\d", "x"), 404);
assertEquals("application/json;charset=UTF-8", response.getContentType());
}
public void testJsonContentParsesCorrectly() throws Exception
{
sendGetReqAndInitRspData(pathToTestPdfNode, 200);
Object jsonObject = new JSONUtils().toObject(jsonResponseString);
assertNotNull("JSON object was null.", jsonObject);
}
public void testJsonUpperStructure() throws Exception
{
sendGetReqAndInitRspData(pathToTestPdfNode, 200);
JSONObject jsonParsedObject = new JSONObject(new JSONTokener(jsonResponseString));
assertNotNull(jsonParsedObject);
Object dataObj = jsonParsedObject.get("data");
assertEquals(JSONObject.class, dataObj.getClass());
JSONObject rootDataObject = (JSONObject)dataObj;
assertEquals(5, rootDataObject.length());
String item = (String)rootDataObject.get("item");
String submissionUrl = (String)rootDataObject.get("submissionUrl");
String type = (String)rootDataObject.get("type");
JSONObject definitionObject = (JSONObject)rootDataObject.get("definition");
JSONObject formDataObject = (JSONObject)rootDataObject.get("formData");
assertNotNull(item);
assertNotNull(submissionUrl);
assertNotNull(type);
assertNotNull(definitionObject);
assertNotNull(formDataObject);
}
@SuppressWarnings("unchecked")
public void testJsonFormData() throws Exception
{
sendGetReqAndInitRspData(pathToTestPdfNode, 200);
JSONObject jsonParsedObject = new JSONObject(new JSONTokener(jsonResponseString));
assertNotNull(jsonParsedObject);
JSONObject rootDataObject = (JSONObject)jsonParsedObject.get("data");
JSONObject formDataObject = (JSONObject)rootDataObject.get("formData");
List<String> keys = new ArrayList<String>();
for (Iterator iter = formDataObject.keys(); iter.hasNext(); )
{
keys.add((String)iter.next());
}
// Threshold is a rather arbitrary number. I simply want to ensure that there
// are *some* entries in the formData hash.
final int threshold = 5;
int actualKeyCount = keys.size();
assertTrue("Expected more than " + threshold +
" entries in formData. Actual: " + actualKeyCount, actualKeyCount > threshold);
}
public void testJsonDefinitionFields() throws Exception
{
sendGetReqAndInitRspData(pathToTestPdfNode, 200);
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");
//TODO This will all be revamped when I introduce test code based on a known
// node. But in the meantime, I'll keep it general.
for (int i = 0; i < fieldsArray.length(); i++)
{
Object nextObj = fieldsArray.get(i);
JSONObject nextJsonObject = (JSONObject)nextObj;
List<String> fieldKeys = new ArrayList<String>();
for (Iterator iter2 = nextJsonObject.keys(); iter2.hasNext(); )
{
fieldKeys.add((String)iter2.next());
}
for (String s : fieldKeys)
{
if (s.equals("mandatory") || s.equals("protectedField"))
{
assertEquals("JSON booleans should be actual booleans.", java.lang.Boolean.class, nextJsonObject.get(s).getClass());
}
}
}
}
private void sendGetReqAndInitRspData(String url, int expectedStatusCode) throws IOException,
UnsupportedEncodingException
{
response = sendRequest(new GetRequest(url), expectedStatusCode);
jsonResponseString = response.getContentAsString();
}
}

View File

@@ -0,0 +1,152 @@
/*
* Copyright (C) 2005-2009 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 recieved 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.forms;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.alfresco.web.scripts.TestWebScriptServer.Response;
import org.alfresco.web.scripts.json.JSONUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
public class TestFormRestAPI_Get extends AbstractTestFormRestApi {
public void testResponseContentType() throws Exception
{
Response rsp = sendGetReq(testNodeUrl, 200);
assertEquals("application/json;charset=UTF-8", rsp.getContentType());
}
public void testGetFormForNonExistentNode() throws Exception
{
// Replace all digits with an 'x' char - this should make for a non-existent node.
Response rsp = sendGetReq(testNodeUrl.replaceAll("\\d", "x"), 404);
assertEquals("application/json;charset=UTF-8", rsp.getContentType());
}
public void testJsonContentParsesCorrectly() throws Exception
{
Response rsp = sendGetReq(testNodeUrl, 200);
String jsonResponseString = rsp.getContentAsString();
Object jsonObject = new JSONUtils().toObject(jsonResponseString);
assertNotNull("JSON object was null.", jsonObject);
}
public void testJsonUpperStructure() throws Exception
{
Response rsp = sendGetReq(testNodeUrl, 200);
String jsonResponseString = rsp.getContentAsString();
JSONObject jsonParsedObject = new JSONObject(new JSONTokener(jsonResponseString));
assertNotNull(jsonParsedObject);
Object dataObj = jsonParsedObject.get("data");
assertEquals(JSONObject.class, dataObj.getClass());
JSONObject rootDataObject = (JSONObject)dataObj;
assertEquals(5, rootDataObject.length());
String item = (String)rootDataObject.get("item");
String submissionUrl = (String)rootDataObject.get("submissionUrl");
String type = (String)rootDataObject.get("type");
JSONObject definitionObject = (JSONObject)rootDataObject.get("definition");
JSONObject formDataObject = (JSONObject)rootDataObject.get("formData");
assertNotNull(item);
assertNotNull(submissionUrl);
assertNotNull(type);
assertNotNull(definitionObject);
assertNotNull(formDataObject);
}
@SuppressWarnings("unchecked")
public void testJsonFormData() throws Exception
{
Response rsp = sendGetReq(testNodeUrl, 200);
String jsonResponseString = rsp.getContentAsString();
// At this point the formData names have underscores
JSONObject jsonParsedObject = new JSONObject(new JSONTokener(jsonResponseString));
assertNotNull(jsonParsedObject);
JSONObject rootDataObject = (JSONObject)jsonParsedObject.get("data");
JSONObject formDataObject = (JSONObject)rootDataObject.get("formData");
List<String> keys = new ArrayList<String>();
for (Iterator iter = formDataObject.keys(); iter.hasNext(); )
{
// None of the formData keys should have a colon in them. We are
// replacing colons in field names with underscores.
String nextFieldName = (String)iter.next();
assertEquals("Did not expect to find a colon char in " + nextFieldName,
-1, nextFieldName.indexOf(':'));
keys.add(nextFieldName);
}
// Threshold is a rather arbitrary number. I simply want to ensure that there
// are *some* entries in the formData hash.
final int threshold = 5;
int actualKeyCount = keys.size();
assertTrue("Expected more than " + threshold +
" entries in formData. Actual: " + actualKeyCount, actualKeyCount > threshold);
}
@SuppressWarnings("unchecked")
public void testJsonDefinitionFields() throws Exception
{
Response rsp = sendGetReq(testNodeUrl, 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");
for (int i = 0; i < fieldsArray.length(); i++)
{
Object nextObj = fieldsArray.get(i);
JSONObject nextJsonObject = (JSONObject)nextObj;
List<String> fieldKeys = new ArrayList<String>();
for (Iterator iter2 = nextJsonObject.keys(); iter2.hasNext(); )
{
fieldKeys.add((String)iter2.next());
}
for (String s : fieldKeys)
{
if (s.equals("mandatory") || s.equals("protectedField"))
{
assertEquals("JSON booleans should be actual booleans.", java.lang.Boolean.class, nextJsonObject.get(s).getClass());
}
}
}
}
}

View File

@@ -0,0 +1,74 @@
/*
* Copyright (C) 2005-2009 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.forms;
import java.io.IOException;
import java.io.Serializable;
import org.alfresco.model.ContentModel;
import org.alfresco.web.scripts.TestWebScriptServer.GetRequest;
import org.alfresco.web.scripts.TestWebScriptServer.PostRequest;
import org.alfresco.web.scripts.TestWebScriptServer.Response;
import org.json.JSONException;
import org.json.JSONObject;
public class TestFormRestAPI_JsonPost extends AbstractTestFormRestApi
{
private static final String PROP_CM_DESCRIPTION = "prop_cm_description";
private static final String APPLICATION_JSON = "application/json";
public void testSubmitJsonPostRequest() throws IOException, JSONException
{
// Retrieve and store the original property value.
Serializable originalDescription =
nodeService.getProperty(testNodeRef, ContentModel.PROP_DESCRIPTION);
assertEquals(TEST_FORM_DESCRIPTION, originalDescription);
// Construct some JSON to represent a new value.
JSONObject jsonPostData = new JSONObject();
final String proposedNewDescription = "Modified Description";
jsonPostData.put(PROP_CM_DESCRIPTION, proposedNewDescription);
// Submit the JSON request.
Response ignoredRsp = sendRequest(new PostRequest(testNodeUrl, jsonPostData.toString(),
APPLICATION_JSON), 200);
// The nodeService should give us the modified property.
Serializable modifiedDescription =
nodeService.getProperty(testNodeRef, ContentModel.PROP_DESCRIPTION);
assertEquals(proposedNewDescription, modifiedDescription);
// The Rest API should also give us the modified property.
Response response = sendRequest(new GetRequest(testNodeUrl), 200);
JSONObject jsonGetResponse = new JSONObject(response.getContentAsString());
JSONObject jsonDataObj = (JSONObject)jsonGetResponse.get("data");
assertNotNull(jsonDataObj);
JSONObject formData = (JSONObject)jsonDataObj.get("formData");
assertNotNull(formData);
String retrievedValue = (String)formData.get(PROP_CM_DESCRIPTION);
assertEquals(modifiedDescription, retrievedValue);
}
}