Search in sources :

Example 6 with Repeat

use of org.collectionspace.chain.csp.schema.Repeat in project application by collectionspace.

the class XmlJsonConversion method addRepeatedNodeToJson.

private static JSONArray addRepeatedNodeToJson(Element container, Repeat f, String permlevel, JSONObject tempSon) throws JSONException {
    JSONArray node = new JSONArray();
    List<FieldSet> children = getChildrenWithGroupFields(f, permlevel);
    JSONArray elementlist = extractRepeatData(container, f, permlevel);
    JSONObject siblingitem = new JSONObject();
    for (int i = 0; i < elementlist.length(); i++) {
        JSONObject element = elementlist.getJSONObject(i);
        Iterator<?> rit = element.keys();
        while (rit.hasNext()) {
            String key = (String) rit.next();
            JSONArray arrvalue = new JSONArray();
            for (FieldSet fs : children) {
                if (fs instanceof Repeat && ((Repeat) fs).hasServicesParent()) {
                    if (!((Repeat) fs).getServicesParent()[0].equals(key)) {
                        continue;
                    }
                    Object value = element.get(key);
                    arrvalue = (JSONArray) value;
                } else {
                    if (!fs.getID().equals(key)) {
                        continue;
                    }
                    Object value = element.get(key);
                    arrvalue = (JSONArray) value;
                }
                if (fs instanceof Field) {
                    for (int j = 0; j < arrvalue.length(); j++) {
                        JSONObject repeatitem = new JSONObject();
                        // XXX remove when service layer supports primary tags
                        if (f.hasPrimary() && j == 0) {
                            repeatitem.put("_primary", true);
                        }
                        Element child = (Element) arrvalue.get(j);
                        Object val = child.getText();
                        Field field = (Field) fs;
                        String id = field.getID();
                        if (f.asSibling()) {
                            addExtraToJson(siblingitem, child, field, tempSon);
                            if (field.getDataType().equals("boolean")) {
                                siblingitem.put(id, (Boolean.parseBoolean((String) val) ? true : false));
                            } else {
                                siblingitem.put(id, val);
                            }
                        } else {
                            addExtraToJson(repeatitem, child, field, tempSon);
                            if (field.getDataType().equals("boolean")) {
                                repeatitem.put(id, (Boolean.parseBoolean((String) val) ? true : false));
                            } else {
                                repeatitem.put(id, val);
                            }
                            node.put(repeatitem);
                        }
                        tempSon = addtemp(tempSon, fs.getID(), child.getText());
                    }
                } else if (fs instanceof Group) {
                    JSONObject tout = new JSONObject();
                    JSONObject tempSon2 = new JSONObject();
                    Group rp = (Group) fs;
                    addRepeatToJson(tout, container, rp, permlevel, tempSon2, "", "");
                    if (f.asSibling()) {
                        JSONArray a1 = tout.getJSONArray(rp.getID());
                        JSONObject o1 = a1.getJSONObject(0);
                        siblingitem.put(fs.getID(), o1);
                    } else {
                        JSONObject repeatitem = new JSONObject();
                        repeatitem.put(fs.getID(), tout.getJSONArray(rp.getID()));
                        node.put(repeatitem);
                    }
                    tempSon = addtemp(tempSon, rp.getID(), tout.getJSONArray(rp.getID()));
                // log.info(f.getID()+":"+rp.getID()+":"+tempSon.toString());
                } else if (fs instanceof Repeat) {
                    JSONObject tout = new JSONObject();
                    JSONObject tempSon2 = new JSONObject();
                    Repeat rp = (Repeat) fs;
                    addRepeatToJson(tout, container, rp, permlevel, tempSon2, "", "");
                    if (f.asSibling()) {
                        siblingitem.put(fs.getID(), tout.getJSONArray(rp.getID()));
                    } else {
                        JSONObject repeatitem = new JSONObject();
                        repeatitem.put(fs.getID(), tout.getJSONArray(rp.getID()));
                        node.put(repeatitem);
                    }
                    tempSon = addtemp(tempSon, rp.getID(), tout.getJSONArray(rp.getID()));
                // log.info(f.getID()+":"+rp.getID()+":"+tempSon.toString());
                }
            }
        }
    }
    if (f.asSibling()) {
        node.put(siblingitem);
    }
    return node;
}
Also used : Field(org.collectionspace.chain.csp.schema.Field) Group(org.collectionspace.chain.csp.schema.Group) FieldSet(org.collectionspace.chain.csp.schema.FieldSet) JSONObject(org.json.JSONObject) Element(org.dom4j.Element) JSONArray(org.json.JSONArray) Repeat(org.collectionspace.chain.csp.schema.Repeat) JSONObject(org.json.JSONObject)

