Example usage for org.json JSONArray put

List of usage examples for org.json JSONArray put

Introduction

In this page you can find the example usage for org.json JSONArray put.

Prototype

public JSONArray put(Object value) 

Source Link

Document

Append an object value.

Usage

From source file:com.quantcast.measurement.service.QCDataUploader.java

String synchronousUploadEvents(Collection<QCEvent> events) {
    if (events == null || events.isEmpty())
        return null;

    String uploadId = QCUtility.generateUniqueId();

    JSONObject upload = new JSONObject();
    try {//from   www  . j  a v a  2s. com
        upload.put(QC_UPLOAD_ID_KEY, uploadId);
        upload.put(QC_QCV_KEY, QCUtility.API_VERSION);
        upload.put(QCEvent.QC_APIKEY_KEY, QCMeasurement.INSTANCE.getApiKey());
        upload.put(QCEvent.QC_NETWORKCODE_KEY, QCMeasurement.INSTANCE.getNetworkCode());
        upload.put(QCEvent.QC_DEVICEID_KEY, QCMeasurement.INSTANCE.getDeviceId());

        JSONArray event = new JSONArray();
        for (QCEvent e : events) {
            event.put(new JSONObject(e.getParameters()));
        }
        upload.put(QC_EVENTS_KEY, event);
    } catch (JSONException e) {
        QCLog.e(TAG, "Error while encoding json.");
        return null;
    }

    int code;
    String url = QCUtility.addScheme(UPLOAD_URL_WITHOUT_SCHEME);
    final DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    defaultHttpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
    final BasicHttpContext localContext = new BasicHttpContext();

    try {
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json");
        StringEntity se = new StringEntity(upload.toString(), HTTP.UTF_8);
        post.setEntity(se);

        HttpParams params = new BasicHttpParams();
        params.setBooleanParameter("http.protocol.expect-continue", false);
        post.setParams(params);

        HttpResponse response = defaultHttpClient.execute(post, localContext);
        code = response.getStatusLine().getStatusCode();
    } catch (Exception e) {
        QCLog.e(TAG, "Could not upload events", e);
        QCMeasurement.INSTANCE.logSDKError("json-upload-failure", e.toString(), null);
        code = HttpStatus.SC_REQUEST_TIMEOUT;
    }

    if (!isSuccessful(code)) {
        uploadId = null;
        QCLog.e(TAG, "Events not sent to server. Response code: " + code);
        QCMeasurement.INSTANCE.logSDKError("json-upload-failure",
                "Bad response from server. Response code: " + code, null);
    }
    return uploadId;
}

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  va 2s.c  om
 * @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

/**
 * get data needed for terms Used block of a record
 * @param creds//from ww  w. j  a va2 s .  c o  m
 * @param cache
 * @param path
 * @return
 * @throws ExistException
 * @throws UnimplementedException
 * @throws UnderlyingStorageException
 * @throws JSONException
 * @throws UnsupportedEncodingException 
 */
