Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

In this page you can find the example usage for org.json JSONObject get.

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:config.Manejador.java

public JSONObject SelectIntoArray(JSONObject objeto, JSONObject busqueda) throws JSONException {
    JSONObject retorno = this.dont_exists;

    JSONArray js_array_obj;// w  w  w .  ja  v  a2 s.  com
    JSONArray js_array_busqueda;

    Iterator it_json = objeto.keys();
    Iterator it_busqueda = busqueda.keys();

    String key_busqueda = "", key_obj = "", key_arr_obj = "";

    int idx_busqueda = 0;
    boolean fin = false;

    if (it_busqueda.hasNext()) {
        key_busqueda = it_busqueda.next().toString();
        js_array_busqueda = (JSONArray) busqueda.get(key_busqueda);
        JSONObject obj_into_arr = js_array_busqueda.getJSONObject(0);

        Iterator it_key_to_search = obj_into_arr.keys();
        if (it_key_to_search.hasNext()) {
            String key_into_arr = it_key_to_search.next().toString();
            String value_of_key = obj_into_arr.get(key_into_arr).toString();

            while (it_json.hasNext()) {
                key_obj = it_json.next().toString();

                if (!key_obj.equals(key_busqueda)) {
                    continue;
                }

                js_array_obj = (JSONArray) objeto.get(key_obj);

                for (int i = 0, l = js_array_obj.length(); i < l; i++) {
                    JSONObject arr_obj = js_array_obj.getJSONObject(i);

                    Iterator it_arr_obj = arr_obj.keys();

                    while (it_arr_obj.hasNext()) {
                        key_arr_obj = it_arr_obj.next().toString();
                        String value_of_key_obj = arr_obj.get(key_arr_obj).toString();

                        if (!key_arr_obj.equals(key_into_arr) || !value_of_key_obj.equals(value_of_key)) {
                            continue;
                        }

                        retorno = objeto;
                        retorno.remove(key_obj);

                        arr_obj.put("idx", idx_busqueda);
                        retorno.put(key_obj, new JSONArray("[" + arr_obj + "]"));

                        fin = true;
                        break;
                    }

                    idx_busqueda++;
                }

                if (fin)
                    break;
            }
        }
    }

    return retorno;
}

From source file:config.Manejador.java

public boolean update(JSONObject criteria, JSONObject changes) throws JSONException, IOException {
    JSONObject js_obj = new JSONObject(this.src_archivo);
    JSONArray js_array = (JSONArray) js_obj.get(this.nom_coleccion);

    boolean retorno = false;

    JSONObject busqueda = this.Select(criteria);

    if (!busqueda.equals(this.dont_exists)) {
        Iterator it_changes = changes.keys();
        while (it_changes.hasNext()) {
            String key_c = it_changes.next().toString();
            busqueda.put(key_c, changes.get(key_c));
        }//  www .j av a  2 s  . c o  m

        int idx = busqueda.getInt("idx");
        busqueda.remove("idx");

        js_obj.put(this.nom_coleccion, js_array.put(idx, busqueda));
        retorno = true;
    }

    this.src_archivo = js_obj.toString(4);
    this.saveFile();
    return retorno;
}

From source file:config.Manejador.java

public boolean updateIntoArray(JSONObject criteria, JSONObject changes) throws JSONException, IOException {
    boolean retorno = false;

    JSONObject js_obj = new JSONObject(this.src_archivo);
    JSONArray js_array = (JSONArray) js_obj.get(this.nom_coleccion);

    if (criteria.has("idx")) {
        int idx_registro = criteria.getInt("idx");
        JSONObject registro = js_array.getJSONObject(idx_registro);
        JSONArray arr_registro, arr_criteria, arr_changes;
        JSONObject obj_arr_registro, obj_arr_criteria, obj_arr_changes;

        Iterator it_changes = changes.keys();

        while (it_changes.hasNext()) {
            String key = it_changes.next().toString();

            int idx_arr_registro = 0;
            arr_registro = registro.getJSONArray(key);
            arr_criteria = criteria.getJSONArray(key);
            arr_changes = changes.getJSONArray(key);

            obj_arr_criteria = arr_criteria.getJSONObject(0);
            obj_arr_changes = arr_changes.getJSONObject(0);

            idx_arr_registro = obj_arr_criteria.getInt("idx");
            obj_arr_registro = arr_registro.getJSONObject(idx_arr_registro);

            Iterator field_changes = obj_arr_changes.keys();
            while (field_changes.hasNext()) {
                String key_change = field_changes.next().toString();
                obj_arr_registro.put(key_change, obj_arr_changes.get(key_change));
            }//from w  w  w . j a v  a  2  s. co m

            arr_registro.put(idx_arr_registro, obj_arr_registro);
            registro.put(key, arr_registro);

            js_obj.put(this.nom_coleccion, js_array.put(idx_registro, registro));
            retorno = true;
        }
    }

    this.src_archivo = js_obj.toString(4);
    this.saveFile();
    return retorno;
}