Example 7 with Repeat

use of org.collectionspace.chain.csp.schema.Repeat in project application by collectionspace.

the class GenericStorage method simpleRetrieveJSON.

/**
 * return data just as the service layer gives it to the App layer
 * no extra columns required
 * @param creds
 * @param cache
 * @param filePath
 * @param servicesurl
 * @param thisr
 * @return
 * @throws ExistException
 * @throws UnimplementedException
 * @throws UnderlyingStorageException
 */
public JSONObject simpleRetrieveJSON(CSPRequestCredentials creds, CSPRequestCache cache, String filePath, String servicesurl, Record thisr) throws ExistException, UnimplementedException, UnderlyingStorageException {
    String csid = "";
    if (filePath == null) {
        filePath = "";
    }
    String[] path_parts = filePath.split("/");
    if (path_parts.length > 1)
        csid = path_parts[1];
    else
        csid = filePath;
    JSONObject out = new JSONObject();
    try {
        String softpath = filePath;
        if (thisr.hasSoftDeleteMethod()) {
            softpath = softpath(filePath);
        }
        if (thisr.hasHierarchyUsed("screen")) {
            softpath = hierarchicalpath(softpath);
        }
        if (thisr.isMultipart()) {
            ReturnedMultipartDocument doc = conn.getMultipartXMLDocument(RequestMethod.GET, servicesurl + softpath, null, creds, cache);
            if ((doc.getStatus() < 200 || doc.getStatus() >= 300))
                throw new UnderlyingStorageException("Does not exist ", doc.getStatus(), softpath);
            for (String section : thisr.getServicesRecordPathKeys()) {
                String path = thisr.getServicesRecordPath(section);
                String[] parts = path.split(":", 2);
                if (doc.getDocument(parts[0]) != null) {
                    convertToJson(out, doc.getDocument(parts[0]), thisr, "GET", section, csid);
                }
            }
            // If this record has hierarchy, will pull out the relations section and map it to the hierarchy
            // fields (special case handling of XML-JSON
            handleHierarchyPayloadRetrieve(thisr, doc, out, csid);
        } else {
            ReturnedDocument doc = conn.getXMLDocument(RequestMethod.GET, servicesurl + softpath, null, creds, cache);
            if ((doc.getStatus() < 200 || doc.getStatus() >= 300))
                throw new UnderlyingStorageException("Does not exist ", doc.getStatus(), softpath);
            convertToJson(out, doc.getDocument(), thisr, "GET", "common", csid);
        }
    } 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);
    }
    /*
		 * Get data for any sub records that are part of this record e.g. contact in person, blob in media
		 */
    try {
        for (FieldSet fs : thisr.getAllSubRecords("GET")) {
            Boolean validator = true;
            Record sr = fs.usesRecordId();
            if (fs.usesRecordValidator() != null) {
                validator = false;
                if (out.has(fs.usesRecordValidator())) {
                    String test = out.getString(fs.usesRecordValidator());
                    if (test != null && !test.equals("")) {
                        validator = true;
                    }
                }
            }
            if (validator) {
                String getPath = servicesurl + filePath + "/" + sr.getServicesURL();
                if (null != fs.getServicesUrl()) {
                    getPath = fs.getServicesUrl();
                }
                if (fs.getWithCSID() != null) {
                    getPath = getPath + "/" + out.getString(fs.getWithCSID());
                }
                // need to get update and delete working? tho not going to be used for media as handling blob seperately
                if (fs instanceof Group) {
                    JSONObject outer = simpleRetrieveJSON(creds, cache, getPath, "", sr);
                    JSONArray group = new JSONArray();
                    group.put(outer);
                    out.put(fs.getID(), group);
                }
                if (fs instanceof Repeat) {
                    // NEED TO GET A LIST OF ALL THE THINGS
                    JSONArray repeat = new JSONArray();
                    String path = getPath;
                    while (!path.equals("")) {
                        JSONObject data = getListView(creds, cache, path, sr.getServicesListPath(), "csid", false, r);
                        if (data.has("listItems")) {
                            String[] results = (String[]) data.get("listItems");
                            for (String result : results) {
                                JSONObject rout = simpleRetrieveJSON(creds, cache, getPath + "/" + result, "", sr);
                                // add in csid so I can do update with a modicum of confidence
                                rout.put("_subrecordcsid", result);
                                repeat.put(rout);
                            }
                        }
                        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 restrictions = new JSONObject();
                                restrictions.put("pageSize", Integer.toString(ps));
                                restrictions.put("pageNum", Integer.toString(pn + 1));
                                path = getRestrictedPath(getPath, restrictions, sr.getServicesSearchKeyword(), "", false, "");
                            // need more values
                            } else {
                                path = "";
                            }
                        }
                    }
                    // group.put(outer);
                    out.put(fs.getID(), repeat);
                }
            }
        }
    } catch (Exception e) {
    // ignore exceptions for sub records at the moment - make it more intelligent later
    // throw new UnderlyingStorageException("Service layer exception",e);
    }
    return out;
}
Also used : Group(org.collectionspace.chain.csp.schema.Group) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) Repeat(org.collectionspace.chain.csp.schema.Repeat) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) UnimplementedException(org.collectionspace.csp.api.persistence.UnimplementedException) DocumentException(org.dom4j.DocumentException) JSONException(org.json.JSONException) ExistException(org.collectionspace.csp.api.persistence.ExistException) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException) IOException(java.io.IOException) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ReturnedMultipartDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument) FieldSet(org.collectionspace.chain.csp.schema.FieldSet) JSONObject(org.json.JSONObject) Record(org.collectionspace.chain.csp.schema.Record) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)