public JSONObject refViewRetrieveJSON(ContextualisedStorage storage, CSPRequestCredentials creds,
        CSPRequestCache cache, String path, JSONObject restrictions) throws ExistException,
        UnimplementedException, UnderlyingStorageException, JSONException, UnsupportedEncodingException {
    try {
        JSONObject out = new JSONObject();
        JSONObject pagination = new JSONObject();
        JSONObject listitems = new JSONObject();
        //not all the records need a reference, look in cspace-config.xml for which that don't
        if (r.hasTermsUsed()) {
            path = getRestrictedPath(path, restrictions, "kw", "", false, "");
            if (r.hasSoftDeleteMethod()) {//XXX completely not the right thinsg to do but a good enough hack
                path = softpath(path);
            }
            if (r.hasHierarchyUsed("screen")) {
                path = hierarchicalpath(path);
            }
            ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET, path, null, creds, cache);
            if (all.getStatus() != 200)
                throw new ConnectionException("Bad request during identifier cache map update: status not 200",
                        all.getStatus(), path);
            Document list = all.getDocument();

            //assumes consistency in service layer payloads - possible could configure this rather than hard code?
            List<Node> nodes = list.selectNodes("authority-ref-list/*");
            for (Node node : nodes) {
                if (node.getName().equals("authority-ref-item")) {
                    if (!(node instanceof Element))
                        continue;
                    if (((Element) node).hasContent()) {

                        String key = ((Element) node).selectSingleNode("sourceField").getText();
                        String refname = ((Element) node).selectSingleNode("refName").getText();
                        String itemDisplayName = ((Element) node).selectSingleNode("itemDisplayName").getText();
                        String uri = "";
                        if (null != ((Element) node).selectSingleNode("uri")) { //seems to be missing sometimes
                            uri = ((Element) node).selectSingleNode("uri").getText();
                        }

                        String fieldName = key;
                        if (key.split(":").length > 1) {
                            fieldName = key.split(":")[1];
                        }

                        Field fieldinstance = null;
                        if (r.getFieldFullList(fieldName) instanceof Repeat) {
                            Repeat rp = (Repeat) r.getFieldFullList(fieldName);
                            for (FieldSet a : rp.getChildren("GET")) {
                                if (a instanceof Field && a.hasAutocompleteInstance()) {
                                    fieldinstance = (Field) a;
                                }
                            }
                        } else {
                            fieldinstance = (Field) r.getFieldFullList(fieldName);
                        }

                        if (fieldinstance != null) {

                            JSONObject data = new JSONObject();
                            data.put("sourceField", key);
                            data.put("itemDisplayName", itemDisplayName);
                            data.put("refname", refname);
                            data.put("uri", uri);
                            //JSONObject data=miniForURI(storage,creds,cache,refname,null,restrictions);
                            /*
                            if(!data.has("refid")){//incase of permissions errors try our best
                               data.put("refid",refname);
                               if(data.has("displayName")){
                                  String itemDisplayName=((Element)node).selectSingleNode("itemDisplayName").getText();
                                  String temp = data.getString("displayName");
                                  data.remove("displayName");
                                  data.put(temp, itemDisplayName);
                               }
                            }
                            */
                            data.put("sourceFieldselector", fieldinstance.getSelector());
                            data.put("sourceFieldName", fieldName);
                            data.put("sourceFieldType", r.getID());
                            if (listitems.has(key)) {
                                JSONArray temp = listitems.getJSONArray(key).put(data);
                                listitems.put(key, temp);
                            } else {
                                JSONArray temp = new JSONArray();
                                temp.put(data);
                                listitems.put(key, temp);
                            }
                        }
                    }

                } else {
                    pagination.put(node.getName(), node.getText());
                }
            }
        }
        out.put("pagination", pagination);
        out.put("listItems", listitems);
        return out;
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Connection problem" + e.getLocalizedMessage(), e.getStatus(),
                e.getUrl(), e);
    }
}

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

/**
 * get data needed for list of objects related to a termUsed
 * @param storage/*www  .j a v  a 2 s.co m*/
 * @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();

    /*
     * Usually, processing of list results utilizes "glean" maps stored as instance variables (view_good, view_map,
     * xxx_view_deurn, view_search_optional, view_merge, and view_useCsid). These instance variables can be
     * considered defaults that work for the most common kinds of list results. The format returned from the refobj
     * services call is non-standard with respect to most list results, so we have to set up a special context to
     * interpret the results the way we need. Swapping out the instance variables is not thread-safe (CSPACE-5988).
     * Instead, the required maps are defined locally to this method, and passed as parameters into the methods
     * that need them, which overrides the use of the corresponding instance variables.
     */

    try {

        Map<String, String> refObj_view_good = new HashMap<String, String>();// map of servicenames of fields to descriptors
        Map<String, String> refObj_view_map = new HashMap<String, String>(); // map of csid to service name of field
        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");

            JSONObject data = getRepeatableListView(storage, creds, cache, path,
                    "authority-ref-doc-list/authority-ref-doc-item", "uri", true, vr, refObj_view_map);//XXX this might be the wrong record to pass to checkf or hard/soft delet listing

            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");
                String filePath = uri; // recs.getJSONObject(i).getString("csid");
                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];
                    //XXX fixCSPACE-2909 would be nice if they gave us the actual field rather than the parent
                    //XXX CSPACE-2586
                    // 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);
    }
}

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

