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:org.collectionspace.chain.csp.persistence.services.relation.TestRelationsThroughWebapp.java

@Test
public void testRelationsMissingOneWay() throws Exception {
    // First create a couple of cataloging
    ServletTester jetty = tester.setupJetty();
    HttpTester out = tester.POSTData("/cataloging/",
            tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);

    String id1 = out.getHeader("Location");
    out = tester.POSTData("/cataloging/", tester.makeSimpleRequest(tester.getResourceString("obj3.json")),
            jetty);/* ww w . j a v  a 2 s  .  c  om*/
    String id2 = out.getHeader("Location");
    out = tester.POSTData("/cataloging/", tester.makeSimpleRequest(tester.getResourceString("obj3.json")),
            jetty);
    String id3 = out.getHeader("Location");
    String[] path1 = id1.split("/");
    String[] path3 = id3.split("/");
    JSONObject data = createRelation(path3[1], path3[2], "affects", path1[1], path1[2], false);
    data.remove("one-way");
    out = tester.POSTData("/relationships", data, jetty);
    // Get csid
    JSONObject datacs = new JSONObject(out.getContent());
    String csid1 = datacs.getString("csid");
    // Just heck they have length 1 (other stuff will be tested by main
    // test)
    out = tester.GETData(id3, jetty);
    JSONObject data3 = new JSONObject(out.getContent());
    JSONArray rel3 = data3.getJSONObject("relations").getJSONArray("cataloging");
    assertNotNull(rel3);
    assertEquals(1, rel3.length());
    out = tester.GETData(id1, jetty);
    JSONObject data1 = new JSONObject(out.getContent());
    JSONArray rel1 = data1.getJSONObject("relations").getJSONArray("cataloging");
    assertNotNull(rel1);
    assertEquals(1, rel1.length());

    // clean up after
    tester.DELETEData("/relationships/" + csid1, jetty);
    tester.DELETEData(id1, jetty);
    tester.DELETEData(id2, jetty);
    tester.DELETEData(id3, jetty);
    tester.stopJetty(jetty);
}

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

private JSONObject correctPassword(JSONObject in) throws JSONException, UnderlyingStorageException {
    try {//from   ww w .  j  a  v a  2s.  c  om
        if (in.has("password")) {
            String password = in.getString("password");
            in.remove("password");
            password = new String(Base64.encodeBase64(password.getBytes("UTF-8")), "UTF-8");
            while (password.endsWith("\n") || password.endsWith("\r"))
                password = password.substring(0, password.length() - 1);
            in.put("password", password);
        }
        return in;
    } catch (UnsupportedEncodingException e) {
        throw new UnderlyingStorageException("Error generating Base 64", e);
    }
}

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

private JSONObject correctScreenName(JSONObject in) throws JSONException, UnderlyingStorageException {
    if (in.has("userName") && !in.has("screenName")) {
        String username = in.getString("userName");
        in.remove("userName");
        in.put("screenName", username);
    }//from  w  ww  . java  2s . co m
    return in;
}

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

private JSONObject correctUserId(JSONObject in) throws JSONException, UnderlyingStorageException {
    if (!in.has("userId")) {
        String userId = in.getString("email");
        in.remove("userId");
        in.put("userId", userId);
    }//from  w ww . j  av  a 2s .  c o m
    return in;
}

From source file:com.xebia.incubator.xebium.RemoteWebDriverSupplier.java

public RemoteWebDriverSupplier(String json) {
    JSONObject jsonObject;
    try {/*from  www . j  a v  a  2  s .co  m*/
        jsonObject = new JSONObject(json);
    } catch (JSONException e) {
        throw new RuntimeException("Unable to interpret browser information", e);
    }

    try {
        remote = jsonObject.getString(REMOTE);
        jsonObject.remove(REMOTE);
        capabilities = jsonObjectToMap(jsonObject);
    } catch (JSONException e) {
        throw new RuntimeException("Unable to fetch required fields from json string", e);
    }
}

From source file:eu.codeplumbers.cosi.api.tasks.SyncDocumentTask.java