Example 8 with Repeat

use of org.collectionspace.chain.csp.schema.Repeat in project application by collectionspace.

the class GenericStorage method refObjViewRetrieveJSON.

/**
 * get data needed for list of objects related to a termUsed
 * @param storage
 * @param creds
 * @param cache
 * @param path
 * @return
 * @throws ExistException
 * @throws UnderlyingStorageException
 * @throws JSONException
 * @throws UnimplementedException
 */
public JSONObject refObjViewRetrieveJSON(ContextualisedStorage storage, CSPRequestCredentials creds, CSPRequestCache cache, String path, JSONObject restrictions, Record vr) throws ExistException, UnderlyingStorageException, JSONException, UnimplementedException {
    JSONObject out = new JSONObject();
    try {
        // map of servicenames of fields to descriptors
        Map<String, String> refObj_view_good = new HashMap<String, String>();
        // map of csid to service name of field
        Map<String, String> refObj_view_map = new HashMap<String, String>();
        if (vr.hasRefObjUsed()) {
            path = getRestrictedPath(path, restrictions, "kw", "", false, "");
            // XXX need a way to append the data needed from the field,
            // which we don't know until after we have got the information...
            refObj_view_map.put("docType", "docType");
            refObj_view_map.put("docId", "docId");
            refObj_view_map.put("docName", "docName");
            refObj_view_map.put("docNumber", "docNumber");
            refObj_view_map.put("sourceField", "sourceField");
            refObj_view_map.put("uri", "uri");
            refObj_view_map.put("refName", "refName");
            refObj_view_good.put("terms_docType", "docType");
            refObj_view_good.put("terms_docId", "docId");
            refObj_view_good.put("terms_docName", "docName");
            refObj_view_good.put("terms_docNumber", "docNumber");
            refObj_view_good.put("terms_sourceField", "sourceField");
            refObj_view_good.put("terms_refName", "refName");
            // XXX this might be the wrong record to pass to checkf or hard/soft delet listing
            JSONObject data = getRepeatableListView(storage, creds, cache, path, "authority-ref-doc-list/authority-ref-doc-item", "uri", true, vr, refObj_view_map);
            JSONArray recs = data.getJSONArray("listItems");
            if (data.has("pagination")) {
                out.put("pagination", data.getJSONObject("pagination"));
            }
            JSONArray items = new JSONArray();
            // String[] filepaths = (String[]) data.get("listItems");
            for (int i = 0; i < recs.length(); ++i) {
                String uri = recs.getJSONObject(i).getString("csid");
                // recs.getJSONObject(i).getString("csid");
                String filePath = uri;
                if (filePath != null && filePath.startsWith("/"))
                    filePath = filePath.substring(1);
                String[] parts = filePath.split("/");
                String recordurl = parts[0];
                Record thisr = vr.getSpec().getRecordByServicesUrl(recordurl);
                // Set up the glean maps required for this record. We need to reset these each time
                // through the loop, because every record could be a different type.
                Map<String, String> thisr_view_good = new HashMap<String, String>(refObj_view_good);
                Map<String, String> thisr_view_map = new HashMap<String, String>(refObj_view_map);
                Set<String> thisr_xxx_view_deurn = new HashSet<String>();
                Set<String> thisr_view_search_optional = new HashSet<String>();
                Map<String, List<String>> thisr_view_merge = new HashMap<String, List<String>>();
                Map<String, List<String>> thisr_view_useCsid = new HashMap<String, List<String>>();
                initializeGlean(thisr, thisr_view_good, thisr_view_map, thisr_xxx_view_deurn, thisr_view_search_optional, thisr_view_merge, thisr_view_useCsid);
                String csid = parts[parts.length - 1];
                JSONObject dataitem = miniViewRetrieveJSON(cache, creds, csid, "terms", uri, thisr, thisr_view_good, thisr_xxx_view_deurn, thisr_view_search_optional, thisr_view_merge, thisr_view_useCsid);
                dataitem.getJSONObject("summarylist").put("uri", filePath);
                String key = recs.getJSONObject(i).getString("sourceField");
                dataitem.getJSONObject("summarylist").put("sourceField", key);
                String fieldName = "unknown";
                String fieldSelector = "unknown";
                if (key.contains(":")) {
                    fieldName = key.split(":")[1];
                    // FIXME: We might remove the following if CSPACE-2909's fix makes this moot - ADR 2012-07-19
                    while (thisr.getFieldFullList(fieldName) instanceof Repeat || thisr.getFieldFullList(fieldName) instanceof Group) {
                        fieldName = ((Repeat) thisr.getFieldFullList(fieldName)).getChildren("GET")[0].getID();
                    }
                    Field fieldinstance = (Field) thisr.getFieldFullList(fieldName);
                    fieldSelector = fieldinstance.getSelector();
                }
                dataitem.put("csid", csid);
                dataitem.put("sourceFieldselector", fieldSelector);
                dataitem.put("sourceFieldName", fieldName);
                dataitem.put("sourceFieldType", dataitem.getJSONObject("summarylist").getString("docType"));
                dataitem.put("sourceFieldType", dataitem.getJSONObject("summarylist").getString("docType"));
                // items.put(csid+":"+key,dataitem);
                items.put(dataitem);
            }
            out.put("items", items);
        }
        return out;
    } catch (ConnectionException e) {
        log.error("failed to retrieve refObjs for " + path);
        JSONObject dataitem = new JSONObject();
        dataitem.put("csid", "");
        dataitem.put("sourceFieldselector", "Functionality Failed");
        dataitem.put("sourceFieldName", "Functionality Failed");
        dataitem.put("sourceFieldType", "Functionality Failed");
        dataitem.put("message", e.getMessage());
        out.put("Functionality Failed", dataitem);
        // return out;
        throw new UnderlyingStorageException("Connection problem" + e.getLocalizedMessage(), e.getStatus(), e.getUrl(), e);
    } catch (UnsupportedEncodingException uae) {
        log.error("failed to retrieve refObjs for " + path);
        JSONObject dataitem = new JSONObject();
        dataitem.put("message", uae.getMessage());
        out.put("Functionality Failed", dataitem);
        throw new UnderlyingStorageException("Problem building query" + uae.getLocalizedMessage(), uae);
    }
}
Also used : Group(org.collectionspace.chain.csp.schema.Group) HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Repeat(org.collectionspace.chain.csp.schema.Repeat) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) Field(org.collectionspace.chain.csp.schema.Field) JSONObject(org.json.JSONObject) Record(org.collectionspace.chain.csp.schema.Record) ArrayList(java.util.ArrayList) List(java.util.List) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException) HashSet(java.util.HashSet)

