Example usage for org.json JSONObject toString

List of usage examples for org.json JSONObject toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONObject.

Usage

From source file:com.tonikorin.cordova.plugin.LocationProvider.LocationService.java

private void handleLocationQuery(JSONObject messageIn, String time) throws JSONException, IOException {
    Log.d(TAG, "Handle location query...");
    String ownName = config.optString("member", "");
    JSONObject teams = config.optJSONObject("teams");
    String teamName;/*  w w w .  ja v a2s.c  o m*/
    String teamPassword;
    String teamHost;
    JSONObject team = null;
    if (teams != null)
        team = teams.optJSONObject(messageIn.optString("teamId"));
    if (team != null) {
        teamName = team.optString("name", "");
        teamPassword = team.optString("password", "");
        ownName = team.optString("member", ownName);
        teamHost = team.optString("host", "");
    } else
        return; // => URI hanging in PostServer
    String msgType = messageIn.optString("messageType", LOCATE);
    // Create Messaging Server interface
    String messageUrl = config.optString("messageUrl", "").replace("{host}", teamHost);
    MessageServer msgServer = new MessageServer(ownName, teamName, teamPassword, messageUrl);
    if (messageIn.optString("memberName").equals(ownName)) {
        updateLocateHistory(messageIn, true, msgType, time);
        msgServer.post(RESERVED);
        SystemClock.sleep(5000);// 5 sec delay
        String pushUrl = config.optString("pushUrl", "").replace("{host}", teamHost);
        msgServer.updatePushToken(ownName, teamName, config.optString("token", ""), pushUrl);
        return;
    }
    // Read extra team configuration (e.g. icon and schedule)
    TeamConfig cTeam = new TeamConfig(config, teamName);
    // Store details about location query
    updateLocateHistory(messageIn, cTeam.isBlocked(), msgType, time);
    if (cTeam.isBlocked())
        msgServer.addBlockedField();
    msgServer.post(ALIVE);
    if (cTeam.isBlocked() || CHAT.equals(msgType))
        return; // skip giving your location
    try {
        //Log.d(TAG, "myContext: " + myContext.getPackageName());
        new MyLocation(myContext, myLocationResult, messageIn.optInt("accuracy", 50),
                config.optInt("timeout", 60)).start();
        JSONObject location = myLocationResult.getJsonLocation();
        //Log.d(TAG, "Background position accuracy: " + location.optInt("accuracy"));
        if (cTeam.getIcon() != null)
            msgServer.addIconField(cTeam.getIcon());
        msgServer.post(POSITION, location.toString());
    } catch (Exception e) {
        Log.e(TAG, "LocationProvider exception ", e);
        msgServer.post(FAILURE, e.getMessage());
    }
    Log.d(TAG, "Handle location query...completed!");
}

From source file:com.tonikorin.cordova.plugin.LocationProvider.LocationService.java

private void updateLocateHistory(JSONObject messageIn, boolean blocked, String msgType, String time)
        throws JSONException { // Read current history
    SharedPreferences sp = myContext.getSharedPreferences(LocationService.PREFS_NAME, Context.MODE_PRIVATE);
    String historyJsonStr = sp.getString(LocationService.HISTORY_NAME, "{}");
    JSONObject history = new JSONObject(historyJsonStr);
    if (CHAT.equals(msgType)) { // CHAT history, save hole message
        JSONArray chatMessages = history.optJSONArray("chatMessages");
        if (chatMessages == null)
            chatMessages = new JSONArray();
        //Log.d(TAG, "CHAT history TIME: " + time);
        messageIn.put("time", Long.parseLong(time));
        chatMessages.put(messageIn.toString());
        if (chatMessages.length() > 100)
            chatMessages.remove(0); // store only last 100 chat messages
        history.put("chatMessages", chatMessages);
    } else {// Current LOCATE
        String member = messageIn.optString("memberName", "");
        if (blocked)
            member = "\u2717 " + member;
        JSONObject updateStatus = new JSONObject();
        updateStatus.put("member", member);
        updateStatus.put("team", messageIn.optString("teamId", ""));
        updateStatus.put("date", getDateAndTimeString(System.currentTimeMillis()));
        updateStatus.put("target", messageIn.optString("target", ""));
        history.put("updateStatus", updateStatus);
        // History LOCATE lines...
        JSONArray historyLines = history.optJSONArray("lines");
        if (historyLines == null)
            historyLines = new JSONArray();
        String target;/*  w  w w  .  j av  a 2 s.c om*/
        if (updateStatus.getString("target").equals(""))
            target = updateStatus.optString("team");
        else
            target = updateStatus.optString("target");
        String historyLine = updateStatus.getString("member") + " (" + target + ") "
                + updateStatus.getString("date") + "\n";
        historyLines.put(historyLine);
        if (historyLines.length() > 200)
            historyLines.remove(0); // store only last 200 locate queries
        history.put("lines", historyLines);
    }
    // Save new history
    SharedPreferences.Editor editor = sp.edit();
    editor.putString(LocationService.HISTORY_NAME, history.toString());
    editor.commit();
    //Log.d(TAG, "history:" + history.toString());
}

