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:edu.mit.media.funf.security.HashUtil.java

private static String oneWayHashAndRSA(Context context, String msg) {
    // Map<String, String> encMsg = new HashMap<String, String>();
    try {/* www .j a va2  s .com*/
        JSONObject jsonEncMsg = new JSONObject();

        jsonEncMsg.put(HashingType.ONE_WAY_HASH.name(), oneWayHashString(msg));
        jsonEncMsg.put(HashingType.RSA_ENC.name(), RSAEncode.encodeStringRSA(context, msg));
        // Log.v(TAG, "oneWayHashAndRSA, jsonEncMsg: " + jsonEncMsg);
        return jsonEncMsg.toString();
    } catch (JSONException e) {
        Log.e(LogUtil.TAG, "oneWayHashAndRSA: json error:", e);
        return "JSON ERROR!";
    }
}

From source file:com.marpies.ane.firebase.auth.utils.FirebaseAuthHelper.java

public void processAuthResponse(@NonNull Task<AuthResult> task, int callbackId) {
    if (task.isSuccessful()) {
        JSONObject response = new JSONObject();
        try {// w ww .  j a  v a 2 s . c om
            response.put("user", getJSONFromUser(task.getResult().getUser()));
            response.put("callbackId", callbackId);
            AIR.dispatchEvent(FirebaseAuthEvent.SIGN_IN_SUCCESS, response.toString());
        } catch (JSONException e) {
            e.printStackTrace();
            AIR.log("User authentication success, but failed to create response");
            dispatchAuthErrorResponse("Failed to create response.", callbackId);
        }
    } else {
        String errorMessage = (task.getException() != null) ? task.getException().getLocalizedMessage()
                : "Unknown error.";
        AIR.log("Error authenticating user: " + errorMessage);
        dispatchAuthErrorResponse(errorMessage, callbackId);
    }
}

From source file:com.marpies.ane.firebase.auth.utils.FirebaseAuthHelper.java

