Example usage for org.json JSONObject optString

List of usage examples for org.json JSONObject optString

Introduction

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

Prototype

public String optString(String key) 

Source Link

Document

Get an optional string associated with a key.

Usage

From source file:at.alladin.rmbt.db.QoSTestObjective.java

@SuppressWarnings("unchecked")
public String toHtml() {
    StringBuilder sb = new StringBuilder();
    sb.append("<h3>QoS-Test (uid: " + getUid() + ", test_class: " + getTestClass() + ")</h3>");
    if (getObjective() != null) {
        try {// w  w  w. j  a v  a2s.co  m
            JSONObject objectives = new JSONObject(getObjective());
            Iterator<String> keys = objectives.keys();
            sb.append("<b>Test objectives (as plain text):</b> <ul>");
            while (keys.hasNext()) {
                String key = keys.next();
                sb.append("<li><i>" + key + "</i>: " + objectives.optString(key) + "</li>");
            }
            sb.append("</ul>");
            sb.append("<b>Test objectives (as hstore representation):</b> "
                    + Helperfunctions.json2hstore(objectives, null) + "<br><br>");
            if (testSummary != null) {
                sb.append("<b>Test summary (test_summary):</b> <a href=\"#"
                        + testSummary.replaceAll("[\\-\\+\\.\\^:,]", "_") + "\">" + testSummary
                        + "</a><br><br>");
            } else {
                sb.append("<b>Test summary (test_summary):</b> <i>NULL</i><br><br>");
            }
            if (testDescription != null) {
                sb.append("<b>Test description (test_desc):</b> <a href=\"#"
                        + testDescription.replaceAll("[\\-\\+\\.\\^:,]", "_") + "\">" + testDescription
                        + "</a><br><br>");
            } else {
                sb.append("<b>Test description (test_desc):</b> <i>NULL</i><br><br>");
            }
        } catch (JSONException e) {
            sb.append(
                    "<b><i>incorrect test objectives format:</i></b><ul><li>" + getObjective() + "</li></ul>");
            e.printStackTrace();
        }
    } else {
        sb.append("<b><i>no objectives set for this test</i></b>");
    }

    sb.append("<b>Expected test results (as hstore representation):</b><ul>");
    if (getResults() != null) {
        JSONArray resultsJson;
        try {
            resultsJson = new JSONArray(getResults());
            for (int i = 0; i < resultsJson.length(); i++) {
                try {
                    final JSONObject expected = resultsJson.getJSONObject(i);
                    sb.append("<li>" + Helperfunctions.json2htmlWithLinks(expected) + "</li>");
                } catch (Exception e) {
                    e.printStackTrace();
                    sb.append("<li>incorrect expected test result format</li>");
                }
            }
        } catch (JSONException e1) {
            sb.append("<li>incorrect expected test result format</li>");
        }
    } else {
        sb.append("<li><i>No expected results set for this test</i></li>");
    }
    sb.append("</ul>");
    return sb.toString();
}

From source file:at.tugraz.ist.catroid.web.ServerCalls.java

public boolean checkToken(String token) throws WebconnectionException {
    try {//  ww w.  ja  va  2s. c  o m
        HashMap<String, String> postValues = new HashMap<String, String>();
        postValues.put(Constants.TOKEN, token);

        String serverUrl = useTestUrl ? TEST_CHECK_TOKEN_URL : CHECK_TOKEN_URL;

        Log.v(TAG, "url to upload: " + serverUrl);
        resultString = connection.doHttpPost(serverUrl, postValues);

        JSONObject jsonObject = null;
        int statusCode = 0;

        Log.v(TAG, "result string: " + resultString);

        jsonObject = new JSONObject(resultString);
        statusCode = jsonObject.getInt("statusCode");
        String serverAnswer = jsonObject.optString("answer");

        if (statusCode == SERVER_RESPONSE_TOKEN_OK) {
            return true;
        } else {
            throw new WebconnectionException(statusCode, serverAnswer);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_JSON);
    } catch (IOException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_NETWORK);
    }
}