/**
 * update the item//from w w  w.j ava  2 s  .  co  m
 * @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

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();
                }//w  w w  . ja  va  2  s.  c  om
                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);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.spiffyui.mvsb.samples.server.CrayonColorsServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JSONArray fullColorArray;
    String query = request.getParameter("q");

    try {//  www .  j a v a2 s . co m
        int count = 0;
        if (query.equals(m_lastQuery)) {
            fullColorArray = m_lastResults;
            count = m_lastResults.length();
        } else {
            m_lastQuery = query;

            fullColorArray = new JSONArray();
            for (String[] colorCode : COLOR_CODES) {
                String colorName = colorCode[0];
                String lowerColor = colorName.toLowerCase();
                int has = lowerColor.indexOf(query.toLowerCase());

                if (!query.isEmpty() && (query.equals("*") || has >= 0)) {
                    JSONObject color = new JSONObject();
                    color.put("DisplayName", colorName);
                    color.put("Value", colorCode[1]);
                    color.put("Description", colorCode[2]);
                    color.put("RGB", colorCode[3]);
                    fullColorArray.put(color);
                    count++;
                }
            }
            m_lastResults = fullColorArray;
        }

        //get the partial array to be returned
        int indexFrom = 0;
        if (request.getParameter("indexFrom") != null) {
            indexFrom = Integer.parseInt(request.getParameter("indexFrom"));
        }

        int indexTo = fullColorArray.length() - 1;
        if (request.getParameter("indexTo") != null) {
            indexTo = Integer.parseInt(request.getParameter("indexTo"));
        }

        JSONArray partial = new JSONArray();
        if (fullColorArray.length() > 0) {
            int end = count - 1 > indexTo ? indexTo : count - 1;
            for (int i = indexFrom; i <= end; i++) {
                partial.put(fullColorArray.get(i));
            }
        }
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        JSONObject obj = new JSONObject();
        obj.put("TotalSize", count);
        obj.put("Options", partial);
        out.println(obj.toString());
    } catch (JSONException e) {
        /*
         This should never happen
         */
        LOGGER.throwing(getClass().getName(), "doGet", e);
    }
}

From source file:de.dakror.virtualhub.client.dialog.ChooseCatalogDialog.java

