Example usage for org.json JSONObject has

List of usage examples for org.json JSONObject has

Introduction

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

Prototype

public boolean has(String key) 

Source Link

Document

Determine if the JSONObject contains a specific key.

Usage

From source file:org.wso2.carbon.connector.integration.test.meetup.boards.BoardsIntegrationTest.java

/**
 * Test getDiscussions API operation for Mandatory fields.
 * Expecting Response header '200' and 'id' JSONObject in returned
 * JSONArray.//from  ww  w.  ja va  2  s.c o  m
 *
 * @throws Exception if test fails.
 */
@Test(enabled = true, groups = {
        "wso2.esb" }, description = "Board's getDiscussions operation integration test for Mandatory fields")
public void testGetDiscussionsMandatory() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "boards_getDiscussions_mandatory.txt";
    String methodName = "boards_getDiscussions";

    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";
    String modifiedJsonString = String.format(jsonString,
            meetupConnectorProperties.getProperty("access_token"));
    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {

        int responseHeader = ConnectorIntegrationUtil
                .sendRequestToRetriveHeaders(getProxyServiceURL(methodName), modifiedJsonString);
        Assert.assertTrue(responseHeader == 200);

        JSONArray jsonArray = ConnectorIntegrationUtil.sendRequestJSONArray(getProxyServiceURL(methodName),
                modifiedJsonString);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        Assert.assertTrue(jsonObject.has("id"));

    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:org.wso2.carbon.connector.integration.test.meetup.boards.BoardsIntegrationTest.java

/**
 * Test getDiscussions API operation for negative scenario.
 * Expecting Response header '401' and 'errors' JSONObject in returned
 * JSONArray.//from  ww  w . ja  v  a  2 s .  c  o  m
 *
 * @throws Exception if test fails.
 */
@Test(enabled = true, groups = {
        "wso2.esb" }, description = "Board's getDiscussions operation integration test for negative scenario")
public void testGetDiscussionsNegative() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "boards_getDiscussions_negative.txt";
    String methodName = "boards_getDiscussions";

    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";
    /*
     * String modifiedJsonString = String.format(jsonString,
     * meetupConnectorProperties.getProperty("access_token"));
     */
    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {

        int responseHeader = ConnectorIntegrationUtil
                .sendRequestToRetriveHeaders(getProxyServiceURL(methodName), jsonString);
        Assert.assertTrue(responseHeader == 401);

        JSONObject jsonObject = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName),
                jsonString);
        Assert.assertTrue(jsonObject.has("errors"));

    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:org.wso2.carbon.connector.integration.test.meetup.boards.BoardsIntegrationTest.java

/**
 * Test getDiscussionPosts API operation for Mandatory fields.
 * Expecting Response header '200' and 'id' JSONObject in returned
 * JSONArray.//from   ww  w .ja v a 2 s  .  c  o m
 *
 * @throws Exception if test fails.
 */
@Test(enabled = true, groups = {
        "wso2.esb" }, description = "Board's getDiscussionPosts operation integration test for Mandatory fields")
public void testGetDiscussionPostsMandatory() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "boards_getDiscussionPosts_mandatory.txt";
    String methodName = "boards_getDiscussionPosts";

    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";
    String modifiedJsonString = String.format(jsonString,
            meetupConnectorProperties.getProperty("access_token"));
    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {

        int responseHeader = ConnectorIntegrationUtil
                .sendRequestToRetriveHeaders(getProxyServiceURL(methodName), modifiedJsonString);
        Assert.assertTrue(responseHeader == 200);

        JSONArray jsonArray = ConnectorIntegrationUtil.sendRequestJSONArray(getProxyServiceURL(methodName),
                modifiedJsonString);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        Assert.assertTrue(jsonObject.has("id"));

    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:org.wso2.carbon.connector.integration.test.meetup.boards.BoardsIntegrationTest.java

/**
 * Test getDiscussionPosts API operation for negative scenario.
 * Expecting Response header '401' and 'errors' JSONObject in returned
 * JSONArray.//from w  w w.  ja  v  a  2s.co  m
 *
 * @throws Exception if test fails.
 */
@Test(enabled = true, groups = {
        "wso2.esb" }, description = "Board's getDiscussionPosts operation integration test for negative scenario")
public void testGetDiscussionPostsNegative() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "boards_getDiscussionPosts_negative.txt";
    String methodName = "boards_getDiscussionPosts";

    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";
    /*
     * String modifiedJsonString = String.format(jsonString,
     * meetupConnectorProperties.getProperty("access_token"));
     */
    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {

        int responseHeader = ConnectorIntegrationUtil
                .sendRequestToRetriveHeaders(getProxyServiceURL(methodName), jsonString);
        Assert.assertTrue(responseHeader == 401);

        JSONObject jsonObject = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName),
                jsonString);
        Assert.assertTrue(jsonObject.has("errors"));

    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:com.ichi2.libanki.importer.Anki2Importer.java

