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:com.mi.xserv.Xserv.java

private void send(final JSONObject json) {
    if (!isConnected())
        return;//from w  ww.ja va  2 s.  c o  m

    int op = 0;
    String topic = "";
    try {
        op = json.getInt("op");
        topic = json.getString("topic");
    } catch (JSONException ignored) {
    }

    if (op == OP_SUBSCRIBE && isPrivateTopic(topic)) {
        JSONObject auth = null;
        try {
            auth = json.getJSONObject("auth");
        } catch (JSONException ignored) {
        }

        if (auth != null) {
            String protocol = "";
            String port = PORT;
            if (isSecure) {
                protocol = "s";
                port = TLS_PORT;
            }

            String endpoint = String.format(DEFAULT_AUTH_URL, protocol, HOST, port);
            try {
                endpoint = auth.getString("endpoint");
            } catch (JSONException ignored) {
            }

            JSONObject params = null;
            try {
                params = auth.getJSONObject("params");
            } catch (JSONException ignored) {
            }

            String user = "";

            // params
            if (params != null) {
                try {
                    user = params.getString("user");
                } catch (JSONException ignored) {
                }

                try {
                    params.put("socket_id", getSocketId());
                    params.put("topic", topic);
                } catch (JSONException ignored) {
                }

                endpoint += "?" + urlEncodedJSON(params);
            }

            AsyncHttpRequest request = new AsyncHttpRequest(Uri.parse(endpoint), "GET");

            // add custom headers
            try {
                JSONObject headers = auth.getJSONObject("headers");
                Iterator<?> keys = headers.keys();
                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    request.setHeader(key, (String) headers.get(key));
                }
            } catch (JSONException ignored) {
            }
            request.setHeader("X-Xserv-AppId", mAppId);

            final String userStatic = user;

            AsyncHttpClient as = AsyncHttpClient.getDefaultInstance();
            as.executeJSONObject(request, new AsyncHttpClient.JSONObjectCallback() {
                @Override
                public void onCompleted(Exception e, AsyncHttpResponse source, JSONObject result) {
                    if (e == null) {
                        json.remove("auth");

                        try {
                            json.put("arg1", userStatic);
                            json.put("arg2", result.getString("data"));
                            json.put("arg3", result.getString("sign"));
                        } catch (JSONException ignored) {
                        }

                        wsSend(json);
                    } else {
                        json.remove("auth");

                        wsSend(json);
                    }
                }
            });
        } else {
            wsSend(json);
        }
    } else {
        wsSend(json);
    }
}

From source file:dentex.youtube.downloader.utils.Json.java

public static void removeEntryFromJsonFile(Context context, String id) {
    String previousJson = Json.readJsonDashboardFile(context);

    JSONObject mO = null;
    try {/*w  ww .  ja va 2  s . c o m*/
        Utils.logger("v", "Removing ID " + id, DEBUG_TAG);
        mO = new JSONObject(previousJson);
        mO.remove(id);
    } catch (JSONException e1) {
        Log.e(DEBUG_TAG, "JSONException @ addEntryToJsonFile");
    }

    String jsonString = null;
    try {
        jsonString = mO.toString(4);

        // write back JSON file
        Utils.logger("v", "-> " + jsonString, DEBUG_TAG);
        Utils.writeToFile(YTD.JSON_FILE, jsonString);
    } catch (JSONException e1) {
        Log.e(DEBUG_TAG, "JSONException @ removeEntryFromJsonFile");
    } catch (NullPointerException e1) {
        Log.e(DEBUG_TAG, "NPE @ removeEntryFromJsonFile");
    }
}

From source file:org.chromium.ChromeUsb.java

private void listInterfaces(CordovaArgs args, JSONObject params, final CallbackContext callbackContext)
        throws JSONException, UsbError {
    ConnectedDevice dev = getDevice(params);
    JSONArray jsonInterfaces = new JSONArray();
    int interfaceCount = dev.getInterfaceCount();
    for (int i = 0; i < interfaceCount; i++) {
        JSONArray jsonEndpoints = new JSONArray();
        int endpointCount = dev.getEndpointCount(i);
        for (int j = 0; j < endpointCount; j++) {
            JSONObject jsonEp = new JSONObject();
            dev.describeEndpoint(i, j, jsonEp);
            jsonEp.put("address", i << ENDPOINT_IF_SHIFT | j);
            if (!jsonEp.getString("type").startsWith("i")) {
                // Only interrupt and isochronous endpoints have pollingInterval.
                jsonEp.remove("pollingInterval");
            }//from   w ww . ja  va2  s.  co  m
            jsonEp.put("extra_data", new JSONObject());
            jsonEndpoints.put(jsonEp);
        }
        JSONObject jsonIf = new JSONObject();
        dev.describeInterface(i, jsonIf);
        jsonIf.put("interfaceNumber", i);
        jsonIf.put("extra_data", new JSONObject());
        jsonIf.put("endpoints", jsonEndpoints);
        jsonInterfaces.put(jsonIf);
    }
    callbackContext.success(jsonInterfaces);
}