From source file:config.Manejador.java

public boolean delete(JSONObject criteria) throws JSONException, IOException {
    boolean retorno = false;

    JSONObject js_obj = new JSONObject(this.src_archivo);
    JSONArray js_array = (JSONArray) js_obj.get(this.nom_coleccion);

    JSONObject busqueda = this.Select(criteria);

    if (!busqueda.equals(this.dont_exists)) {
        System.out.println(busqueda.toString(4));

        int indice = busqueda.getInt("idx");
        System.out.println(indice);

        js_array.remove(indice);//from w w  w.jav  a2  s  . c  o m
        js_obj.put(this.nom_coleccion, js_array);

        retorno = true;

        this.src_archivo = js_obj.toString(4);
        this.saveFile();
    }

    return retorno;
}

From source file:config.Manejador.java

public boolean deleteIntoArray(JSONObject criteria, JSONObject target) throws JSONException, IOException {
    boolean retorno = false;

    JSONObject js_obj = new JSONObject(this.src_archivo);
    JSONArray js_array = (JSONArray) js_obj.get(this.nom_coleccion);

    System.out.println(criteria.toString(4));

    if (criteria.has("idx")) {
        int idx_registro = criteria.getInt("idx");
        int idx_arr_obj = 0;

        JSONObject registro = js_array.getJSONObject(idx_registro);

        JSONArray arr_registro, arr_criteria;
        JSONObject obj_arr_criteria;/* ww w .  ja  v  a  2  s .  com*/

        Iterator it_target = target.keys();
        if (it_target.hasNext()) {
            String key = it_target.next().toString();

            arr_registro = registro.getJSONArray(key);
            arr_criteria = criteria.getJSONArray(key);

            obj_arr_criteria = arr_criteria.getJSONObject(0);

            idx_arr_obj = obj_arr_criteria.getInt("idx");

            arr_registro.remove(idx_arr_obj);
            registro.put(key, arr_registro);

            js_array.put(idx_registro, registro);
            js_obj.put(this.nom_coleccion, js_array);
            retorno = true;

            this.src_archivo = js_obj.toString(4);
            this.saveFile();
        }
    }

    return retorno;
}

From source file:com.dwdesign.tweetings.util.Utils.java

public static Bundle parseArguments(final String string) {
    final Bundle bundle = new Bundle();
    if (string != null) {
        try {//from   ww  w  .j  a  va  2s.co m
            final JSONObject json = new JSONObject(string);
            final Iterator<?> it = json.keys();
            while (it.hasNext()) {
                final Object key_obj = it.next();
                if (key_obj == null) {
                    continue;
                }
                final String key = key_obj.toString();
                final Object value = json.get(key);
                if (value instanceof Boolean) {
                    bundle.putBoolean(key, json.getBoolean(key));
                } else if (value instanceof Integer) {
                    // Simple workaround for account_id
                    if (INTENT_KEY_ACCOUNT_ID.equals(key)) {
                        bundle.putLong(key, json.getLong(key));
                    } else {
                        bundle.putInt(key, json.getInt(key));
                    }
                } else if (value instanceof Long) {
                    bundle.putLong(key, json.getLong(key));
                } else if (value instanceof String) {
                    bundle.putString(key, json.getString(key));
                } else {
                    Log.w(LOGTAG,
                            "Unknown type " + value.getClass().getSimpleName() + " in arguments key " + key);
                }
            }
        } catch (final JSONException e) {
            e.printStackTrace();
        } catch (final ClassCastException e) {
            e.printStackTrace();
        }
    }
    return bundle;
}

From source file:org.collectionspace.chain.csp.persistence.services.GenericStorage.java