/** Decks */

/* Given did in src col, return local id */
private long _did(long did) {
    try {//from  w w w  .ja  va  2  s  . c  om
        // already converted?
        if (mDecks.containsKey(did)) {
            return mDecks.get(did);
        }
        // get the name in src
        JSONObject g = mSrc.getDecks().get(did);
        String name = g.getString("name");
        // if there's a prefix, replace the top level deck
        if (mDeckPrefix != null) {
            String[] tmpname = name.split("::", -1);
            name = mDeckPrefix;
            if (tmpname.length > 1) {
                for (int i = 0; i < tmpname.length - 2; i++) {
                    name += "::" + tmpname[i + 1];
                }
            }
        }
        // Manually create any parents so we can pull in descriptions
        String head = "";
        String[] parents = name.split("::", -1);
        for (int i = 0; i < parents.length - 1; ++i) {
            if (head.length() > 0) {
                head = head.concat("::");
            }
            head = head.concat(parents[i]);
            long idInSrc = mSrc.getDecks().id(head);
            _did(idInSrc);
        }
        // create in local
        long newid = mDst.getDecks().id(name);
        // pull conf over
        if (g.has("conf") && g.getLong("conf") != 1) {
            JSONObject conf = mSrc.getDecks().getConf(g.getLong("conf"));
            mDst.getDecks().save(conf);
            mDst.getDecks().updateConf(conf);
            JSONObject g2 = mDst.getDecks().get(newid);
            g2.put("conf", g.getLong("conf"));
            mDst.getDecks().save(g2);
        }
        // save desc
        JSONObject deck = mDst.getDecks().get(newid);
        deck.put("desc", g.getString("desc"));
        mDst.getDecks().save(deck);
        // add to deck map and return
        mDecks.put(did, newid);
        return newid;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.asd.littleprincesbeauty.data.TaskList.java

@Override
public void setContentByRemoteJSON(JSONObject js) {
    if (js != null) {
        try {/*w  ww .  j  ava 2 s  . c o m*/
            // id
            if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
                setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
            }

            // last_modified
            if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
                setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
            }

            // name
            if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
                setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
            }

        } catch (JSONException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new ActionFailureException("fail to get tasklist content from jsonobject");
        }
    }
}

From source file:com.asd.littleprincesbeauty.data.TaskList.java

@Override
public void setContentByLocalJSON(JSONObject js) {
    if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
        Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
    }//from  w w  w  .  ja v  a  2  s  .  c o m

    try {
        JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);

        if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
            String name = folder.getString(NoteColumns.SNIPPET);
            setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
        } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
            if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
                setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
            else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
                setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE);
            else
                Log.e(TAG, "invalid system folder");
        } else {
            Log.e(TAG, "error type");
        }
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }
}

From source file:com.citruspay.mobile.payment.oauth2.OAuth2Token.java