public static void show(ClientFrame frame, final JSONArray data) {
    final JDialog dialog = new JDialog(frame, "Katalog whlen", true);
    dialog.setSize(400, 300);/*from   w w  w .j  a v a 2  s  . c o m*/
    dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    dialog.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            Client.currentClient.disconnect();
            System.exit(0);
        }
    });

    JPanel contentPane = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
    dialog.setContentPane(contentPane);
    DefaultListModel dlm = new DefaultListModel();
    for (int i = 0; i < data.length(); i++) {
        try {
            dlm.addElement(data.getJSONObject(i).getString("name"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    final JList catalogs = new JList(dlm);
    catalogs.setDragEnabled(false);
    catalogs.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    JScrollPane jsp = new JScrollPane(catalogs, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    jsp.setPreferredSize(new Dimension(396, 200));
    contentPane.add(jsp);

    JPanel mods = new JPanel(new GridLayout(1, 2));
    mods.setPreferredSize(new Dimension(50, 22));
    mods.add(new JButton(new AbstractAction("+") {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            String name = JOptionPane.showInputDialog(dialog,
                    "Bitte geben Sie den Namen des neuen Katalogs ein.", "Katalog hinzufgen",
                    JOptionPane.PLAIN_MESSAGE);
            if (name != null && name.length() > 0) {
                DefaultListModel dlm = (DefaultListModel) catalogs.getModel();
                for (int i = 0; i < dlm.getSize(); i++) {
                    if (dlm.get(i).toString().equals(name)) {
                        JOptionPane.showMessageDialog(dialog,
                                "Es existert bereits ein Katalog mit diesem Namen!",
                                "Katalog bereits vorhanden!", JOptionPane.ERROR_MESSAGE);
                        actionPerformed(e);
                        return;
                    }
                }

                try {
                    dlm.addElement(name);
                    JSONObject o = new JSONObject();
                    o.put("name", name);
                    o.put("sources", new JSONArray());
                    o.put("tags", new JSONArray());
                    data.put(o);
                    Client.currentClient.sendPacket(new Packet0Catalogs(data));
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
    }));
    mods.add(new JButton(new AbstractAction("-") {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            if (catalogs.getSelectedIndex() != -1) {
                if (JOptionPane.showConfirmDialog(dialog,
                        "Sind Sie sicher, dass Sie diesen\r\nKatalog unwiderruflich lschen wollen?",
                        "Katalog lschen", JOptionPane.YES_NO_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
                    DefaultListModel dlm = (DefaultListModel) catalogs.getModel();
                    data.remove(catalogs.getSelectedIndex());
                    dlm.remove(catalogs.getSelectedIndex());
                    try {
                        Client.currentClient.sendPacket(new Packet0Catalogs(data));
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }));

    contentPane.add(mods);

    JLabel l = new JLabel("");
    l.setPreferredSize(new Dimension(396, 14));
    contentPane.add(l);

    JSeparator sep = new JSeparator(JSeparator.HORIZONTAL);
    sep.setPreferredSize(new Dimension(396, 10));
    contentPane.add(sep);

    JPanel buttons = new JPanel(new GridLayout(1, 2));
    buttons.setPreferredSize(new Dimension(396, 22));
    buttons.add(new JButton(new AbstractAction("Abbrechen") {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            Client.currentClient.disconnect();
            System.exit(0);
        }
    }));
    buttons.add(new JButton(new AbstractAction("Katalog whlen") {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            if (catalogs.getSelectedIndex() != -1) {
                try {
                    Client.currentClient
                            .setCatalog(new Catalog(data.getJSONObject(catalogs.getSelectedIndex())));
                    Client.currentClient.frame.setTitle("- " + Client.currentClient.getCatalog().getName());
                    dialog.dispose();
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }));

    dialog.add(buttons);

    dialog.setLocationRelativeTo(frame);
    dialog.setResizable(false);
    dialog.setVisible(true);
}

From source file:edu.stanford.junction.director.JAVADirector.java

@Override
public void onMessageReceived(MessageHeader header, JSONObject message) {
    try {//from  w  ww  .  j  a v a  2s.c om
        if (message.has("action")) {
            String action = message.getString("action");
            if ("list".equals(action)) {
                JSONArray procs = new JSONArray();
                for (int i = mActivities.size() - 1; i >= 0; i--) {
                    Activity activity = mActivities.get(i);
                    try {
                        activity.process.exitValue();
                        // If we get this far, the process is terminated.
                        System.out.println("exit value " + activity.process.exitValue());
                        mActivities.remove(i);
                    } catch (Exception e) {
                        // No exit value means its still running.
                        JSONObject obj = new JSONObject();
                        obj.put("activity", activity.uri.toString());
                        procs.put(obj);
                    }
                }
                JSONObject msg = new JSONObject();
                msg.put("activities", procs);
                header.getReplyTarget().sendMessage(msg);
            }

            else if ("info".equals(action)) {
                // return Junction version, platform(s), and "hints" (headless, bigscreen, etc)
                // also a nickname.

                // maybe other known directors? owner info?

                // HINTS:
                // headless ~ server
                // bigscreen ~ TV or monitor attached
                // mobile ~ phone
                // nouser ~ no direct user input (bigscreen / headless)
                // keyboard? mouse?
            }

            else if ("cast".equals(action)) {
                String activityString = message.getString("activity");
                URI activityURI = new URI(activityString);

                // TODO: clean this up.
                ActivityScript script = mMaker.getActivityScript(activityURI);
                int p = activityString.indexOf("role=");
                if (p < 0) {
                    System.out.println("Invitation does not specify a role.");
                    return;
                }

                String role = activityString.substring(p + 5);
                if (role.contains("&")) {
                    int q = role.indexOf("&");
                    role = role.substring(0, q);
                }

                JSONObject spec = script.getRoleSpec(role);
                JSONObject platforms = spec.getJSONObject("platforms");
                if (platforms.has("java")) {
                    JSONObject javaplat = platforms.getJSONObject("java");
                    if (javaplat.has("jar")) {
                        URL jarURL = new URL(javaplat.getString("jar"));
                        Process proc = launchJAR(jarURL, activityURI);

                        if (proc != null) {
                            mActivities.add(new Activity(activityURI, proc));

                            InputStream is = proc.getInputStream();
                            BufferedReader br = new BufferedReader(new InputStreamReader(is));
                            String line;

                            while ((line = br.readLine()) != null) {
                                System.out.println(line);
                            }
                        }
                    } else {
                        System.out.println("Warning: JAVA platform specified but no JAR found.");
                    }
                }

                else if (platforms.has("web")) {
                    // TODO: make sure this director isn't 'headless'
                    // (add these properties)
                    JSONObject webplat = platforms.getJSONObject("web");
                    String webURL = webplat.getString("url");

                    if (webURL.contains("?")) {
                        webURL = webURL + "&";
                    } else {
                        webURL = webURL + "?";
                    }
                    webURL += "jxinvite=" + URLEncoder.encode(activityString, "UTF-8");
                    Process proc = BrowserControl.openUrl(webURL);
                    if (proc != null) {
                        mActivities.add(new Activity(activityURI, proc));
                    }
                }

                else if (message.has("serviceName")) {
                    String className = message.getString("serviceName");
                    launchService(activityURI, script, className);
                } else {
                    System.out.println("No action taken for " + message);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.moez.QKSMS.model.MediaModelFactory.java

/**
 * This method is meant to identify the part in the given PduBody that corresponds to the given
 * src string.//  w w w . j ava2s  .c  o  m
 *
 * Essentially, a SMIL MMS is formatted as follows:
 *
 * 1. A smil/application part, which contains XML-like formatting for images, text, audio,
 * slideshows, videos, etc.
 * 2. One or more parts that correspond to one of the elements that was mentioned in the
 * formatting above.
 *
 * In the smil/application part, elements are identified by a "src" attribute in an XML-like
 * element. The challenge of this method lies in the fact that sometimes, the src string isn't
 * located at all in the part that it is meant to identify.
 *
 * We employ several methods of pairing src strings up to parts, using certain patterns we've
 * seen in failed MMS messages. These are described in this method.
 * TODO TODO TODO: Create a testing suite for this!
 */
private static PduPart findPart(final Context context, PduBody pb, String src, ArrayList<String> srcs) {

    PduPart result = null;

    if (src != null) {
        src = unescapeXML(src);

        // Sometimes, src takes the form of "cid:[NUMBER]".
        if (contentIdSrc(src)) {

            // Extract the content ID, and try finding the part using that.
            result = pb.getPartByContentId("<" + src.substring("cid:".length()) + ">");

            if (result == null) {
                // Another thing that can happen is that there is a slideshow of images, each with
                // "cid:[NUMBER]" src, but the parts aren't labelled with the content ID. If
                // this is the case, then we just return the ith image part, where i is the position
                // of src if all the srcs are sorted in ascending order as content IDs. srcs may
                // include duplicates; we remove those and then identify i when the list is free from
                // duplicates.
                //
                // i.e., for srcs = [ "cid:755", "cid:755", "cid:756", "cid:757", "cid:758" ],
                // the i of "cid:755" is 0; for "cid:756" is 1, etc.

                // First check that all the src strings are content IDs.
                boolean allContentIDs = true;
                for (String _src : srcs) {
                    if (!contentIdSrc(_src)) {
                        allContentIDs = false;
                        break;
                    }
                }

                if (allContentIDs) {
                    // Now, build a list of long IDs, sort them, and remove the duplicates.
                    ArrayList<Long> cids = new ArrayList<>();
                    for (String _src : srcs) {
                        cids.add(getContentId(_src));
                    }
                    Collections.sort(cids);

                    int removed = 0;
                    long previous = -1;
                    for (int i = 0; i < cids.size() - removed; i++) {
                        long cid = cids.get(i);

                        if (cid == previous) {
                            cids.remove(i);
                            removed++;
                        } else {
                            previous = cid;
                        }
                    }

                    // Find the i such that getContentId(src) == cids[i]
                    long cid = getContentId(src);
                    int i = cids.indexOf(cid);

                    // Finally, since the SMIL formatted part will come first, we expect to see
                    // 1 + cids.size() parts, and the right part for this particular cid will be
                    // 1 + i.
                    if (1 + i < pb.getPartsNum()) {
                        result = pb.getPart(i + 1);
                    }
                }
            }

        } else if (textSrc(src)) {
            // This is just a text src, so look for the PduPart that is has the "text/plain"
            // content type.
            for (int i = 0; i < pb.getPartsNum(); i++) {
                PduPart part = pb.getPart(i);
                String contentType = byteArrayToString(part.getContentType());
                if ("text/plain".equals(contentType)) {
                    result = part;
                    break;
                }
            }
        }

        // Try a few more things in case the previous processing didn't work correctly:

        // Search by name
        if (result == null) {
            result = pb.getPartByName(src);
        }

        // Search by filename
        if (result == null) {
            result = pb.getPartByFileName(src);
        }

        // Search by content location
        if (result == null) {
            result = pb.getPartByContentLocation(src);
        }

        // Try treating the src string as a content ID, and searching by content ID.
        if (result == null) {
            result = pb.getPartByContentId("<" + src + ">");
        }

        // TODO:
        // four remaining cases currently in Firebase:
        // 1. src: "image:[NUMBER]" (broken formatting)
        // 2. src: "[NUMBER]" (broken formatting)
        // 3. src: "[name].vcf" (we don't support x-vcard)
        // 3. src: "Current Location.loc.vcf" (we don't support x-vcard)

    }

    if (result != null) {
        return result;
    }

    if (pb.getPartsNum() > 0) {

        final JSONArray array = new JSONArray();

        for (int i = 0; i < pb.getPartsNum(); i++) {

            JSONObject object = new JSONObject();

            try {
                object.put("part_number", i);
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                object.put("location", i);
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                object.put("charset", pb.getPart(i).getCharset());
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                object.put("content_disposition", byteArrayToString(pb.getPart(i).getContentDisposition()));
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                object.put("content_id", byteArrayToString(pb.getPart(i).getContentId()));
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                object.put("content_location", byteArrayToString(pb.getPart(i).getContentLocation()));
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                object.put("content_transfer_encoding",
                        byteArrayToString(pb.getPart(i).getContentTransferEncoding()));
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                object.put("content_type", byteArrayToString(pb.getPart(i).getContentType()));
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                object.put("data", byteArrayToString(pb.getPart(i).getData()));
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                object.put("data_uri", pb.getPart(i).getDataUri());
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                object.put("file_name", byteArrayToString(pb.getPart(i).getFilename()));
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                object.put("name", byteArrayToString(pb.getPart(i).getName()));
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (pb.getPart(i).generateLocation() != null) {
                Log.d(TAG, "Location: " + pb.getPart(i).generateLocation());
                if (pb.getPart(i).generateLocation().contains(src)) {
                    return pb.getPart(i);
                }
            }

            array.put(object);
        }
    }

    throw new IllegalArgumentException("No part found for the model.");
}