/**
 * return data just as the service layer gives it to the App layer
 * no extra columns required//ww w  . ja v  a2  s .c  o  m
 * @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);
        }

        List<JSONObject> tempSons = new ArrayList<JSONObject>();

        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) {
                    tempSons.add(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);
            tempSons.add(convertToJson(out, doc.getDocument(), thisr, "GET", "common", csid));
        }

        if (r.hasMerged()) {
            for (FieldSet f : r.getAllMergedFields()) {
                /*
                 * PAHMA- 469: The above calls to convertToJson called XmlJsonConversion.convertToJson,
                 * which calculated values for merge fields. However, these calculations only looked for
                 * merged values from within one section, so they can produce incorrect results when
                 * merge fields pull values from multiple sections. So, for each merge field, we remove
                 * the previously calculated value, then recalculate the value, looking in all sections.
                 * It may be that the merge field calculation in XmlJsonConversion.convertToJson can
                 * be removed, and the calculation only needs to be done here. However, there are tests
                 * that rely on XmlJsonConversion.convertToJson producing a value for merge fields
                 * (and the value is correct if all merged values come from the same section), so this
                 * is being conservative.
                 */
                out.remove(f.getID());

                for (String fm : f.getAllMerge()) {
                    if (fm != null && r.hasFieldByOperation(fm, "GET")) {
                        String value = null;

                        for (JSONObject tempSon : tempSons) {
                            if (tempSon.has(fm)) {
                                value = tempSon.getString(fm);
                                break;
                            }
                        }

                        if (value != null && !value.equals("")) {
                            out.put(f.getID(), value);
                            break;
                        }
                    }
                }
            }
        }
    } 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());
                }

                //seems to work for media blob
                //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);
                                rout.put("_subrecordcsid", result);//add in csid so I can do update with a modicum of confidence
                                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;
}

From source file:org.collectionspace.chain.csp.persistence.services.GenericStorage.java

/**
 * update the item//w  ww . ja  v a 2s .  c om
 * @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) {//JSONObject
                        //do we have a csid
                        //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 {//JSONArray Repeat
                        //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
                                        String thiscsid = lookupCsid(cache, filepaths, serviceurl, thisShortID); // See if we can find a matching short ID in the current list of items
                                        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();
                        deleteJSON(root, creds, cache, key, savePath, sr); // will fail if this record is a term having active references -i.e., one or more non-deleted records reference it.
                    }

                    //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);
                    }
                }
            }
        }
        //if(status==404)
        //   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);
    }
}

From source file:org.collectionspace.chain.csp.persistence.services.GenericStorage.java

/** 
 * needs some tests.. just copied from ConfiguredVocabStorage
 * @param root//  w  w w  . j a  va 2s .  c o m
 * @param creds
 * @param cache
 * @param myr
 * @param jsonObject
 * @param savePrefix
 * @return
 * @throws ExistException
 * @throws UnimplementedException
 * @throws UnderlyingStorageException
 */
public String subautocreateJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache,
        Record myr, JSONObject jsonObject, String savePrefix)
        throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {

        ReturnedURL url = null;
        Document doc = null;
        //used by userroles and permroles as they have complex urls
        //XXX I would hope this might be removed if userroles etc ever get improved to be more like the rest
        if (myr.hasPrimaryField()) {
            //XXX test if works: need to delete first before create/update
            //   deleteJSON(root,creds,cache,filePath);

            for (String section : myr.getServicesRecordPathKeys()) {
                doc = XmlJsonConversion.convertToXml(myr, jsonObject, section, "POST");
                String path = myr.getServicesURL();
                path = path.replace("*", getSubCsid(jsonObject, myr.getPrimaryField()));

                deleteJSON(root, creds, cache, path);
                url = conn.getURL(RequestMethod.POST, path, doc, creds, cache);
            }
        } else {
            url = autoCreateSub(creds, cache, jsonObject, doc, savePrefix, myr);
        }

        // create related sub records?
        for (FieldSet allfs : myr.getAllSubRecords("POST")) {
            Record sr = allfs.usesRecordId();
            if (sr.isType("authority")) {
            } else {
                String savePath = url.getURL() + "/" + sr.getServicesURL();
                if (jsonObject.has(sr.getID())) {
                    Object subdata = jsonObject.get(sr.getID());

                    if (subdata instanceof JSONArray) {
                        JSONArray subarray = (JSONArray) subdata;

                        for (int i = 0; i < subarray.length(); i++) {
                            JSONObject subrecord = subarray.getJSONObject(i);
                            subautocreateJSON(root, creds, cache, sr, subrecord, savePath);
                        }

                    } else if (subdata instanceof JSONObject) {
                        JSONObject subrecord = (JSONObject) subdata;
                        subautocreateJSON(root, creds, cache, sr, subrecord, savePath);
                    }
                }
            }
        }

        return url.getURLTail();
    } 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);
    }
}