public static OAuth2Token create(JSONObject json) {
    // enhance object w/ expiry date
    JSONObject jtoken = json;/* w  w w .ja  v  a2s .c  o  m*/
    if (!json.has("expiry")) {
        // copy input
        jtoken = new JSONObject();
        for (Iterator<?> keys = json.keys(); keys.hasNext();) {
            String key = (String) keys.next();
            try {
                jtoken.put(key, json.get(key));
            } catch (JSONException jx) {
                throw new RuntimeException(jx);
            }
        }

        // add expiry date
        long expiry = new Date().getTime() / 1000l;
        try {
            expiry += json.getLong("expires_in");
        } catch (JSONException jx) {
            /* ignore => expires now ! */
        }
        try {
            jtoken.put("expiry", expiry);
        } catch (JSONException jx) {
            throw new RuntimeException(jx);
        }
    }

    // create token
    return new OAuth2Token(jtoken);
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java

/**
 * This method is called when the JavaScript sends a message to the native side.
 * This method should be overridden in subclasses.
 * @param message : the JSON-message sent by JavaScript.
 * @return true if the message was handled by the native, false otherwise
 * @details some basic operations are already implemented : navigation, logs, toasts, native alerts, web alerts
 * @details this method may be called from a secondary thread.
 *//*from   ww w.  ja  va  2 s . co m*/
// This method must be public !!!
@JavascriptInterface
public boolean onCobaltMessage(String message) {
    try {
        final JSONObject jsonObj = new JSONObject(message);

        // TYPE
        if (jsonObj.has(Cobalt.kJSType)) {
            String type = jsonObj.getString(Cobalt.kJSType);

            //CALLBACK
            if (type.equals(Cobalt.JSTypeCallBack)) {
                String callbackID = jsonObj.getString(Cobalt.kJSCallback);
                JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData);

                return handleCallback(callbackID, data);
            }

            // COBALT IS READY
            else if (type.equals(Cobalt.JSTypeCobaltIsReady)) {
                String versionWeb = jsonObj.optString(Cobalt.kJSVersion, null);
                String versionNative = getResources().getString(R.string.version_name);
                if (versionWeb != null && !versionWeb.equals(versionNative))
                    Log.e(TAG, "Warning : Cobalt version mismatch : Android Cobalt version is " + versionNative
                            + " but Web Cobalt version is " + versionWeb + ". You should fix this. ");
                onCobaltIsReady();
                return true;
            }

            // EVENT
            else if (type.equals(Cobalt.JSTypeEvent)) {
                String event = jsonObj.getString(Cobalt.kJSEvent);
                JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData);
                String callback = jsonObj.optString(Cobalt.kJSCallback, null);

                return handleEvent(event, data, callback);
            }

            // INTENT
            else if (type.equals(Cobalt.JSTypeIntent)) {
                String action = jsonObj.getString(Cobalt.kJSAction);

                // OPEN EXTERNAL URL
                if (action.equals(Cobalt.JSActionIntentOpenExternalUrl)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String url = data.getString(Cobalt.kJSUrl);
                    openExternalUrl(url);

                    return true;
                }

                // UNHANDLED INTENT
                else {
                    onUnhandledMessage(jsonObj);
                }
            }

            // LOG
            else if (type.equals(Cobalt.JSTypeLog)) {
                String text = jsonObj.getString(Cobalt.kJSValue);
                Log.d(Cobalt.TAG, "JS LOG: " + text);
                return true;
            }

            // NAVIGATION
            else if (type.equals(Cobalt.JSTypeNavigation)) {
                String action = jsonObj.getString(Cobalt.kJSAction);

                // PUSH
                if (action.equals(Cobalt.JSActionNavigationPush)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String page = data.getString(Cobalt.kJSPage);
                    String controller = data.optString(Cobalt.kJSController, null);
                    push(controller, page);
                    return true;
                }

                // POP
                else if (action.equals(Cobalt.JSActionNavigationPop)) {
                    JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData);
                    if (data != null) {
                        String page = data.getString(Cobalt.kJSPage);
                        String controller = data.optString(Cobalt.kJSController, null);
                        pop(controller, page);
                    } else
                        pop();
                    return true;
                }

                // MODAL
                else if (action.equals(Cobalt.JSActionNavigationModal)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String page = data.getString(Cobalt.kJSPage);
                    String controller = data.optString(Cobalt.kJSController, null);
                    String callbackId = jsonObj.optString(Cobalt.kJSCallback, null);
                    presentModal(controller, page, callbackId);
                    return true;
                }

                // DISMISS
                else if (action.equals(Cobalt.JSActionNavigationDismiss)) {
                    // TODO: not present in iOS
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String controller = data.getString(Cobalt.kJSController);
                    String page = data.getString(Cobalt.kJSPage);
                    dismissModal(controller, page);
                    return true;
                }

                //REPLACE
                else if (action.equals(Cobalt.JSActionNavigationReplace)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String controller = data.getString(Cobalt.kJSController);
                    String page = data.getString(Cobalt.kJSPage);
                    boolean animated = data.optBoolean(Cobalt.kJSAnimated);
                    replace(controller, page, animated);
                    return true;
                }

                // UNHANDLED NAVIGATION
                else {
                    onUnhandledMessage(jsonObj);
                }
            }

            // PLUGIN
            else if (type.equals(Cobalt.JSTypePlugin)) {
                mPluginManager.onMessage(mContext, this, jsonObj);
            }

            // UI
            else if (type.equals(Cobalt.JSTypeUI)) {
                String control = jsonObj.getString(Cobalt.kJSUIControl);
                JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                String callback = jsonObj.optString(Cobalt.kJSCallback, null);

                return handleUi(control, data, callback);
            }

            // WEB LAYER
            else if (type.equals(Cobalt.JSTypeWebLayer)) {
                String action = jsonObj.getString(Cobalt.kJSAction);

                // SHOW
                if (action.equals(Cobalt.JSActionWebLayerShow)) {
                    final JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);

                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            showWebLayer(data);
                        }
                    });

                    return true;
                }

                // UNHANDLED WEB LAYER
                else {
                    onUnhandledMessage(jsonObj);
                }
            }

            // UNHANDLED TYPE
            else {
                onUnhandledMessage(jsonObj);
            }
        }

        // UNHANDLED MESSAGE
        else {
            onUnhandledMessage(jsonObj);
        }
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - onCobaltMessage: JSONException");
        exception.printStackTrace();
    } catch (NullPointerException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - onCobaltMessage: NullPointerException");
        exception.printStackTrace();
    }

    return false;
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java