@Override
protected String doInBackground(JSONObject... jsonObjects) {
    for (int i = 0; i < jsonObjects.length; i++) {
        JSONObject jsonObject = jsonObjects[i];

        URL urlO = null;/*from  w w w.jav  a  2  s  .  co m*/
        try {
            publishProgress("Syncing " + jsonObject.getString("docType") + ":", i + "",
                    jsonObjects.length + "");
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(url);
                requestMethod = "POST";
            } else {
                urlO = new URL(url + 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");
            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");

                if (jsonObject.get("docType").equals("Sms")) {
                    Sms sms = Sms.load(Sms.class, objectId);
                    sms.setRemoteId(result);
                    sms.save();
                }

                if (jsonObject.get("docType").equals("Note")) {
                    Note note = Note.load(Note.class, objectId);
                    note.setRemoteId(result);
                    note.save();
                }

                if (jsonObject.get("docType").equals("Call")) {
                    Call call = Call.load(Call.class, objectId);
                    call.setRemoteId(result);
                    call.save();
                }

                if (jsonObject.get("docType").equals("Expense")) {
                    Expense expense = Expense.load(Expense.class, objectId);
                    expense.setRemoteId(result);
                    expense.save();
                }
            }

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

        } catch (MalformedURLException e) {
            result = "error";
            e.printStackTrace();
            errorMessage = e.getLocalizedMessage();
        } catch (ProtocolException e) {
            result = "error";
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (IOException e) {
            result = "error";
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (JSONException e) {
            result = "error";
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        }
    }

    return result;
}

From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffWriter.java

private void writeMMHeaderAndSummaryMD(JSONObject summaryMD) throws IOException {
    if (summaryMD.has("Comment")) {
        summaryMD.remove("Comment");
    }/*  w  ww.  j av  a2  s. co m*/
    String summaryMDString = summaryMD.toString();
    int mdLength = summaryMDString.length();
    ByteBuffer buffer = ByteBuffer.allocate(40).order(BYTE_ORDER);
    if (BYTE_ORDER.equals(ByteOrder.BIG_ENDIAN)) {
        buffer.asCharBuffer().put(0, (char) 0x4d4d);
    } else {
        buffer.asCharBuffer().put(0, (char) 0x4949);
    }
    buffer.asCharBuffer().put(1, (char) 42);
    buffer.putInt(4, 40 + mdLength);
    //8 bytes for file header +
    //8 bytes for index map offset header and offset +
    //8 bytes for display settings offset header and display settings offset
    //8 bytes for comments offset header and comments offset
    //8 bytes for summaryMD header  summary md length + 
    //1 byte for each character of summary md     
    buffer.putInt(32, SUMMARY_MD_HEADER);
    buffer.putInt(36, mdLength);
    ByteBuffer[] buffers = new ByteBuffer[2];
    buffers[0] = buffer;
    buffers[1] = ByteBuffer.wrap(getBytesFromString(summaryMDString));
    fileChannel_.write(buffers);
    filePosition_ += buffer.position() + mdLength;
}

From source file:synapticloop.b2.response.BaseB2Response.java

/**
 * Read and remove String with key from JSON object
 * //from   w ww  .ja va  2 s.c  om
 * @param response The JSON object to read from
 * @param key the key to read as a string and remove
 * 
 * @return the read key (or null if it doesn't exist)
 */
protected String readString(JSONObject response, String key) {
    final Object value = response.remove(key);
    if (null == value || JSONObject.NULL == value) {
        getLogger().warn("No field for key {}", key);
        return null;
    }
    return value.toString();
}

From source file:synapticloop.b2.response.BaseB2Response.java

/**
 * Read and remove JSONObject with key from JSON object
 * /*from www .  ja  va 2  s .c o m*/
 * @param response The JSON object to read from
 * @param key the key to read as a JSONObject and remove
 * 
 * @return the read key (or null if it doesn't exist)
 */
protected JSONObject readObject(JSONObject response, String key) {
    final Object value = response.remove(key);
    if (null == value || JSONObject.NULL == value) {
        getLogger().warn("No field for key {}", key);
        return null;
    }
    return value instanceof JSONObject ? (JSONObject) value : null;
}

From source file:config.Manejador.java

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

    JSONArray js_array_obj;/* ww w  .ja  v a2s. co m*/
    JSONArray js_array_busqueda;

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

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

    int idx_busqueda = 0;
    boolean fin = false;

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

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

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

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

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

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

                    Iterator it_arr_obj = arr_obj.keys();

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

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

                        retorno = objeto;
                        retorno.remove(key_obj);

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

                        fin = true;
                        break;
                    }

                    idx_busqueda++;
                }

                if (fin)
                    break;
            }
        }
    }

    return retorno;
}