From source file:com.zotoh.core.util.JSONUte.java

/**
 * @param j/* ww w  .j a  v a  2s .  c  om*/
 * @param fld
 * @return
 * @throws JSONException
 */
public static JSONArray getAndSetArray(JSONObject j, String fld) throws JSONException {
    JSONArray r = null;
    Object o;

    if (j != null && fld != null) {
        o = j.opt(fld);
        if (o instanceof JSONArray) {
            r = (JSONArray) o;
        } else if (o != null) {
            j.remove(fld);
        }

        if (r == null) {
            r = new JSONArray();
            j.put(fld, r);
        }
    }

    return r;
}

From source file:com.zotoh.core.util.JSONUte.java

/**
 * @param j//ww w . jav  a  2s  .co m
 * @param fld
 * @return
 * @throws JSONException
 */
public static JSONObject getAndSetObject(JSONObject j, String fld) throws JSONException {
    JSONObject r = null;
    Object o;

    if (j != null && fld != null) {
        o = j.opt(fld);
        if (o instanceof JSONObject) {
            r = (JSONObject) o;
        } else if (o != null) {
            j.remove(fld);
        }

        if (r == null) {
            r = new JSONObject();
            j.put(fld, r);
        }
    }

    return r;
}

From source file:com.rapid.actions.Database.java