From source file:at.tugraz.ist.catroid.web.ServerCalls.java

public boolean registerOrCheckToken(String username, String password, String userEmail, String language,
        String country, String token) throws WebconnectionException {
    if (emailForUiTests != null) {
        userEmail = emailForUiTests;//from   ww w  . ja  v a 2s  .c  om
    }
    try {

        HashMap<String, String> postValues = new HashMap<String, String>();
        postValues.put(REG_USER_NAME, username);
        postValues.put(REG_USER_PASSWORD, password);
        postValues.put(REG_USER_EMAIL, userEmail);
        postValues.put(Constants.TOKEN, token);

        if (country != null) {
            postValues.put(REG_USER_COUNTRY, country);
        }
        if (language != null) {
            postValues.put(REG_USER_LANGUAGE, language);
        }
        String serverUrl = useTestUrl ? TEST_REGISTRATION_URL : REGISTRATION_URL;

        Log.v(TAG, "url to use: " + serverUrl);
        resultString = connection.doHttpPost(serverUrl, postValues);

        JSONObject jsonObject = null;
        int statusCode = 0;

        Log.v(TAG, "result string: " + resultString);

        jsonObject = new JSONObject(resultString);
        statusCode = jsonObject.getInt("statusCode");
        String serverAnswer = jsonObject.optString("answer");

        boolean registered;
        if (statusCode == SERVER_RESPONSE_TOKEN_OK) {
            registered = false;
        } else if (statusCode == SERVER_RESPONSE_REGISTER_OK) {
            registered = true;
        } else {
            throw new WebconnectionException(statusCode, serverAnswer);
        }
        return registered;
    } catch (JSONException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_JSON);
    } catch (IOException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_NETWORK);
    }
}

From source file:sh.calaba.driver.client.model.impl.ViewImpl.java

public String getText() {
    JSONObject result = executeCalabashCommand(CalabashCommands.GET_TEXT_BY_ID, id.getIdentifier());
    return result.optString("message");
}

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

public void handleDirectMessage(Context context, Contact from, JSONObject obj) {
    String arg = obj.optString(ARG);
    Intent launch = new Intent();
    launch.setAction(Intent.ACTION_MAIN);
    launch.addCategory(Intent.CATEGORY_LAUNCHER);
    launch.putExtra("android.intent.extra.APPLICATION_ARGUMENT", arg);
    launch.putExtra("creator", false);
    launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    String webUrl = obj.optString(WEB_URL);
    launch.setData(Uri.parse(webUrl));//from   ww  w .  ja v  a  2 s.  com
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, launch,
            PendingIntent.FLAG_CANCEL_CURRENT);
    (new PresenceAwareNotify(context)).notify("New Invitation", "Invitation received",
            "Click to launch application.", contentIntent);
}

From source file:com.tatsuowatanabe.funukulelequiz.util.Purchase.java

public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
    mItemType = itemType;//from  www  . j  ava 2s .com
    mOriginalJson = jsonPurchaseInfo;
    JSONObject o = new JSONObject(mOriginalJson);
    mOrderId = o.optString("orderId");
    mPackageName = o.optString("packageName");
    mSku = o.optString("productId");
    mPurchaseTime = o.optLong("purchaseTime");
    mPurchaseState = o.optInt("purchaseState");
    mDeveloperPayload = o.optString("developerPayload");
    mToken = o.optString("token", o.optString("purchaseToken"));
    mIsAutoRenewing = o.optBoolean("autoRenewing");
    mSignature = signature;
}

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