Example 9 with Repeat

use of org.collectionspace.chain.csp.schema.Repeat in project application by collectionspace.

the class SchemaStructure method makeAGroupField.

/**
 * Do all the magic to make a GroupField
 *
 * @param fs
 * @param context
 * @throws JSONException
 */
protected JSONObject makeAGroupField(FieldSet fs, UISpecRunContext context) throws JSONException {
    JSONObject out = new JSONObject();
    if (fs instanceof Field || fs instanceof Repeat) {
        JSONObject subexpander = new JSONObject();
        JSONObject options = new JSONObject();
        String[] parts = fs.getUIType().split("/");
        Record subitems = fs.getRecord().getSpec().getRecordByServicesUrl(parts[1]);
        UISpecRunContext sub = context.createChild();
        sub.setUIPrefix(fs.getID());
        sub.setPad(false);
        if (isAStructureDate(fs)) {
            makeAStructureDate(fs, out, subexpander, options, subitems, sub, context);
        } else if (fs.isASelfRenderer()) {
            makeASelfRenderer(fs, context, out, subexpander, options, subitems, sub);
        } else {
            makeAOtherGroup(fs, out, subexpander, options, subitems, sub);
        }
    }
    return out;
}
Also used : Field(org.collectionspace.chain.csp.schema.Field) UISpecRunContext(org.collectionspace.chain.csp.schema.UISpecRunContext) JSONObject(org.json.JSONObject) Repeat(org.collectionspace.chain.csp.schema.Repeat) Record(org.collectionspace.chain.csp.schema.Record)