@Override
public String getJavaScript(RapidRequest rapidRequest, Application application, Page page, Control control,
        JSONObject jsonDetails) throws Exception {

    String js = "";

    if (_query != null) {

        // get the rapid servlet
        RapidHttpServlet rapidServlet = rapidRequest.getRapidServlet();

        // get the sequence for this action requests so long-running early ones don't overwrite fast later ones (defined in databaseaction.xml)
        js += "var sequence = getDatabaseActionSequence('" + getId() + "');\n";

        // open the js function to get the input data
        js += "var data = getDatabaseActionInputData(" + _query.getMultiRow() + ", ";

        // get the inputs
        js += getInputsJavaScript(rapidServlet.getServletContext(), application, page, _query);

        // close the js function to get the input data
        js += ");\n";

        // drop in the query variable used to collect the inputs, and hold the sequence
        js += "var query = { data: data, sequence: sequence };\n";

        // look for any _childDatabaseActions
        if (_childDatabaseActions != null) {
            // if there are some
            if (_childDatabaseActions.size() > 0) {
                // add a collection into the parent
                js += "  query.childQueries = [];\n";
                // count them
                int i = 1;
                // loop them
                for (Database childDatabaseAction : _childDatabaseActions) {
                    // get the childQuery
                    Query childQuery = childDatabaseAction.getQuery();
                    // open function to get input data
                    js += "var childData" + i + " = getDatabaseActionInputData(" + childQuery.getMultiRow()
                            + ", ";
                    // add inputs
                    js += getInputsJavaScript(rapidServlet.getServletContext(), application, page, childQuery);
                    // close the function
                    js += ");\n";
                    // create object
                    js += "var childQuery" + i + " = { data: childData" + i + ", index: " + (i - 1) + " };\n";
                    // add to query
                    js += "query.childQueries.push(childQuery" + i + ");\n";
                    // increment the counter
                    i++;/*from  www . ja  v  a2s . c  om*/
                }
            }
        }

        // control can be null when the action is called from the page load
        String controlParam = "";
        if (control != null)
            controlParam = "&c=" + control.getId();

        // get the outputs
        ArrayList<Parameter> outputs = _query.getOutputs();

        // instantiate the jsonDetails if required
        if (jsonDetails == null)
            jsonDetails = new JSONObject();
        // look for a working page in the jsonDetails
        String workingPage = jsonDetails.optString("workingPage", null);
        // look for an offline page in the jsonDetails
        String offlinePage = jsonDetails.optString("offlinePage", null);

        // get the js to hide the loading (if applicable)
        if (_showLoading)
            js += getLoadingJS(page, outputs, true);

        // stringify the query
        js += "query = JSON.stringify(query);\n";

        // open the ajax call
        js += "$.ajax({ url : '~?a=" + application.getId() + "&v=" + application.getVersion() + "&p="
                + page.getId() + controlParam + "&act=" + getId()
                + "', type: 'POST', contentType: 'application/json', dataType: 'json',\n";
        js += "  data: query,\n";
        js += "  error: function(server, status, message) {\n";

        // if there is a working page
        if (workingPage != null) {
            // remove any working page dialogue 
            js += "    $('#" + workingPage + "dialogue').remove();\n";
            // remove any working page dialogue cover
            js += "    $('#" + workingPage + "cover').remove();\n";
            // remove the working page so as not to affect actions further down the tree
        }

        // hide the loading javascript (if applicable)
        if (_showLoading)
            js += "      " + getLoadingJS(page, outputs, false);

        // this avoids doing the errors if the page is unloading or the back button was pressed
        js += "    if (server.readyState > 0) {\n";

        // retain if error actions
        boolean errorActions = false;

        // prepare a default error hander we'll show if no error actions, or pass to child actions for them to use
        String defaultErrorHandler = "alert('Error with database action : ' + server.responseText||message);";
        // if we have an offline page
        if (offlinePage != null) {
            // update defaultErrorHandler to navigate to offline page
            defaultErrorHandler = "if (Action_navigate && typeof _rapidmobile != 'undefined' && !_rapidmobile.isOnline()) {\n          Action_navigate('~?a="
                    + application.getId() + "&v=" + application.getVersion() + "&p=" + offlinePage
                    + "&action=dialogue',true,'" + getId() + "');\n        } else {\n          "
                    + defaultErrorHandler + "\n        }";
            // remove the offline page so we don't interfere with actions down the three
            jsonDetails.remove("offlinePage");
        }

        // add any error actions
        if (_errorActions != null) {
            // count the actions
            int i = 0;
            // loop the actions
            for (Action action : _errorActions) {
                // retain that we have custom error actions
                errorActions = true;
                // if this is the last error action add in the default error handler
                if (i == _errorActions.size() - 1)
                    jsonDetails.put("defaultErrorHandler", defaultErrorHandler);
                // add the js
                js += "       " + action.getJavaScript(rapidRequest, application, page, control, jsonDetails)
                        .trim().replace("\n", "\n       ") + "\n";
                // if this is the last error action and the default error handler is still present, remove it so it isn't sent down the success path
                if (i == _errorActions.size() - 1 && jsonDetails.optString("defaultErrorHandler", null) != null)
                    jsonDetails.remove("defaultErrorHandler");
                // increase the count
                i++;
            }
        }
        // add default error handler if none in collection
        if (!errorActions)
            js += "        " + defaultErrorHandler + "\n";

        // close unloading check
        js += "    }\n";

        // close error actions
        js += "  },\n";

        // open success function
        js += "  success: function(data) {\n";

        // hide the loading javascript (if applicable)
        if (_showLoading)
            js += "  " + getLoadingJS(page, outputs, false);

        // open if data check
        js += "    if (data) {\n";

        // check there are outputs
        if (outputs != null) {
            // the outputs array we're going to make
            String jsOutputs = "";
            // loop the output parameters
            for (int i = 0; i < outputs.size(); i++) {
                // get the parameter
                Parameter output = outputs.get(i);
                // get the control the data is going into
                Control outputControl = page.getControl(output.getItemId());
                // try the application if still null
                if (outputControl == null)
                    outputControl = application.getControl(rapidServlet.getServletContext(),
                            output.getItemId());
                // check we got one
                if (outputControl != null) {
                    // get any mappings we may have
                    String details = outputControl.getDetailsJavaScript(application, page);
                    // set to empty string or clean up
                    if (details == null) {
                        details = "";
                    } else {
                        details = ", details: " + outputControl.getId() + "details";
                    }
                    // append the javascript outputs
                    jsOutputs += "{id: '" + outputControl.getId() + "', type: '" + outputControl.getType()
                            + "', field: '" + output.getField() + "'" + details + "}";
                    // add a comma if not the last
                    if (i < outputs.size() - 1)
                        jsOutputs += ",";
                }
            }
            js += "     var outputs = [" + jsOutputs + "];\n";
            // send them them and the data to the database action            
            js += "     Action_database(ev,'" + getId() + "', data, outputs);\n";
        }

        // add any sucess actions
        if (_successActions != null) {
            for (Action action : _successActions) {
                js += "     " + action.getJavaScript(rapidRequest, application, page, control, jsonDetails)
                        .trim().replace("\n", "\n       ") + "\n";
            }
        }

        // if there is a working page (from the details)
        if (workingPage != null) {
            // remove any working page dialogue 
            js += "    $('#" + workingPage + "dialogue').remove();\n";
            // remove any working page dialogue cover
            js += "    $('#" + workingPage + "cover').remove();\n";
            // remove the working page so as not to affect actions further down the tree
            jsonDetails.remove("workingPage");
        }

        // close if data check
        js += "    }\n";
        // close success function
        js += "  }\n";

        // close ajax call
        js += "});";
    }

    // return what we built         
    return js;
}