From source file:org.jenkinsci.plugins.testrail.TestRailClient.java

public Case addCase(Testcase caseToAdd, int sectionId) throws IOException, TestRailException {
    JSONObject payload = new JSONObject().put("title", caseToAdd.getName());
    if (!StringUtils.isEmpty(caseToAdd.getRefs())) {
        payload.put("refs", caseToAdd.getRefs());
    }/* w w w .jav  a2  s. c om*/

    String body = httpPost("index.php?/api/v2/add_case/" + sectionId, payload.toString()).getBody();
    Case c = createCaseFromJson(new JSONObject(body));
    return c;
}

From source file:com.fsa.en.dron.activity.MainActivity.java

private void fetchImages() {

    pDialog.setMessage("Levantando vuelo...");
    pDialog.setCanceledOnTouchOutside(false);
    pDialog.show();//from   w  w w  . j  a v a 2s.c  o m

    JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, endpoint, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    pDialog.hide();
                    JSONArray array = null;

                    try {
                        JSONObject user = response.getJSONObject("photos");
                        array = user.getJSONArray("photo");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    images.clear();
                    for (int i = 0; i < array.length(); i++) {
                        try {
                            JSONObject object = array.getJSONObject(i);
                            Image image = new Image();

                            image.setSmall("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setMedium("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setLarge("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setUrl("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setId(object.getString("id"));
                            Log.i("uuu", "" + "https://farm2.staticflickr.com/" + object.getString("server")
                                    + "/" + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            images.add(image);

                        } catch (JSONException e) {
                            Log.e(TAG, "Json parsing error: " + e.getMessage());
                        }
                    }

                    mAdapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "Error: " + error.getMessage());
                    pDialog.hide();
                }
            });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(req);
}

From source file:de.decoit.visa.http.ajax.handlers.CreateVSAHandler.java

@Override
public void handle(HttpExchange he) throws IOException {
    log.info(he.getRequestURI().toString());

    // Get the URI of the request and extract the query string from it
    QueryString queryParameters = new QueryString(he.getRequestURI());

    // Create StringBuilder for the response
    String response = null;/* w ww  . ja  va2s  .  c  om*/

    // Check if the query parameters are valid for this handler
    if (this.checkQueryParameters(queryParameters)) {
        try {
            HashMap<String, String> connTargets = new HashMap<>();
            HashMap<String, String> connVLANs = new HashMap<>();

            boolean connParamsPresent = true;

            Document tpl = TEBackend.RDF_MANAGER
                    .getVSATemplate(Integer.parseInt(queryParameters.get("tplid").get()));

            // Verify that all connections are present in the query
            // parameters
            // Get all elements of type CONNECTION and iterate over the list
            NodeList nl = tpl.getElementsByTagName("CONNECTION");
            for (int i = 0; i < nl.getLength(); i++) {
                Node n = nl.item(i);

                // Check if the node is an Element. Should be the case, just
                // for security reasons
                if (n.getNodeType() == Node.ELEMENT_NODE) {
                    // Cast the node to Element to access the attributes
                    Element e = (Element) n;

                    String id = e.getAttribute("id");

                    if (!queryParameters.containsKey(id)) {
                        // A connection is missing, set the response to the
                        // missing arguments message and break the loop
                        connParamsPresent = false;

                        JSONObject rv = new JSONObject();
                        rv.put("status", AJAXServer.AJAX_ERROR_MISSING_ARGS);
                        response = rv.toString();

                        break;
                    } else {
                        connTargets.put(id, queryParameters.get(id).get());

                        StringBuilder sbVLAN = new StringBuilder(id);
                        sbVLAN.append("_vlan");

                        if (queryParameters.containsKey(sbVLAN.toString())) {
                            connVLANs.put(id, queryParameters.get(sbVLAN.toString()).get());
                        }
                    }
                }
            }

            if (connParamsPresent) {
                TEBackend.RDF_MANAGER.importRDFTemplate(Integer.parseInt(queryParameters.get("tplid").get()),
                        queryParameters.get("name").get(), connTargets, connVLANs);

                // Return success response
                JSONObject rv = new JSONObject();
                rv.put("status", AJAXServer.AJAX_SUCCESS);
                rv.put("topology", TEBackend.TOPOLOGY_STORAGE.genTopologyJSON());
                response = rv.toString();
            }
        } catch (Throwable ex) {
            TEBackend.logException(ex, log);

            try {
                // Synchronize the topology with the RDF model to
                // resolve
                // any errors caused by the caught exception
                TEBackend.RDF_MANAGER.syncTopologyToRDF();

                JSONObject rv = new JSONObject();
                rv.put("status", AJAXServer.AJAX_ERROR_EXCEPTION);
                rv.put("type", ex.getClass().getSimpleName());
                rv.put("message", ex.getMessage());
                rv.put("topology", TEBackend.TOPOLOGY_STORAGE.genTopologyJSON());
                response = rv.toString();
            } catch (Throwable e) {
                // Exception during synchronization, the model may have
                // been
                // corrupted so the whole backend was cleared
                JSONObject rv = new JSONObject();
                try {
                    rv.put("status", AJAXServer.AJAX_ERROR_EXCEPTION_UNRESOLVED);
                    rv.put("topology", TEBackend.TOPOLOGY_STORAGE.genTopologyJSON());
                } catch (JSONException exc) {
                    /* Ignore */
                }

                response = rv.toString();
            }
        }
    } else {
        // Missing or malformed query string, set response to error code
        JSONObject rv = new JSONObject();
        try {
            // Missing or malformed query string, set response to error code
            rv.put("status", AJAXServer.AJAX_ERROR_MISSING_ARGS);
        } catch (JSONException exc) {
            /* Ignore */
        }

        response = rv.toString();
    }

    // Send the response
    sendResponse(he, response);
}