Example 10 with Repeat

use of org.collectionspace.chain.csp.schema.Repeat in project application by collectionspace.

the class SchemaStructure method makeASubRecordEntry.

/**
 * Do all the magic to make a sub record thing first is it nested directly
 * in the data or one level under
 *
 * @param out
 * @param fs
 * @param context
 * @throws JSONException
 */
protected void makeASubRecordEntry(JSONObject out, FieldSet fs, UISpecRunContext context, JSONObject outerlayer) throws JSONException {
    // create group item or field at the same level as parent fields - do not nest
    UISpecRunContext sub = context;
    if (!fs.getUISpecInherit()) {
        // default behaviour do group or field as expected by changing the context (adds more info to the selectors etc)
        sub = context.createChild();
        if (!fs.getSelectorAffix().equals("")) {
            sub.setUIAffix(fs.getSelectorAffix());
        }
        String sp = fs.getUISpecPrefix();
        if (sp != null)
            sub.setUIPrefix(sp);
    }
    Record subrecord = fs.usesRecordId();
    Boolean repeated = false;
    if (fs.getParent() instanceof Repeat || (fs instanceof Repeat && !(fs instanceof Group))) {
        repeated = true;
    }
    if (outerlayer == null) {
        outerlayer = out;
    }
    if (fs instanceof Group) {
        Group gp = (Group) fs;
        if (gp.isGrouped()) {
            sub.setPad(false);
        }
    }
    actualSubRecordField(out, fs, sub, subrecord, repeated, outerlayer);
}
Also used : Group(org.collectionspace.chain.csp.schema.Group) UISpecRunContext(org.collectionspace.chain.csp.schema.UISpecRunContext) Record(org.collectionspace.chain.csp.schema.Record) Repeat(org.collectionspace.chain.csp.schema.Repeat)

Aggregations

Repeat (org.collectionspace.chain.csp.schema.Repeat)19 FieldSet (org.collectionspace.chain.csp.schema.FieldSet)11 Field (org.collectionspace.chain.csp.schema.Field)9 Group (org.collectionspace.chain.csp.schema.Group)9 Record (org.collectionspace.chain.csp.schema.Record)7 JSONObject (org.json.JSONObject)7 FieldParent (org.collectionspace.chain.csp.schema.FieldParent)6 JSONArray (org.json.JSONArray)6 Element (org.dom4j.Element)5 ConnectionException (org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)3 UnderlyingStorageException (org.collectionspace.csp.api.persistence.UnderlyingStorageException)3 QName (org.dom4j.QName)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ArrayList (java.util.ArrayList)2 ReturnedDocument (org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument)2 ReturnedMultipartDocument (org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument)2 UISpecRunContext (org.collectionspace.chain.csp.schema.UISpecRunContext)2 IOException (java.io.IOException)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1