use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.
the class ConfiguredVocabStorage method updateJSON.
public void updateJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, JSONObject jsonObject, JSONObject restrictions, Record thisr, String savePath) throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
String csid = savePath.split("/")[3];
Map<String, Document> body = new HashMap<String, Document>();
for (String section : r.getServicesRecordPathKeys()) {
String path = r.getServicesRecordPath(section);
String[] record_path = path.split(":", 2);
String[] tag_path = record_path[1].split(",", 2);
Document temp = createEntry(section, tag_path[0], tag_path[1], jsonObject, null, null, thisr, false);
if (temp != null) {
body.put(record_path[0], temp);
// log.info(temp.asXML());
}
}
handleHierarchyPayloadSend(thisr, body, jsonObject, csid);
ReturnedMultipartDocument out = conn.getMultipartXMLDocument(RequestMethod.PUT, savePath, body, creds, cache);
if (out.isErrorStatus()) {
if (out.isTransactionFailedStatus()) {
throw new UnderlyingStorageException(VOCABULARY_UPDATE_FAILED_MESSAGE + ": " + out.TRANSACTION_FAILED_MESSAGE, out.getStatus(), savePath);
} else {
throw new UnderlyingStorageException(VOCABULARY_UPDATE_FAILED_MESSAGE, out.getStatus(), savePath);
}
}
// subrecord update
for (FieldSet fs : thisr.getAllSubRecords("PUT")) {
Record sr = fs.usesRecordId();
// get list of existing subrecords
JSONObject existingcsid = new JSONObject();
JSONObject updatecsid = new JSONObject();
JSONArray createcsid = new JSONArray();
String getPath = savePath + "/" + sr.getServicesURL();
Integer subcount = 0;
String firstfile = "";
while (!getPath.equals("")) {
JSONObject data = getListView(creds, cache, getPath, sr.getServicesListPath(), "csid", false, sr);
String[] filepaths = (String[]) data.get("listItems");
subcount += filepaths.length;
if (firstfile.equals("") && subcount != 0) {
firstfile = filepaths[0];
}
for (String uri : filepaths) {
String path = uri;
if (path != null && path.startsWith("/"))
path = path.substring(1);
existingcsid.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")) {
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
createcsid.put(subdata);
} else {
// update - there should only be one
String firstcsid = firstfile;
updatecsid.put(firstcsid, subdata);
existingcsid.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 (existingcsid.has(thiscsid)) {
updatecsid.put(thiscsid, (JSONObject) subdata);
existingcsid.remove(thiscsid);
} else {
// something has gone wrong... best just create it from scratch
createcsid.put(subdata);
}
} else {
// create
createcsid.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")) {
String thiscsid = subrecord.getString("_subrecordcsid");
// update
if (existingcsid.has(thiscsid)) {
updatecsid.put(thiscsid, (JSONObject) subdata);
existingcsid.remove(thiscsid);
} else {
// something has gone wrong... best just create it from scratch
createcsid.put(subdata);
}
} else {
// create
createcsid.put(subdata);
}
}
}
}
}
String savePathSr = savePath + "/" + sr.getServicesURL() + "/";
// do delete JSONObject existingcsid = new JSONObject();
Iterator<String> rit = existingcsid.keys();
while (rit.hasNext()) {
String key = rit.next();
deleteJSON(root, creds, cache, key, savePathSr, sr);
}
// do update JSONObject updatecsid = new JSONObject();
Iterator<String> keys = updatecsid.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject value = updatecsid.getJSONObject(key);
String thissave = savePathSr + key;
updateJSON(root, creds, cache, value, new JSONObject(), sr, thissave);
// updateJSON( root, creds, cache, key, value, sr, savePathSr);
}
// do create JSONArray createcsid = new JSONArray();
for (int i = 0; i < createcsid.length(); i++) {
JSONObject value = createcsid.getJSONObject(i);
subautocreateJSON(root, creds, cache, sr, value, savePathSr);
}
}
}
// XXX dont currently update the shortID???
// cache.setCached(getClass(),new String[]{"shortId",vocab,filePath.split("/")[1]},shortId);
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Connection exception " + e.getLocalizedMessage(), e.getStatus(), e.getUrl(), e);
} catch (JSONException e) {
throw new UnderlyingStorageException("Cannot parse surrounding JSON " + e.getLocalizedMessage(), e);
} catch (UnsupportedEncodingException e) {
throw new UnimplementedException("UnsupportedEncodingException" + e.getLocalizedMessage(), e);
}
}
use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.
the class AuthorizationStorage method getPaths.
/**
* Returns a list of csid's from a certain type of record
*/
@Override
@SuppressWarnings("unchecked")
public String[] getPaths(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String rootPath, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
Document list = null;
List<String> out = new ArrayList<String>();
String path = getRestrictedPath(r.getServicesURL(), restrictions, "res", "", false, "");
ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET, path, null, creds, cache);
if (all.getStatus() != 200) {
throw new ConnectionException("Bad request in Authorization Storage: status not 200", all.getStatus(), path);
}
list = all.getDocument();
List<Node> objects = list.selectNodes(r.getServicesListPath());
for (Node object : objects) {
String csid = object.valueOf("@csid");
out.add(csid);
setGleanedValue(cache, r.getServicesURL() + "/" + csid, view_map.get(object.getName()), object.getText());
}
return out.toArray(new String[0]);
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e.getStatus(), e.getUrl(), e);
} catch (UnsupportedEncodingException e) {
throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e);
} catch (JSONException e) {
throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e);
}
}
use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.
the class AuthorizationStorage method simpleRetrieveJSONFullPath.
public JSONObject simpleRetrieveJSONFullPath(CSPRequestCredentials creds, CSPRequestCache cache, String filePath, Record thisr) throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
JSONObject out = new JSONObject();
if (thisr.isMultipart()) {
ReturnedMultipartDocument doc = conn.getMultipartXMLDocument(RequestMethod.GET, filePath, null, creds, cache);
if ((doc.getStatus() < 200 || doc.getStatus() >= 300))
throw new UnderlyingStorageException("Does not exist ", doc.getStatus(), filePath);
for (String section : thisr.getServicesRecordPathKeys()) {
String path = thisr.getServicesRecordPath(section);
String[] parts = path.split(":", 2);
convertToJson(out, doc.getDocument(parts[0]), thisr, "GET", section, "", "");
}
} else {
ReturnedDocument doc = conn.getXMLDocument(RequestMethod.GET, filePath, null, creds, cache);
if ((doc.getStatus() < 200 || doc.getStatus() >= 300)) {
if (doc.getStatus() == 401) {
throw new UnauthorizedException("Username and/or password are invalid.", doc.getStatus(), filePath);
} else if (doc.getStatus() == 409) {
throw new ConflictException("Conflict with request. The user's tenant may be disabled. Contact your CollectionSpace administrator.", doc.getStatus(), filePath);
} else {
String status = Integer.toString(doc.getStatus());
throw new UnderlyingStorageException("Does not exist ", doc.getStatus(), filePath);
}
}
convertToJson(out, doc.getDocument(), thisr, "GET", "common", "");
}
return out;
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e.getStatus(), e.getUrl(), e);
} catch (JSONException e) {
throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e);
}
}
use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.
the class AuthorizationStorage method getPathsJSON.
/**
* Gets a list of csids of a certain type of record together with the pagination info
* permissions might need to break the mold tho.
*/
@Override
@SuppressWarnings("unchecked")
public JSONObject getPathsJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String rootPath, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
JSONObject out = new JSONObject();
// PLS: why on earth would reports be routed through AuthStorage?!?!
if (r.getID().equals("reports") || r.getID().equals("batch")) {
String path = getRestrictedPath(r.getServicesURL(), restrictions, r.getServicesSearchKeyword(), "", false, "");
JSONObject data = getListView(creds, cache, path, r.getServicesListPath(), "csid", false, r);
return data;
}
Document list = null;
String prefix = null;
Boolean queryadded = false;
JSONObject pagination = new JSONObject();
List<String> listitems = new ArrayList<String>();
String serviceurl = getRestrictedPath(r.getServicesURL(), restrictions, r.getServicesSearchKeyword(), "", false, "");
ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET, serviceurl, null, creds, cache);
if (all.getStatus() != 200) {
throw new ConnectionException("Bad request in Authorization Storage getPathsJSON: status not 200", all.getStatus(), serviceurl);
}
list = all.getDocument();
String listItemPath = r.getServicesListPath();
String[] listItemPathElements = listItemPath.split("/");
if (listItemPathElements.length != 2) {
throw new RuntimeException("Illegal list item path " + listItemPath);
}
String listNodeName = listItemPathElements[0];
String listItemNodeName = listItemPathElements[1];
String listNodeChildrenSelector = "/" + listNodeName + "/*";
List<Node> nodes = list.selectNodes(listNodeChildrenSelector);
for (Node node : nodes) {
if (listItemNodeName.equals(node.getName())) {
String csid = node.valueOf("@csid");
listitems.add(csid);
String fullPath = r.getServicesURL() + "/" + csid;
if (view_map.get(node.getName()) != null) {
setGleanedValue(cache, fullPath, view_map.get(node.getName()), node.getText());
}
// Now glean the values we need from the child nodes
List<Node> fields = node.selectNodes("*");
for (Node field : fields) {
// Is this a field we want?
String json_name = view_map.get(field.getName());
if (json_name != null) {
String value = field.getText();
setGleanedValue(cache, r.getServicesURL() + "/" + csid, json_name, value);
}
}
} else {
pagination.put(node.getName(), node.getText());
}
}
out.put("pagination", pagination);
out.put("listItems", listitems.toArray(new String[0]));
return out;
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e.getStatus(), e.getUrl(), e);
} catch (UnsupportedEncodingException e) {
throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e);
} catch (JSONException e) {
throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e);
}
}
use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.
the class AuthorizationStorage method deleteJSON.
/**
* Remove an object in the Service Layer.
*/
@Override
public void deleteJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String filePath) throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
int status = 0;
if (r.hasDeleteMethod()) {
// get all data to post back
// hopefully the filepath we have is the filepath to get the data from
Document doc = null;
try {
doc = simpleRetrieveXML(creds, cache, filePath + "/");
String nodepath = "/" + r.getServicesListPath() + "/*";
List<Node> nodes = doc.selectNodes(nodepath);
if (nodes.size() > 0) {
status = 201;
status = conn.getNone(RequestMethod.DELETE, filePath, null, creds, cache);
// post it back to delete it
/*
log.info("TRYING TO DELETE ACCOUNTROLE");
log.info(doc.asXML());
log.info(filePath+"?_method=delete");
ReturnedURL url = null;
url = conn.getURL(RequestMethod.POST, filePath+"?_method=delete", doc, creds, cache);
status = url.getStatus();
//status=conn.getNone(RequestMethod.POST,r.getServicesURL()+"/"+filePath+"?_method=delete",doc,creds,cache);
*/
} else {
// if we didn't need to delete it because there was nothing there then everything was good
status = 201;
}
} catch (ExistException ex) {
// ignore as nothign to delete if nothing exists
status = 201;
}
} else {
status = conn.getNone(RequestMethod.DELETE, r.getServicesURL() + "/" + filePath, null, creds, cache);
}
if (// XXX CSPACE-73, should be 404
status > 299 || status < 200)
throw new UnderlyingStorageException("Service layer exception status=" + status, status, r.getServicesURL() + "/" + filePath);
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Service layer exception", e);
}
}
Aggregations