private boolean handleUi(String control, JSONObject data, String callback) {
    try {//  www . j a va  2s  . c  o m
        // PICKER
        switch (control) {
        case Cobalt.JSControlPicker:
            String type = data.getString(Cobalt.kJSType);

            // DATE
            if (type.equals(Cobalt.JSPickerDate)) {
                JSONObject date = data.optJSONObject(Cobalt.kJSDate);

                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int day = calendar.get(Calendar.DAY_OF_MONTH);

                if (date != null && date.has(Cobalt.kJSYear) && date.has(Cobalt.kJSMonth)
                        && date.has(Cobalt.kJSDay)) {
                    year = date.getInt(Cobalt.kJSYear);
                    month = date.getInt(Cobalt.kJSMonth) - 1;
                    day = date.getInt(Cobalt.kJSDay);
                }

                JSONObject texts = data.optJSONObject(Cobalt.kJSTexts);
                String title = texts.optString(Cobalt.kJSTitle, null);
                //String delete = texts.optString(Cobalt.kJSDelete, null);
                String clear = texts.optString(Cobalt.kJSClear, null);
                String cancel = texts.optString(Cobalt.kJSCancel, null);
                String validate = texts.optString(Cobalt.kJSValidate, null);

                showDatePickerDialog(year, month, day, title, clear, cancel, validate, callback);

                return true;
            }

            break;
        case Cobalt.JSControlAlert:
            showAlertDialog(data, callback);
            return true;
        case Cobalt.JSControlToast:
            String message = data.getString(Cobalt.kJSMessage);
            Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
            return true;
        default:
            break;
        }
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - handleUi: JSONException");
        exception.printStackTrace();
    }

    // UNHANDLED UI
    try {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(Cobalt.kJSType, Cobalt.JSTypeUI);
        jsonObj.put(Cobalt.kJSUIControl, control);
        jsonObj.put(Cobalt.kJSData, data);
        jsonObj.put(Cobalt.kJSCallback, callback);
        onUnhandledMessage(jsonObj);
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - handleUi: JSONException");
        exception.printStackTrace();
    }

    return false;
}