From source file:org.collectionspace.chain.csp.persistence.services.GenericStorage.java

/**
 * Convert the JSON from the UI Layer into XML for the Service layer while using the XML structure from cspace-config.xml
 * Send the XML through to the Service Layer to store it in the database
 * The Service Layer returns a url to the object we just stored.
 * @param {ContextualisedStorage} root //w  w  w .j av  a  2 s  .  com
 * @param {CSPRequestCredentials} creds
 * @param {CSPRequestCache} cache
 * @param {String} filePath part of the path to the Service URL (containing the type of object)
 * @param {JSONObject} jsonObject The JSON string coming in from the UI Layer, containing the object to be stored
 * @return {String} csid The id of the object in the database
 */
@Override
public String autocreateJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache,
        String filePath, JSONObject jsonObject, JSONObject restrictions)
        throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {
        ReturnedURL url = null;
        Document doc = null;
        //used by userroles and permroles as they have complex urls
        if (r.hasPrimaryField()) {
            //XXX test if works: need to delete first before create/update
            //   deleteJSON(root,creds,cache,filePath);

            for (String section : r.getServicesRecordPathKeys()) {
                doc = XmlJsonConversion.convertToXml(r, jsonObject, section, "POST");
                String path = r.getServicesURL();
                path = path.replace("*", getSubCsid(jsonObject, r.getPrimaryField()));
                String restrictedPath = getRestrictedPath(path, restrictions, null);

                deleteJSON(root, creds, cache, restrictedPath);
                url = conn.getURL(RequestMethod.POST, restrictedPath, doc, creds, cache);
            }
        } else {
            String restrictedPath = getRestrictedPath(r.getServicesURL(), restrictions, null);
            url = autoCreateSub(creds, cache, jsonObject, doc, restrictedPath, r); // REM - We need a way to send query params (restrictions) on POST and UPDATE 
        }

        // create related sub records?
        //I am developing this.. it might not work...
        for (FieldSet fs : r.getAllSubRecords("POST")) {
            Record sr = fs.usesRecordId();
            //sr.getID()
            if (sr.isType("authority")) {
                //need to use code from configuredVocabStorage
            } else {
                String savePath = url.getURL() + "/" + sr.getServicesURL();
                if (fs instanceof Field) {//get the fields form inline XXX untested - might not work...
                    JSONObject subdata = new JSONObject();
                    //loop thr jsonObject and find the fields I need
                    for (FieldSet subfs : sr.getAllFieldTopLevel("POST")) {
                        String key = subfs.getID();
                        if (jsonObject.has(key)) {
                            subdata.put(key, jsonObject.get(key));
                        }
                    }
                    subautocreateJSON(root, creds, cache, sr, subdata, savePath);
                } else if (fs instanceof Group) {//JSONObject
                    if (jsonObject.has(fs.getID())) {
                        Object subdata = jsonObject.get(fs.getID());
                        if (subdata instanceof JSONObject) {
                            JSONObject subrecord = (JSONObject) subdata;
                            subautocreateJSON(root, creds, cache, sr, subrecord, savePath);
                        }
                    }
                } else {//JSONArray
                    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);
                                subautocreateJSON(root, creds, cache, sr, subrecord, savePath);
                            }

                        }
                    }
                }
            }
        }
        return url.getURLTail();
    } catch (ConnectionException e) {
        String msg = e.getMessage();
        if (e.getStatus() == 403) { //permissions error
            msg += " permissions error";
        }
        throw new UnderlyingStorageException(msg, e.getStatus(), e.getUrl(), e);
    } catch (UnderlyingStorageException e) {
        throw e; // REM - CSPACE-5632: Need to catch and rethrow this exception type to prevent throwing an "UnimplementedException" exception below.
    } catch (Exception e) {
        throw new UnimplementedException("JSONException", e);
    }
}