public void render(Context context, ViewGroup frame, Obj obj, boolean allowInteractions) {
    JSONObject content = obj.getJson();
    TextView valueTV = new TextView(context);
    valueTV.setText(content.optString(TEXT));
    valueTV.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));
    valueTV.setGravity(Gravity.TOP | Gravity.LEFT);
    if (Linkify.addLinks(valueTV, Linkify.ALL)) {
        if (!allowInteractions)
            valueTV.setMovementMethod(null);
    }//from w  w w  . j  av  a2  s  .  c  om

    frame.addView(valueTV);
}

From source file:com.weibo.net.Oauth2AccessToken.java

public Oauth2AccessToken(String rltString) {
    // { "access_token":"SlAV32hkKG", "expires_in":3600, "refresh_token":"8xLOxBtZp8" } 
    if (rltString != null) {
        if (rltString.indexOf("{") >= 0) {
            try {
                JSONObject json = new JSONObject(rltString);
                setToken(json.optString("access_token"));
                setExpiresIn(json.optInt("expires_in"));
                setRefreshToken(json.optString("refresh_token"));
            } catch (JSONException e) {
                //??
            }//from   w  w  w.j a  v a2  s .co  m
        }
    }
}

From source file:com.vk.sdkweb.api.model.VKPrivacy.java

/**
 * Parses privacy in int format from privacy_view format.
 * @see <a href="http://vk.com/dev/privacy_setting">http://vk.com/dev/privacy_setting</a>
 *//*from w ww . j ava 2s . co  m*/
public static int parsePrivacy(JSONObject privacyView) {
    int privacy = 0;
    if (privacyView != null) {
        String type = privacyView.optString("type");
        if ("all".equals(type)) {
            privacy = PRIVACY_ALL;
        } else if ("friends".equals(type)) {
            privacy = PRIVACY_FRIENDS;
        } else if ("friends_of_friends".equals(type)) {
            privacy = PRIVACY_FRIENDS_OF_FRIENDS;
        } else if ("nobody".equals(type)) {
            privacy = PRIVACY_NOBODY;
        } else {
            privacy = PRIVACY_UNKNOWN;
        }
    }
    return privacy;
}

From source file:com.chaosinmotion.securechat.server.commands.ForgotPassword.java

/**
 * Process a forgot password request. This generates a token that the
 * client is expected to return with the change password request.
 * @param requestParams//  w ww  . j  a v a  2s. c o m
 * @throws SQLException 
 * @throws IOException 
 * @throws ClassNotFoundException 
 * @throws JSONException 
 * @throws NoSuchAlgorithmException 
 */

public static void processRequest(JSONObject requestParams)
        throws SQLException, ClassNotFoundException, IOException, NoSuchAlgorithmException, JSONException {
    String username = requestParams.optString("username");

    /*
     * Step 1: Convert username to the userid for this
     */
    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    int userID = 0;
    String retryID = UUID.randomUUID().toString();

    try {
        c = Database.get();
        ps = c.prepareStatement("SELECT userid " + "FROM Users " + "WHERE username = ?");
        ps.setString(1, username);
        rs = ps.executeQuery();
        if (rs.next()) {
            userID = rs.getInt(1);
        }

        if (userID == 0)
            return;
        ps.close();
        rs.close();

        /*
         * Step 2: Generate the retry token and insert into the forgot 
         * database with an expiration date 1 hour from now.
         */

        Timestamp ts = new Timestamp(System.currentTimeMillis() + 3600000);
        ps = c.prepareStatement("INSERT INTO ForgotPassword " + "    ( userid, token, expires ) " + "VALUES "
                + "    ( ?, ?, ?)");
        ps.setInt(1, userID);
        ps.setString(2, retryID);
        ps.setTimestamp(3, ts);
        ps.execute();
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }

    /*
     * Step 3: formulate a JSON string with the retry and send
     * to the user. The format of the command we send is:
     * 
     * { "cmd": "forgotpassword", "token": token }
     */

    JSONObject obj = new JSONObject();
    obj.put("cmd", "forgotpassword");
    obj.put("token", retryID);
    MessageQueue.getInstance().enqueueAdmin(userID, obj.toString(4));
}