private String getJSONFromUser(FirebaseUser newUser) {
    FirebaseUser user = (newUser == null) ? getUser() : newUser;
    if (user != null) {
        JSONObject json = new JSONObject();
        try {//from  ww  w .j  a v a2  s  . c o  m
            json.put("uid", user.getUid());
            json.put("isAnonymous", user.isAnonymous());
            if (user.getDisplayName() != null) {
                json.put("displayName", user.getDisplayName());
            }
            if (user.getEmail() != null) {
                json.put("email", user.getEmail());
            }
            if (user.getPhotoUrl() != null) {
                json.put("email", user.getPhotoUrl().toString());
            }
            JSONArray providerData = new JSONArray();
            for (UserInfo userInfo : user.getProviderData()) {
                String userInfoJSON = getJSONFromUserInfo(userInfo);
                if (userInfoJSON != null) {
                    providerData.put(userInfoJSON);
                }
            }
            if (providerData.length() > 0) {
                json.put("providerData", providerData);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
    }
    return null;
}

From source file:com.marpies.ane.firebase.auth.utils.FirebaseAuthHelper.java

private String getJSONFromUserInfo(UserInfo userInfo) {
    JSONObject json = new JSONObject();
    try {//www .jav  a 2s. co m
        String providerId = userInfo.getProviderId();
        if (providerId != null) {
            json.put("providerId", providerId);
        }
        String uid = userInfo.getUid();
        if (uid != null) {
            json.put("uid", uid);
        }
        String displayName = userInfo.getDisplayName();
        if (displayName != null) {
            json.put("displayName", displayName);
        }
        String email = userInfo.getEmail();
        if (email != null) {
            json.put("email", email);
        }
        Uri photoURL = userInfo.getPhotoUrl();
        if (photoURL != null) {
            json.put("photoURL", photoURL.toString());
        }
        return json.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java

/**
 * @param response {@link CloseableHttpResponse}
 * @return null if response is invalid. Json as string, if it is a valid response.
 * @throws MLHttpClientException/*from   w  w w .  ja  v a  2 s .  c  om*/
 */
public String getResponseAsString(CloseableHttpResponse response) throws MLHttpClientException {
    if (response == null || response.getEntity() == null) {
        return null;
    }
    String reply = null;
    try {
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));
        String line = bufferedReader.readLine();
        try {
            JSONObject responseJson = new JSONObject(line);
            reply = responseJson.toString();
        } catch (JSONException e) {
            JSONArray responseArray = new JSONArray(line);
            reply = responseArray.toString();
        }
        bufferedReader.close();
        response.close();
        return reply;
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to extract the response body.", e);
    }
}

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

@Override
public void execute() {
    try {//from   www  .ja v a2s  . c  o  m
        dbConn = PostgresConnection.getDataSource().getConnection();
        dbConn.setAutoCommit(true);
        proc = dbConn.prepareCall("{? = call favorite(?,?)}");
        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 favorites = proc.getInt(1);

        root.put("app", map.get("app"));
        root.put("method", map.get("method"));
        root.put("status", "ok");
        root.put("code", "200");
        root.put("favorites", favorites);
        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.OFF, e.getMessage(), e);
        } catch (JsonMappingException e) {
            //LOGGER.log(Level.OFF, e.getMessage(), e);
        } catch (IOException e) {
            //LOGGER.log(Level.OFF, e.getMessage(), e);
        }
        //            catch (JSONException e) {
        //                // TODO Auto-generated catch block
        //                e.printStackTrace();
        //            }

    } catch (PSQLException e) {
        if (e.getMessage().contains("unique constraint")) {
            CommandsHelp.handleError(map.get("app"), map.get("method"), "You already favorited this tweet",
                    map.get("correlation_id"), LOGGER);
        } else {
            CommandsHelp.handleError(map.get("app"), map.get("method"), e.getMessage(),
                    map.get("correlation_id"), LOGGER);
        }

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

From source file:com.mobeelizer.java.connection.MobeelizerConnectionServiceImpl.java

private MobeelizerOperationStatus<String> executePostAndGetContent(final String path, final JSONObject body) {
    HttpPost request = new HttpPost(getUrl(path, new String[0]));
    try {/*from  www .java 2s  .  c om*/
        request.setEntity(new StringEntity(body.toString(), "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        return new MobeelizerOperationStatus<String>(MobeelizerOperationErrorImpl.exception(e));
    }

    setHeaders(request, true, true);

    return executeAndGetContent(request);
}

From source file:com.imalu.alyou.activity.MySettingActivity.java

public void modifySetting(View v) {

    final ProgressDialog pd = new ProgressDialog(MySettingActivity.this);
    pd.setCanceledOnTouchOutside(false);

    nickname = (EditText) findViewById(R.id.nickname);

    final String name = nickname.getText().toString();

    ModifyUserRequest userInfo = new ModifyUserRequest();
    userInfo.setName(name);/*from  ww w . ja v  a2  s  .co m*/
    userInfo.setRealname(name);
    userInfo.setPhoneNum(AlUApplication.getMyInfo().getPhoneNum());
    userInfo.setPassword(AlUApplication.getMyInfo().getPassword());

    NetManager.execute(NetManager.MODIFY_USER_REQUEST_OPERATION, userInfo, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {

            try {

                pd.dismiss();
                Log.e("login_check", " response:" + response.toString());

                OperationResponse operationRes = new OperationResponse();
                operationRes.setJsonObject(response);

                AlUApplication.getMyInfo().setUsername(name);

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

            finish();
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, final String responseString,
                Throwable throwable) {

            runOnUiThread(new Runnable() {
                public void run() {
                    //pd.dismiss();
                    Toast.makeText(getApplicationContext(), ": " + responseString, 0).show();

                }
            });
        }
    });

}

From source file:org.uiautomation.ios.server.servlet.IOSServlet.java

private String toString(Response r) throws Exception {
    JSONObject o = new JSONObject();
    o.put("sessionId", r.getSessionId());
    o.put("status", r.getStatus());
    o.put("value", r.getValue().toString());
    return o.toString();
}

From source file:org.marietjedroid.connect.MarietjeClientChannel.java

public void handleMessage(String token, JSONObject data) throws JSONException {

    System.out.println("processing" + data.toString());
    if (data.getString("type").equals("media_part")) {
        synchronized (tracksRetrieved) {
            JSONObject ding = data.getJSONObject("part");

            @SuppressWarnings("unchecked")
            Iterator<String> it = ding.keys();
            while (it.hasNext())
                tempPartialMedia.add(ding.getJSONArray((it.next().toString())));
            if (this.partialMediaSize == tempPartialMedia.size()) {
                this.partialMedia = tempPartialMedia.toArray(new JSONArray[0]);
                this.tempPartialMedia.clear();
                this.partialMediaSize = -1;
                tracksRetrieved.release();
            }//w w  w.  ja  v  a 2s.c o  m

        }
    } else if (data.getString("type").equals("media")) {
        synchronized (tracksRetrieved) {
            this.partialMediaSize = data.getInt("count");
            if (this.partialMediaSize == tempPartialMedia.size()) {
                this.partialMedia = tempPartialMedia.toArray(new JSONArray[0]);
                this.tempPartialMedia.clear();
                this.partialMediaSize = 0;
                tracksRetrieved.release();
            }
        }
    } else if (data.getString("type").equals("welcome"))
        return;
    else if (data.getString("type").equals("playing")) {
        this.nowPlaying = data.getJSONObject("playing");
        playingRetrieved.release();
    } else if (data.getString("type").equals("requests")) {
        this.requests = data.getJSONArray("requests");
        this.requestsRetrieved.release();

    } else if (data.getString("type").equals("error_login")) {
        synchronized (loginAttempt) {
            this.loginError = new MarietjeException(data.getString("message"));
            this.loginAttempt.release();
        }
    } else if (data.getString("type").equals("login_token")) {
        synchronized (this.loginToken) {
            this.loginToken = data.getString("login_token");
            this.loginAttempt.release();
        }
    } else if (data.getString("type").equals("logged_in")) {
        synchronized (loginAttempt) {
            this.accessKey = data.getString("accessKey");
            loginAttempt.release();
        }
    } else if (data.getString("type").equals("error_request")) {
        this.requestError = data.getString("message");
        this.requestsRetrieved.release();
    } else if (data.getString("type").equals("query_media_results")) {
        if (data.getInt("token") != server.queryToken) {
            return; // wrong result set
        }
        synchronized (this.queryResults) {
            this.queryResults.clear();
            JSONArray results = data.getJSONArray("results");
            for (int i = 0; results.opt(i) != null; i++) {
                JSONObject m = results.getJSONObject(i);
                this.queryResults.add(new MarietjeTrack(m));
            }
            this.queryResultsRetrieved.release();
        }

    }

    this.setChanged();
    this.notifyObservers(data.getString("type"));
}