use of org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument in project application by collectionspace.
the class TestService method testPersonContact.
// @Test
public void testPersonContact() throws Exception {
String serviceurl = "personauthorities/urn:cspace:name(person)/items";
String filename = "personItem.xml";
String partname = "persons_common";
ReturnedURL url;
log.info("Testing " + serviceurl + " with " + filename + " and partname=" + partname);
// POST (Create)
if (partname != null) {
Map<String, Document> parts = new HashMap<String, Document>();
parts.put(partname, getDocument(filename));
url = conn.getMultipartURL(RequestMethod.POST, serviceurl, parts, creds, cache);
} else {
url = conn.getURL(RequestMethod.POST, serviceurl, getDocument(filename), creds, cache);
}
assertEquals(201, url.getStatus());
// log.info("CREATE PERSON" + url.getURL());
// assertTrue(url.getURL().startsWith("/"+serviceurl)); // ensures e.g.
// CSPACE-305 hasn't regressed
log.info("CREATE PERSON" + url.getURL());
// create contact person
String serviceurlContact = "personauthorities/urn:cspace:name(person)/items/" + url.getURLTail() + "/contacts";
String filenameContact = "personItemContact.xml";
String partnameContact = "contacts_common";
log.info("ADD CONTACT USING THIS URL " + serviceurlContact);
testPostGetDelete(serviceurlContact, partnameContact, filenameContact, "contacts_common/email", "email@example.com");
// DELETE (Delete)
int status = conn.getNone(RequestMethod.DELETE, url.getURL(), null, creds, cache);
assertEquals(200, status);
// Now try to delete non-existent (make sure CSPACE-73 hasn't regressed)
status = conn.getNone(RequestMethod.DELETE, url.getURL(), null, creds, cache);
assertEquals(404, status);
log.info("DELETE PERSON");
// GET once more to make sure it isn't there
int getStatus;
Document doc;
if (partname != null) {
ReturnedMultipartDocument rdocs = conn.getMultipartXMLDocument(RequestMethod.GET, url.getURL(), null, creds, cache);
getStatus = rdocs.getStatus();
doc = rdocs.getDocument(partname);
} else {
ReturnedDocument rdoc = conn.getXMLDocument(RequestMethod.GET, url.getURL(), null, creds, cache);
getStatus = rdoc.getStatus();
doc = rdoc.getDocument();
}
// ensures CSPACE-209 hasn't regressed
assertEquals(404, getStatus);
assertNull(doc);
}
use of org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument in project application by collectionspace.
the class AuthorizationStorage method updateJSON.
@Override
public void updateJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String filePath, JSONObject jsonObject, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
Map<String, Document> parts = new HashMap<String, Document>();
Document doc = null;
for (String section : r.getServicesRecordPathKeys()) {
String path = r.getServicesRecordPath(section);
String[] record_path = path.split(":", 2);
doc = XmlJsonConversion.convertToXml(r, jsonObject, section, "PUT");
parts.put(record_path[0], doc);
}
int status = 0;
if (r.isMultipart()) {
ReturnedMultipartDocument docm = conn.getMultipartXMLDocument(RequestMethod.PUT, r.getServicesURL() + "/" + filePath, parts, creds, cache);
status = docm.getStatus();
} else {
ReturnedDocument docm = conn.getXMLDocument(RequestMethod.PUT, r.getServicesURL() + "/" + filePath, doc, creds, cache);
status = docm.getStatus();
}
if (status == 404)
throw new ExistException("Not found: " + r.getServicesURL() + "/" + filePath);
if (status > 299 || status < 200)
throw new UnderlyingStorageException("Bad response " + status, status, r.getServicesURL() + "/" + filePath);
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Service layer exception", e);
} catch (JSONException e) {
throw new UnimplementedException("JSONException", e);
}
}
use of org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument in project application by collectionspace.
the class ServicesRelationStorage method retrieveJSON.
@Override
public JSONObject retrieveJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String filePath, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
Boolean isHierarchical = false;
String[] parts = null;
if (isPathType(filePath, new String[] { "main" }, 1)) {
parts = extractPaths(filePath, new String[] { "main" }, 1);
} else if (isPathType(filePath, new String[] { "hierarchical" }, 1)) {
parts = extractPaths(filePath, new String[] { "hierarchical" }, 1);
isHierarchical = true;
}
ReturnedMultipartDocument out = conn.getMultipartXMLDocument(RequestMethod.GET, "/relations/" + parts[0], null, creds, cache);
if (out.getStatus() == 404)
throw new UnderlyingStorageException("Could not retrieve relation", out.getStatus(), "/relations/" + parts[0]);
Document doc = out.getDocument("relations_common");
if (doc == null)
throw new UnderlyingStorageException("Could not retrieve relation, missing relations_common", out.getStatus(), "/relations/" + parts[0]);
return relationToData(cache, factory.load(parts[0], doc));
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Could not retrieve relation" + e.getLocalizedMessage(), e.getStatus(), e.getUrl(), e);
} catch (JaxenException e) {
throw new UnderlyingStorageException("Could not retrieve relation" + e.getLocalizedMessage(), e);
} catch (JSONException e) {
throw new UnderlyingStorageException("Could not retrieve relation" + e.getLocalizedMessage(), e);
}
}
use of org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument in project application by collectionspace.
the class GenericStorage method handleHierarchyPayloadRetrieve.
public void handleHierarchyPayloadRetrieve(Record r, ReturnedMultipartDocument doc, JSONObject out, String thiscsid) throws JSONException {
if (r.hasHierarchyUsed("screen")) {
// lets do relationship stuff...
Document list = doc.getDocument("relations-common-list");
if (list == null)
return;
List<Node> nodes = list.selectNodes("/relations-common-list/*");
for (Node node : nodes) {
if ("relation-list-item".equals(node.getName())) {
// String test = node.asXML();
String relationshipType = node.selectSingleNode("relationshipType").getText();
// Be forgiving while waiting for services to complete code.
Node relationshipMetaTypeNode = node.selectSingleNode("relationshipMetaType");
String relationshipMetaType = (relationshipMetaTypeNode != null) ? relationshipMetaTypeNode.getText() : "";
// String subjCSID = node.selectSingleNode("subjectCsid").getText();
// String objCSID = node.selectSingleNode("objectCsid").getText();
String subjURI = "";
String subjCSID = "";
String subjDocType = "";
if (node.selectSingleNode("subject/uri") != null) {
subjCSID = node.selectSingleNode("subject/csid").getText();
subjDocType = node.selectSingleNode("subject/documentType").getText();
subjURI = node.selectSingleNode("subject/refName").getText();
}
String objRefName = "";
String objDocType = "";
String objCSID = "";
if (node.selectSingleNode("object/uri") != null) {
objCSID = node.selectSingleNode("object/csid").getText();
objDocType = node.selectSingleNode("object/documentType").getText();
objRefName = node.selectSingleNode("object/refName").getText();
}
String relateduri = objRefName;
String relatedcsid = objCSID;
String relatedser = objDocType;
if (r.getSpec().hasRelationshipByPredicate(relationshipType)) {
Relationship rel = r.getSpec().getRelationshipByPredicate(relationshipType);
Relationship newrel = rel;
// is this subject or object
if (thiscsid.equals(objCSID)) {
// should we invert
if (r.getSpec().hasRelationshipInverse(rel.getID())) {
newrel = r.getSpec().getInverseRelationship(rel.getID());
relateduri = subjURI;
relatedcsid = subjCSID;
relatedser = subjDocType;
}
}
String metaTypeField = newrel.getMetaTypeField();
if (newrel.getObject().equals("n")) {
// array
JSONObject subdata = new JSONObject();
subdata.put(newrel.getChildName(), relateduri);
if (!StringUtils.isEmpty(metaTypeField)) {
subdata.put(metaTypeField, relationshipMetaType);
}
if (out.has(newrel.getID())) {
out.getJSONArray(newrel.getID()).put(subdata);
} else {
JSONArray relList = new JSONArray();
relList.put(subdata);
out.put(newrel.getID(), relList);
}
} else {
// string
out.put(newrel.getID(), relateduri);
if (!StringUtils.isEmpty(metaTypeField)) {
out.put(metaTypeField, relationshipMetaType);
}
if (newrel.showSiblings()) {
out.put(newrel.getSiblingChild(), relatedser + "/" + relatedcsid);
// out.put(newrel.getSiblingChild(), relateduri);
}
}
}
}
}
}
}
use of org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument in project application by collectionspace.
the class GenericStorage method updateJSON.
/**
* update the item
* @param root
* @param creds
* @param cache
* @param filePath
* @param jsonObject
* @param thisr
* @param serviceurl
* @throws ExistException
* @throws UnimplementedException
* @throws UnderlyingStorageException
*/
public void updateJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String filePath, JSONObject jsonObject, JSONObject restrictions, Record thisr, String serviceurl) throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
Map<String, Document> parts = new HashMap<String, Document>();
Document doc = null;
for (String section : thisr.getServicesRecordPathKeys()) {
String path = thisr.getServicesRecordPath(section);
String[] record_path = path.split(":", 2);
doc = XmlJsonConversion.convertToXml(thisr, jsonObject, section, "PUT");
if (doc != null) {
parts.put(record_path[0], doc);
// log.info(doc.asXML());
}
}
// This checks for hierarchy support, and does nothing if not appropriate.
handleHierarchyPayloadSend(thisr, parts, jsonObject, filePath);
int status = 0;
if (thisr.isMultipart()) {
String restrictedPath = getRestrictedPath(serviceurl, filePath, restrictions, null);
ReturnedMultipartDocument docm = conn.getMultipartXMLDocument(RequestMethod.PUT, restrictedPath, parts, creds, cache);
status = docm.getStatus();
} else {
ReturnedDocument docm = conn.getXMLDocument(RequestMethod.PUT, serviceurl + filePath, doc, creds, cache);
status = docm.getStatus();
}
// XXX Completely untested subrecord update
for (FieldSet fs : thisr.getAllSubRecords("PUT")) {
Record sr = fs.usesRecordId();
if (sr.isRealRecord()) {
// only deal with ones which are separate Records in the services
// get list of existing subrecords
JSONObject toDeleteList = new JSONObject();
JSONObject toUpdateList = new JSONObject();
JSONArray toCreateList = new JSONArray();
String getPath = serviceurl + filePath + "/" + sr.getServicesURL();
Integer subcount = 0;
String firstfile = "";
String[] filepaths = null;
while (!getPath.equals("")) {
JSONObject data = getListView(creds, cache, getPath, sr.getServicesListPath(), "csid", false, sr);
filepaths = (String[]) data.get("listItems");
subcount += filepaths.length;
if (firstfile.equals("") && subcount != 0) {
firstfile = filepaths[0];
}
// need to paginate // if(sr.getID().equals("termlistitem"))
for (String uri : filepaths) {
String path = uri;
if (path != null && path.startsWith("/")) {
path = path.substring(1);
}
toDeleteList.put(path, "original");
}
if (data.has("pagination")) {
Integer ps = Integer.valueOf(data.getJSONObject("pagination").getString("pageSize"));
Integer pn = Integer.valueOf(data.getJSONObject("pagination").getString("pageNum"));
Integer ti = Integer.valueOf(data.getJSONObject("pagination").getString("totalItems"));
if (ti > (ps * (pn + 1))) {
JSONObject pgRestrictions = new JSONObject();
pgRestrictions.put("pageSize", Integer.toString(ps));
pgRestrictions.put("pageNum", Integer.toString(pn + 1));
getPath = getRestrictedPath(getPath, pgRestrictions, sr.getServicesSearchKeyword(), "", false, "");
// need more values
} else {
getPath = "";
}
}
}
// how does that compare to what we need
if (sr.isType("authority")) {
// XXX need to use configuredVocabStorage
} else {
if (fs instanceof Field) {
JSONObject subdata = new JSONObject();
// loop thr jsonObject and find the fields I need
for (FieldSet subfs : sr.getAllFieldTopLevel("PUT")) {
String key = subfs.getID();
if (jsonObject.has(key)) {
subdata.put(key, jsonObject.get(key));
}
}
if (subcount == 0) {
// create
toCreateList.put(subdata);
} else {
// update - there should only be one
String firstcsid = firstfile;
toUpdateList.put(firstcsid, subdata);
toDeleteList.remove(firstcsid);
}
} else if (fs instanceof Group) {
// subrecorddata.put(value);
if (jsonObject.has(fs.getID())) {
Object subdata = jsonObject.get(fs.getID());
if (subdata instanceof JSONObject) {
if (((JSONObject) subdata).has("_subrecordcsid")) {
String thiscsid = ((JSONObject) subdata).getString("_subrecordcsid");
// update
if (toDeleteList.has(thiscsid)) {
toUpdateList.put(thiscsid, (JSONObject) subdata);
toDeleteList.remove(thiscsid);
} else {
// something has gone wrong... best just create it from scratch
toCreateList.put(subdata);
}
} else {
// create
toCreateList.put(subdata);
}
}
}
} else {
// need to find if we have csid's for each one
if (jsonObject.has(fs.getID())) {
Object subdata = jsonObject.get(fs.getID());
if (subdata instanceof JSONArray) {
JSONArray subarray = (JSONArray) subdata;
for (int i = 0; i < subarray.length(); i++) {
JSONObject subrecord = subarray.getJSONObject(i);
if (subrecord.has("_subrecordcsid") == true) {
String thiscsid = subrecord.getString("_subrecordcsid");
// update
if (toDeleteList.has(thiscsid)) {
toUpdateList.put(thiscsid, subrecord);
toDeleteList.remove(thiscsid);
} else {
// something has gone wrong... no existing records match the CSID being passed in, so
// we will try to create a new record. Could fail if a record with the same short ID already exists
toCreateList.put(subrecord);
}
} else if (subrecord.has("shortIdentifier") == true) {
String thisShortID = subrecord.getString("shortIdentifier");
// update
// See if we can find a matching short ID in the current list of items
String thiscsid = lookupCsid(cache, filepaths, serviceurl, thisShortID);
if (thiscsid != null) {
toUpdateList.put(thiscsid, subrecord);
toDeleteList.remove(thiscsid);
} else {
//
// Since we couldn't find an existing record with that short ID, we need to create it.
//
toCreateList.put(subrecord);
}
} else {
// create since we couldn't look for existing records via CSID or Short ID
toCreateList.put(subrecord);
}
}
}
}
}
String savePath = serviceurl + filePath + "/" + sr.getServicesURL() + "/";
// do delete JSONObject existingcsid = new JSONObject();
Iterator<String> rit = toDeleteList.keys();
while (rit.hasNext()) {
String key = rit.next();
// will fail if this record is a term having active references -i.e., one or more non-deleted records reference it.
deleteJSON(root, creds, cache, key, savePath, sr);
}
// do update JSONObject updatecsid = new JSONObject();
Iterator<String> keys = toUpdateList.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject value = toUpdateList.getJSONObject(key);
JSONObject subrRestrictions = new JSONObject();
updateJSON(root, creds, cache, key, value, subrRestrictions, sr, savePath);
}
// do create JSONArray createcsid = new JSONArray();
for (int i = 0; i < toCreateList.length(); i++) {
JSONObject value = toCreateList.getJSONObject(i);
subautocreateJSON(root, creds, cache, sr, value, savePath);
}
}
}
}
// throw new ExistException("Not found: "+serviceurl+filePath);
if (status > 299 || status < 200)
throw new UnderlyingStorageException("Bad response ", status, serviceurl + filePath);
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e.getStatus(), e.getUrl(), e);
} catch (JSONException e) {
throw new UnimplementedException("JSONException", e);
} catch (UnsupportedEncodingException e) {
throw new UnimplementedException("UnsupportedEncodingException", e);
}
}
Aggregations