use of org.collectionspace.csp.api.persistence.UnderlyingStorageException in project application by collectionspace.
the class ConfiguredVocabStorage method retrieveJSON.
@Override
public JSONObject retrieveJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String filePath, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
Integer num = 0;
String[] parts = filePath.split("/");
// deal with different url structures
String vocab, csid;
if ("_direct".equals(parts[0])) {
vocab = parts[2];
csid = parts[3];
num = 4;
} else {
vocab = parts[0];
if (!VOCAB_WILDCARD.equals(vocab)) {
vocab = RefName.shortIdToPath(vocab);
}
csid = (parts.length > 1) ? parts[1] : null;
num = 2;
}
if (parts.length > num) {
String extra = "";
Integer extradata = num + 1;
if (parts.length > extradata) {
extra = parts[extradata];
}
String servicepath = generateURL(vocab, csid, "", this.r);
return viewRetrieveJSON(root, creds, cache, null, parts[num], extra, restrictions, servicepath);
} else
return simpleRetrieveJSON(root, creds, cache, vocab, csid);
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Connection exception" + e.getLocalizedMessage(), e.getStatus(), e.getUrl(), e);
} catch (JSONException x) {
throw new UnderlyingStorageException("Error building JSON" + x.getLocalizedMessage(), x);
} catch (UnsupportedEncodingException x) {
throw new UnderlyingStorageException("Error UnsupportedEncodingException JSON", x);
}
}
use of org.collectionspace.csp.api.persistence.UnderlyingStorageException 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.csp.api.persistence.UnderlyingStorageException in project application by collectionspace.
the class VocabInstanceCache method createVocabulary.
// Only called if doesn't exist
private synchronized void createVocabulary(CSPRequestCredentials creds, CSPRequestCache cache, String id) throws ConnectionException, UnderlyingStorageException, ExistException {
Map<String, Document> body = new HashMap<String, Document>();
String[] path_parts = r.getServicesSingleInstancePath().split(":", 2);
String vocab_type = r.getVocabType();
String[] tag_parts = path_parts[1].split(",", 2);
body.put(path_parts[0], createList(tag_parts[0], tag_parts[1], id, vocab_type));
ReturnedURL out = conn.getMultipartURL(RequestMethod.POST, "/" + r.getServicesURL() + "/", body, creds, cache);
// log.info("/"+r.getServicesURL()+"/");
if (out.getStatus() > 299)
throw new UnderlyingStorageException("Could not create vocabulary status=" + out.getStatus(), out.getStatus(), "/" + r.getServicesURL() + "/");
csids.put(id, out.getURLTail());
}
use of org.collectionspace.csp.api.persistence.UnderlyingStorageException in project application by collectionspace.
the class VocabInstanceCache method buildVocabularies.
// XXX pagination? argh
@SuppressWarnings("unchecked")
private void buildVocabularies(CSPRequestCredentials creds, CSPRequestCache cache) throws ConnectionException, UnderlyingStorageException {
ReturnedDocument data = conn.getXMLDocument(RequestMethod.GET, "/" + r.getServicesURL() + "/", null, creds, cache);
Document doc = data.getDocument();
if (doc == null)
throw new UnderlyingStorageException("Could not retrieve vocabularies");
String[] path_parts = r.getServicesInstancesPath().split(":", 2);
String[] tag_parts = path_parts[1].split(",", 2);
List<Node> objects = doc.getDocument().selectNodes(tag_parts[1]);
for (Node object : objects) {
String name = "MISSING";
if (null != object.selectSingleNode("displayName")) {
name = object.selectSingleNode("displayName").getText();
}
if (null == object.selectSingleNode("shortIdentifier")) {
continue;
}
String base = object.selectSingleNode("shortIdentifier").getText();
if (base == null)
continue;
if (!vocabs.containsKey(base)) {
vocabs.put(base, name);
}
csids.put(base, object.selectSingleNode("csid").getText());
}
}
use of org.collectionspace.csp.api.persistence.UnderlyingStorageException in project application by collectionspace.
the class TestPermissions method testRoles.
// permissions
// create user
// list all permissions for a role
// add permission to a role
// change permission action in a role
@Test
public void testRoles() throws Exception {
// create user
JSONObject userdata = createUser("user1.json");
String userId = userdata.getString("userId");
String csidId = userdata.getString("accountId");
assertFalse(userdata == null);
// list roles for user
// cspace-services/authorization/roles/{csid}/permroles/xxx
Storage ss;
ss = makeServicesStorage();
JSONObject data = ss.getPathsJSON("accounts/" + userId + "/accountrole", null);
String[] roleperms = (String[]) data.get("listItems");
log.info(data.toString());
if (roleperms.length > 0) {
log.info("has roles already");
}
// create a role
JSONObject roledata = createRole("role.json");
String role = roledata.getString("roleId");
log.info(roledata.toString());
assertFalse(roledata == null);
// add a role
JSONObject addroledata = new JSONObject();
addroledata.put("roleId", role);
addroledata.put("roleName", roledata.getString("roleName"));
JSONArray rolearray = new JSONArray();
rolearray.put(addroledata);
JSONObject addrole = new JSONObject();
addrole.put("role", rolearray);
addrole.put("account", userdata);
log.info(addrole.toString());
// add permissions to role
String path = ss.autocreateJSON("userrole", addrole, null);
log.info(path);
assertNotNull(path);
// delete role
ss.deleteJSON("role/" + role);
try {
ss.retrieveJSON("role/" + role, new JSONObject());
// XXX use JUnit exception annotation
assertFalse(true);
} catch (UnderlyingStorageException e) {
// XXX use JUnit exception annotation
assertTrue(true);
}
// delete user
ss.deleteJSON("users/" + csidId);
}
Aggregations