From source file:com.github.akinaru.roboticbuttonpusher.bluetooth.BluetoothCustomManager.java

private void dispatchBtDevices(BluetoothDevice device, int rssi, final byte[] scanRecord) {

    if (scanningList.containsKey(device.getAddress())) {

    } else {//  ww  w  .  jav  a2 s . com

        Log.v(TAG, "found a new Bluetooth device : " + device.getName() + " : " + device.getAddress());

        scanningList.put(device.getAddress(), device);

        try {
            JSONObject object = new JSONObject();
            object.put(JsonConstants.BT_ADDRESS, device.getAddress());
            object.put(JsonConstants.BT_DEVICE_NAME, device.getName());
            object.put(JsonConstants.BT_ADVERTISING_INTERVAL, -1);

            ArrayList<String> deviceInfo = new ArrayList<>();
            deviceInfo.add(object.toString());

            broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_DISCOVERED, deviceInfo);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

long addToOutgoing(SQLiteDatabase db, String appId, String to, String type, JSONObject json) {
    if (DBG) {/*from   www .  j  a va  2 s .  c  o m*/
        Log.d(TAG, "Adding to outgoing; to: " + to + ", json: " + json);
    }
    try {
        long timestamp = new Date().getTime();
        prepareForSending(json, type, timestamp, appId);
        ContentValues cv = new ContentValues();
        cv.put(DbObject._ID, getNextId());
        cv.put(DbObject.APP_ID, appId);
        cv.put(DbObject.FEED_NAME, "friend");
        cv.put(DbObject.CONTACT_ID, Contact.MY_ID);
        cv.put(DbObject.DESTINATION, to);
        cv.put(DbObject.TYPE, type);
        cv.put(DbObject.JSON, json.toString());
        cv.put(DbObject.SEQUENCE_ID, 0);
        cv.put(DbObject.TIMESTAMP, timestamp);
        if (cv.getAsString(DbObject.JSON).length() > SIZE_LIMIT)
            throw new RuntimeException("Messasge size is too large for sending");
        return db.insertOrThrow(DbObject.TABLE, null, cv);
    } catch (Exception e) {
        // TODO, too spammy
        //e.printStackTrace(System.err);
        return -1;
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

/**
 * Inserts an object into the database and flags it to be sent by
 * the transport layer.// w w  w. ja v  a2  s.c o  m
 */
long addToFeed(String appId, String feedName, ContentValues values) {
    try {
        JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
        String type = values.getAsString(DbObject.TYPE);

        long nextSeqId = getFeedMaxSequenceId(Contact.MY_ID, feedName) + 1;
        long timestamp = new Date().getTime();
        json.put(DbObjects.TYPE, type);
        json.put(DbObjects.FEED_NAME, feedName);
        json.put(DbObjects.SEQUENCE_ID, nextSeqId);
        json.put(DbObjects.TIMESTAMP, timestamp);
        json.put(DbObjects.APP_ID, appId);

        // Explicit column referencing avoids database errors.
        ContentValues cv = new ContentValues();
        cv.put(DbObject._ID, getNextId());
        cv.put(DbObject.APP_ID, appId);
        cv.put(DbObject.FEED_NAME, feedName);
        cv.put(DbObject.CONTACT_ID, Contact.MY_ID);
        cv.put(DbObject.TYPE, type);
        cv.put(DbObject.SEQUENCE_ID, nextSeqId);
        cv.put(DbObject.JSON, json.toString());
        cv.put(DbObject.TIMESTAMP, timestamp);
        cv.put(DbObject.LAST_MODIFIED_TIMESTAMP, new Date().getTime());

        if (values.containsKey(DbObject.RAW)) {
            cv.put(DbObject.RAW, values.getAsByteArray(DbObject.RAW));
        }
        if (values.containsKey(DbObject.KEY_INT)) {
            cv.put(DbObject.KEY_INT, values.getAsInteger(DbObject.KEY_INT));
        }
        if (json.has(DbObject.CHILD_FEED_NAME)) {
            cv.put(DbObject.CHILD_FEED_NAME, json.optString(DbObject.CHILD_FEED_NAME));
        }
        if (cv.getAsString(DbObject.JSON).length() > SIZE_LIMIT)
            throw new RuntimeException("Messasge size is too large for sending");
        Long objId = getWritableDatabase().insertOrThrow(DbObject.TABLE, null, cv);

        if (json.has(DbObjects.TARGET_HASH)) {
            long hashA = json.optLong(DbObjects.TARGET_HASH);
            long idA = objIdForHash(hashA);
            String relation;
            if (json.has(DbObjects.TARGET_RELATION)) {
                relation = json.optString(DbObjects.TARGET_RELATION);
            } else {
                relation = DbRelation.RELATION_PARENT;
            }
            if (idA == -1) {
                Log.e(TAG, "No objId found for hash " + hashA);
            } else {
                addObjRelation(idA, objId, relation);
            }
        }

        Uri objUri = DbObject.uriForObj(objId);
        mContext.getContentResolver().registerContentObserver(objUri, false,
                new ModificationObserver(mContext, objId));
        return objId;
    } catch (Exception e) {
        // TODO, too spammy
        //e.printStackTrace(System.err);
        return -1;
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

long addObjectByJson(long contactId, JSONObject json, long hash, byte[] raw, Integer intKey) {
    try {//www.ja v  a2 s  .c  o  m
        long objId = getNextId();
        long seqId = json.optLong(DbObjects.SEQUENCE_ID);
        long timestamp = json.getLong(DbObjects.TIMESTAMP);
        String feedName = json.getString(DbObjects.FEED_NAME);
        String type = json.getString(DbObjects.TYPE);
        String appId = json.getString(DbObjects.APP_ID);
        ContentValues cv = new ContentValues();
        cv.put(DbObject._ID, objId);
        cv.put(DbObject.APP_ID, appId);
        cv.put(DbObject.FEED_NAME, feedName);
        cv.put(DbObject.CONTACT_ID, contactId);
        cv.put(DbObject.TYPE, type);
        cv.put(DbObject.SEQUENCE_ID, seqId);
        cv.put(DbObject.JSON, json.toString());
        cv.put(DbObject.TIMESTAMP, timestamp);
        cv.put(DbObject.HASH, hash);
        cv.put(DbObject.SENT, 1);

        cv.put(DbObject.LAST_MODIFIED_TIMESTAMP, new Date().getTime());
        if (raw != null) {
            cv.put(DbObject.RAW, raw);
        }
        if (intKey != null) {
            cv.put(DbObject.KEY_INT, intKey);
        }

        // TODO: Deprecated!!
        if (json.has(DbObject.CHILD_FEED_NAME)) {
            cv.put(DbObject.CHILD_FEED_NAME, json.optString(DbObject.CHILD_FEED_NAME));
        }
        if (cv.getAsString(DbObject.JSON).length() > SIZE_LIMIT)
            throw new RuntimeException("Messasge size is too large for sending");
        long newObjId = getWritableDatabase().insertOrThrow(DbObject.TABLE, null, cv);

        String notifyName = feedName;
        if (json.has(DbObjects.TARGET_HASH)) {
            long hashA = json.optLong(DbObjects.TARGET_HASH);
            long idA = objIdForHash(hashA);
            notifyName = feedName + ":" + hashA;
            String relation;
            if (json.has(DbObjects.TARGET_RELATION)) {
                relation = json.optString(DbObjects.TARGET_RELATION);
            } else {
                relation = DbRelation.RELATION_PARENT;
            }
            if (idA == -1) {
                Log.e(TAG, "No objId found for hash " + hashA);
            } else {
                addObjRelation(idA, newObjId, relation);
            }
        }

        ContentResolver resolver = mContext.getContentResolver();
        DungBeetleContentProvider.notifyDependencies(this, resolver, notifyName);
        updateObjModification(App.instance().getMusubi().objForId(newObjId));
        return objId;
    } catch (Exception e) {
        if (DBG)
            Log.e(TAG, "Error adding object by json.", e);
        return -1;
    }
}

From source file:edumsg.core.commands.tweet.UnRetweetCommand.java

@Override
public void execute() {
    try {//from www .ja  v  a 2  s .c o  m
        dbConn = PostgresConnection.getDataSource().getConnection();
        dbConn.setAutoCommit(true);
        proc = dbConn.prepareCall("{? = call unretweet(?,?)}");
        proc.setPoolable(true);
        proc.registerOutParameter(1, Types.INTEGER);
        proc.setInt(2, Integer.parseInt(map.get("tweet_id")));
        proc.setString(3, map.get("session_id"));
        proc.execute();

        int retweets = proc.getInt(1);

        MyObjectMapper mapper = new MyObjectMapper();
        JsonNodeFactory nf = JsonNodeFactory.instance;
        ObjectNode root = nf.objectNode();
        root.put("app", map.get("app"));
        root.put("method", map.get("method"));
        root.put("status", "ok");
        root.put("code", "200");
        root.put("favorites", retweets);
        try {
            CommandsHelp.submit(map.get("app"), mapper.writeValueAsString(root), map.get("correlation_id"),
                    LOGGER);
            String cacheEntry = UserCache.userCache.get("user_tweets:" + map.get("session_id"));
            if (cacheEntry != null) {
                JSONObject cacheEntryJson = new JSONObject(cacheEntry);
                cacheEntryJson.put("cacheStatus", "invalid");
                //                    System.out.println("invalidated");
                UserCache.userCache.set("user_tweets:" + map.get("session_id"), cacheEntryJson.toString());
            }
            String cacheEntry1 = UserCache.userCache.get("timeline:" + map.get("session_id"));
            if (cacheEntry1 != null) {
                JSONObject cacheEntryJson = new JSONObject(cacheEntry1);
                cacheEntryJson.put("cacheStatus", "invalid");
                //                    System.out.println("invalidated");
                UserCache.userCache.set("timeline:" + map.get("session_id"), cacheEntryJson.toString());
            }
            String cacheEntry2 = TweetsCache.tweetCache.get("get_earliest_replies:" + map.get("session_id"));
            if (cacheEntry2 != null) {
                JSONObject cacheEntryJson = new JSONObject(cacheEntry2);
                cacheEntryJson.put("cacheStatus", "invalid");
                //                    System.out.println("invalidated");
                TweetsCache.tweetCache.set("get_earliest_replies:" + map.get("session_id"),
                        cacheEntryJson.toString());
            }
            String cacheEntry3 = TweetsCache.tweetCache.get("get_replies:" + map.get("session_id"));
            if (cacheEntry3 != null) {
                JSONObject cacheEntryJson = new JSONObject(cacheEntry3);
                cacheEntryJson.put("cacheStatus", "invalid");
                //                    System.out.println("invalidated");
                TweetsCache.tweetCache.set("get_replies:" + map.get("session_id"), cacheEntryJson.toString());
            }
            String cacheEntry4 = ListCache.listCache.get("get_list_feeds:" + map.get("session_id"));
            if (cacheEntry4 != null) {
                JSONObject cacheEntryJson = new JSONObject(cacheEntry4);
                cacheEntryJson.put("cacheStatus", "invalid");
                //                    System.out.println("invalidated");
                ListCache.listCache.set("get_list_feeds:" + map.get("session_id"), cacheEntryJson.toString());
            }
        } catch (JsonGenerationException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
        } catch (JsonMappingException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
        }
        //            catch (JSONException e) {
        //                e.printStackTrace();
        //            }

    } catch (PSQLException e) {
        CommandsHelp.handleError(map.get("app"), map.get("method"), e.getMessage(), map.get("correlation_id"),
                LOGGER);
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (SQLException e) {
        CommandsHelp.handleError(map.get("app"), map.get("method"), e.getMessage(), map.get("correlation_id"),
                LOGGER);
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } finally {
        PostgresConnection.disconnect(null, proc, dbConn);
    }
}