From source file:de.jackwhite20.japs.client.sub.impl.SubscriberImpl.java

@SuppressWarnings("unchecked")
@Override/*from   ww w .  j ava  2 s .c  o  m*/
public void received(JSONObject jsonObject) {

    String channel = ((String) jsonObject.remove("ch"));

    if (channel == null || channel.isEmpty()) {
        return;
    }

    HandlerInfo handlerInfo = handlers.get(channel);

    if (handlerInfo != null) {
        if (handlerInfo.classType() == ClassType.JSON) {
            handlerInfo.messageHandler().onMessage(channel, jsonObject);
        } else {
            handlerInfo.messageHandler().onMessage(channel,
                    gson.fromJson(jsonObject.toString(), handlerInfo.clazz()));
        }
    } else {
        MultiHandlerInfo multiHandlerInfo = multiHandlers.get(channel);

        if (multiHandlerInfo != null) {
            //noinspection Convert2streamapi
            for (MultiHandlerInfo.Entry entry : multiHandlerInfo.entries()) {
                if (!jsonObject.isNull(entry.key().value())) {
                    if (jsonObject.get(entry.key().value()).equals(entry.value().value())) {
                        // Remove matched key value pair
                        jsonObject.remove(entry.key().value());

                        if (entry.classType() == ClassType.JSON) {
                            try {
                                // Invoke the matching method
                                entry.method().invoke(multiHandlerInfo.object(), jsonObject);
                            } catch (IllegalAccessException | InvocationTargetException e) {
                                e.printStackTrace();
                            }
                        } else {
                            try {
                                // Deserialize with gson
                                entry.method().invoke(multiHandlerInfo.object(),
                                        gson.fromJson(jsonObject.toString(), entry.paramClass()));
                            } catch (IllegalAccessException | InvocationTargetException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }
}

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

public void sendChangesToCozy() {
    List<Contact> unSyncedContacts = Contact.getAllUnsynced();
    int i = 0;/*  ww  w.  j a  v a  2 s.c  o m*/
    for (Contact contact : unSyncedContacts) {
        URL urlO = null;
        try {
            JSONObject jsonObject = contact.toJsonObject();

            System.out.println(jsonObject.toString());

            mBuilder.setProgress(unSyncedContacts.size(), i + 1, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault()
                    .post(new ContactSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_contacts_ongoing_sync)));
            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");
                contact.setRemoteId(result);
                contact.save();
            }

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

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

From source file:com.jennifer.ui.chart.ChartBuilder.java

private String createGradient(JSONObject parsedColor, String hashKey) {

    JSONObject hash = bobject("hash");

    if (hash.has(hashKey)) {
        return url(hash.getString(hashKey));
    }/*from w ww. j  a va 2s. c  o m*/

    String id = StringUtil.createId("gradient");

    parsedColor.put("id", id);

    String type = parsedColor.getString("type");
    Transform g = el(type + "Gradient", parsedColor);

    JSONArray stops = (JSONArray) parsedColor.getJSONArray("stops");
    for (int i = 0, len = stops.length(); i < len; i++) {
        g.append(el("stop", (JSONObject) stops.getJSONObject(i)));
    }
    parsedColor.remove("stops");

    this.defs.append(g);

    if (hashKey != null) {
        hash.put(hashKey, id);
    }

    return url(id);
}

From source file:com.jennifer.ui.chart.ChartBuilder.java

private void setGridAxis(JSONObject obj, JSONObject drawObject) {
    obj.remove("x");
    obj.remove("y");
    obj.remove("c");

    if (!builderoptions.has("scales")) {
        return;// w  ww .  j a  v  a  2s. co m
    }

    JSONObject scales = builderoptions.getJSONObject("scales");

    if (scales.has("x") || scales.has("x1")) {
        if (drawObject.has("x1") && drawObject.getInt("x1") > -1) {
            obj.put("x", scales.getJSONArray("x1").get(drawObject.getInt("x1")));
        } else {
            obj.put("x", scales.getJSONArray("x").get(drawObject.optInt("x", 0)));
        }
    }

    if (scales.has("y") || scales.has("y1")) {
        if (drawObject.has("y1") && drawObject.getInt("y1") > -1) {
            obj.put("y", scales.getJSONArray("y1").get(drawObject.getInt("y1")));
        } else {
            obj.put("y", scales.getJSONArray("y").get(drawObject.optInt("y", 0)));
        }
    }

    if (scales.has("c")) {
        obj.put("c", scales.getJSONArray("c").get(drawObject.optInt("c", 0)));
    }

}