Example usage for org.json JSONObject remove

List of usage examples for org.json JSONObject remove

Introduction

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

Prototype

public Object remove(String key) 

Source Link

Document

Remove a name and its value, if present.

Usage

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));
        }//from w ww  .  j  a v a2  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: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/*from   w  ww.  java2  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//from  www.  ja  va 2s.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:com.samsung.appengine.web.server.RemindMeServlet.java

@JsonRpcMethod(method = RemindMeProtocol.AlertsSync.METHOD, requires_login = true)
public JSONObject notesSync(final CallContext context) throws JSONException, JsonRpcException {
    // This method should return a list of updated notes since a current
    // date, optionally reconciling/merging a set of a local notes.
    String clientDeviceId = null;
    UserInfo userInfo = getCurrentUserInfo(context);
    Date sinceDate;/*from  www  . j a va  2 s . co  m*/

    try {
        clientDeviceId = context.getParams().optString(RemindMeProtocol.ARG_CLIENT_DEVICE_ID);
        sinceDate = Util
                .parseDateISO8601(context.getParams().getString(RemindMeProtocol.AlertsSync.ARG_SINCE_DATE));
    } catch (ParseException e) {
        throw new JsonRpcException(400, "Invalid since_date.", e);
    } catch (JSONException e) {
        throw new JsonRpcException(400, "Invalid since_date.", e);
    }

    JSONObject responseJson = new JSONObject();
    JSONArray notesJson = new JSONArray();
    Transaction tx = context.getPersistenceManager().currentTransaction();
    Date newSinceDate = new Date();
    try {
        tx.begin();
        List<Alert> localAlerts = new ArrayList<Alert>();
        if (context.getParams().has(RemindMeProtocol.AlertsSync.ARG_LOCAL_ALERTS)) {
            JSONArray localChangesJson = context.getParams()
                    .getJSONArray(RemindMeProtocol.AlertsSync.ARG_LOCAL_ALERTS);
            for (int i = 0; i < localChangesJson.length(); i++) {
                try {
                    JSONObject noteJson = localChangesJson.getJSONObject(i);

                    if (noteJson.has("id")) {
                        Key existingAlertKey = Alert.makeKey(userInfo.getId(), noteJson.get("id").toString());
                        try {
                            Alert existingAlert = (Alert) context.getPersistenceManager()
                                    .getObjectById(Alert.class, existingAlertKey);
                            if (!existingAlert.getOwnerId().equals(userInfo.getId())) {
                                // User doesn't have permission to edit this note. Instead of
                                // throwing an error, just re-create it on the server side.
                                //throw new JsonRpcException(403,
                                //        "You do not have permission to modify this note.");
                                noteJson.remove("id");
                            }
                        } catch (JDOObjectNotFoundException e) {
                            // Alert doesn't exist, instead of throwing an error,
                            // just re-create the note on the server side (unassign its ID).
                            //throw new JsonRpcException(404, "Alert with ID "
                            //        + noteJson.get("id").toString() + " does not exist.");
                            noteJson.remove("id");
                        }
                    }

                    noteJson.put("owner_id", userInfo.getId());
                    Alert localAlert = new Alert(noteJson);
                    localAlerts.add(localAlert);
                } catch (JSONException e) {
                    throw new JsonRpcException(400, "Invalid local note content.", e);
                }
            }
        }

        // Query server-side note changes.
        Query query = context.getPersistenceManager().newQuery(Alert.class);
        query.setFilter("ownerKey == ownerKeyParam && modifiedDate > sinceDate");
        query.setOrdering("modifiedDate desc");
        query.declareParameters(Key.class.getName() + " ownerKeyParam, java.util.Date sinceDate");
        @SuppressWarnings("unchecked")
        List<Alert> alerts = (List<Alert>) query.execute(userInfo.getKey(), sinceDate);

        // Now merge the lists and conflicting objects.
        Reconciler<Alert> reconciler = new Reconciler<Alert>() {
            @Override
            public Alert reconcile(Alert o1, Alert o2) {
                boolean pick1 = o1.getModifiedDate().after(o2.getModifiedDate());

                // Make sure only the chosen version of the note is persisted
                context.getPersistenceManager().makeTransient(pick1 ? o2 : o1);

                return pick1 ? o1 : o2;
            }
        };

        Collection<Alert> reconciledAlerts = reconciler.reconcileLists(alerts, localAlerts);

        for (Alert alert : reconciledAlerts) {
            // Save the note.
            context.getPersistenceManager().makePersistent(alert);

            // Put it in the response output.
            notesJson.put(alert.toJSON());
        }
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
    }

    enqueueDeviceMessage(context.getPersistenceManager(), userInfo, clientDeviceId);

    responseJson.put(RemindMeProtocol.AlertsSync.RET_ALERTS, notesJson);
    responseJson.put(RemindMeProtocol.AlertsSync.RET_NEW_SINCE_DATE, Util.formatDateISO8601(newSinceDate));
    return responseJson;
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VoiceObj.java

@Override
public Pair<JSONObject, byte[]> splitRaw(JSONObject json) {
    byte[] raw = Base64.decode(json.optString(DATA), Base64.DEFAULT);
    json.remove(DATA);
    return new Pair<JSONObject, byte[]>(json, raw);
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VoiceObj.java

@Override
public Pair<JSONObject, byte[]> handleOutgoing(JSONObject json) {
    byte[] bytes = Base64.decode(json.optString(DATA), Base64.DEFAULT);
    json.remove(DATA);
    return new Pair<JSONObject, byte[]>(json, bytes);
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VoiceObj.java

@Override
public Pair<JSONObject, byte[]> handleUnprocessed(Context context, JSONObject msg) {
    byte[] bytes = FastBase64.decode(msg.optString(DATA));
    msg.remove(DATA);
    return new Pair<JSONObject, byte[]>(msg, bytes);
}

From source file:eu.sathra.io.IO.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Object getValue(JSONObject jObj, String param, Class<?> clazz)
        throws ArrayIndexOutOfBoundsException, IllegalArgumentException, Exception {
    try {//from  w  w  w  .  j a va  2 s .c  o m
        if (clazz.equals(String.class)) {
            return jObj.getString(param);
        } else if (clazz.equals(int.class)) {
            return jObj.getInt(param);
        } else if (clazz.equals(long.class)) {
            return jObj.getLong(param);
        } else if (clazz.equals(float.class)) {
            return (float) jObj.getDouble(param);
        } else if (clazz.equals(double.class)) {
            return jObj.getDouble(param);
        } else if (clazz.equals(boolean.class)) {
            return jObj.getBoolean(param);
        } else if (mAdapters.containsKey(clazz)) {
            return mAdapters.get(clazz).load(param, jObj);
        } else if (clazz.isEnum()) {
            return Enum.valueOf((Class<? extends Enum>) clazz, jObj.getString(param));
        } else if (clazz.isArray()) {
            return getValue(jObj.getJSONArray(param), clazz.getComponentType());
        } else {
            return load(jObj.getJSONObject(param), clazz);
        }
    } catch (JSONException e) {
        return null;
    } finally {
        jObj.remove(param);
    }

}

From source file:eu.codeplumbers.cosi.services.CosiSmsService.java

public void sendChangesToCozy() {
    List<Sms> unSyncedSms = Sms.getAllUnsynced();
    int i = 0;/*from   ww  w .  j  a  v  a2s.c  o  m*/
    for (Sms sms : unSyncedSms) {
        URL urlO = null;
        try {
            JSONObject jsonObject = sms.toJsonObject();
            mBuilder.setProgress(unSyncedSms.size(), i, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault()
                    .post(new SmsSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_phone)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                sms.setRemoteId(result);
                sms.save();
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        }
        i++;
    }
}

From source file:com.rathravane.drumlin.examples.accounts.exampleAcctPersistence.java

private void removeFromIndex(String indexName, String keyName) throws DrumlinAccountsException {
    try {/*from   w ww  .  jav  a2  s.c o  m*/
        final JSONObject o = fIndex.getJSONObject(indexName);
        o.remove(keyName);
        fStore.overwrite(fStore.indexToAddress(0), fIndex);
    } catch (JSONException e) {
        throw new DrumlinAccountsException(e);
    } catch (IOException e) {
        throw new DrumlinAccountsException(e);
    }
}