Example usage for org.json JSONObject getJSONObject

List of usage examples for org.json JSONObject getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(String key) throws JSONException 

Source Link

Document

Get the JSONObject value associated with a key.

Usage

From source file:org.tomdroid.sync.web.OAuthConnection.java

public boolean getAccess(String verifier) throws UnknownHostException {

    TLog.i(TAG, "Verifier: {0}", verifier);

    // this method shouldn't have been called
    if (isAuthenticated())
        return false;

    if (!requestToken.equals("") && !requestTokenSecret.equals("")) {
        consumer.setTokenWithSecret(requestToken, requestTokenSecret);
        TLog.d(TAG, "Added request token {0} and request token secret {1}", requestToken, requestTokenSecret);
    } else/*w  w w .j  a v a  2 s .c om*/
        return false;

    OAuthProvider provider = getProvider();

    try {
        provider.retrieveAccessToken(consumer, verifier);
    } catch (OAuthMessageSignerException e1) {
        e1.printStackTrace();
        return false;
    } catch (OAuthNotAuthorizedException e1) {
        e1.printStackTrace();
        return false;
    } catch (OAuthExpectationFailedException e1) {
        e1.printStackTrace();
        return false;
    } catch (OAuthCommunicationException e1) {
        e1.printStackTrace();
        return false;
    }

    // access has been granted, store the access token
    accessToken = consumer.getToken();
    accessTokenSecret = consumer.getTokenSecret();
    requestToken = "";
    requestTokenSecret = "";

    try {
        JSONObject response = new JSONObject(get(rootApi));
        TLog.d(TAG, "Request: {0}", rootApi);

        // append a slash to the url, else the signature will fail
        userApi = response.getJSONObject("user-ref").getString("api-ref");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    saveConfiguration();

    TLog.i(TAG, "Got access token {0}.", consumer.getToken());

    return true;
}

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

@Override
public VKApiModel parse(JSONObject object) {
    try {//from ww  w  .j a  v a 2 s .c o m
        JSONArray jsonArray;
        if ((jsonArray = object.optJSONArray("response")) == null) {
            object = object.getJSONObject("response");
            count = object.getInt("count");
            jsonArray = object.getJSONArray("items");
        }
        parse(jsonArray);

    } catch (JSONException e) {
        if (VKSdk.DEBUG)
            e.printStackTrace();
    }
    fields = object;
    return this;
}

From source file:com.google.testing.testify.risk.frontend.server.task.UploadDataTask.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    String user = req.getParameter("user");
    String jsonString = req.getParameter("json");
    try {//from w w w.  j a v a2s . c  o m
        // TODO(jimr): add impersonation of user in string user.
        JSONObject json = new JSONObject(jsonString);
        JSONObject item;
        if (json.has("bug")) {
            item = json.getJSONObject("bug");
            Bug bug = new Bug();
            bug.setParentProjectId(item.getLong("projectId"));
            bug.setExternalId(item.getLong("bugId"));
            bug.setTitle(item.getString("title"));
            bug.setPath(item.getString("path"));
            bug.setSeverity(item.getLong("severity"));
            bug.setPriority(item.getLong("priority"));
            bug.setBugGroups(Sets.newHashSet(StringUtil.csvToList(item.getString("groups"))));
            bug.setBugUrl(item.getString("url"));
            bug.setState(item.getString("status"));
            bug.setStateDate(item.getLong("statusDate"));
            dataService.addBug(bug);
        } else if (json.has("test")) {
            item = json.getJSONObject("test");
            TestCase test = new TestCase();
            test.setParentProjectId(item.getLong("projectId"));
            test.setExternalId(item.getLong("testId"));
            test.setTitle(item.getString("title"));
            test.setTags(Sets.newHashSet(StringUtil.csvToList(item.getString("tags"))));
            test.setTestCaseUrl(item.getString("url"));
            test.setState(item.getString("result"));
            test.setStateDate(item.getLong("resultDate"));
            dataService.addTestCase(test);
        } else if (json.has("checkin")) {
            item = json.getJSONObject("checkin");
            Checkin checkin = new Checkin();
            checkin.setParentProjectId(item.getLong("projectId"));
            checkin.setExternalId(item.getLong("checkinId"));
            checkin.setSummary(item.getString("summary"));
            checkin.setDirectoriesTouched(Sets.newHashSet(StringUtil.csvToList(item.getString("directories"))));
            checkin.setChangeUrl(item.getString("url"));
            checkin.setState(item.getString("state"));
            checkin.setStateDate(item.getLong("stateDate"));
            dataService.addCheckin(checkin);
        } else {
            LOG.severe("No applicable data found for json: " + json.toString());
        }
    } catch (JSONException e) {
        // We don't issue a 500 or similar response code here to prevent retries, which would have
        // no different a result.
        LOG.severe("Couldn't parse input JSON: " + jsonString);
        return;
    }
}

From source file:com.google.wave.api.impl.EventMessageBundleSerializer.java

@Override
public Object unmarshall(SerializerState state, Class clazz, Object json) throws UnmarshallException {
    if (!EventMessageBundle.class.isAssignableFrom(clazz)) {
        throw new UnmarshallException(clazz.getName() + " is not assignable from EventMessageBundle");
    }/*w w w.  j  a v  a  2s .  c om*/

    JSONObject jsonObject = (JSONObject) json;
    EventMessageBundle bundle = new EventMessageBundle();
    try {
        bundle.setEvents(
                (List<EventData>) ser.unmarshall(state, List.class, jsonObject.getJSONObject("events")));
        bundle.setWaveletData(
                (WaveletData) ser.unmarshall(state, WaveletData.class, jsonObject.getJSONObject("wavelet")));
        bundle.setBlipData((Map<String, BlipData>) ser.unmarshall(state, Map.class, jsonObject.get("blips")));
    } catch (JSONException jsonx) {
        jsonx.printStackTrace();
    }

    return bundle;
}

From source file:produvia.com.scanner.DevicesActivity.java

/*********************************************************************
 * The WeaverSdk callback indicating that a task has been completed:
 *********************************************************************/
@Override//from  w w  w  .ja  va2s .com
public void onTaskCompleted(final int flag, final JSONObject response) {
    if (response == null || mActivityPaused)
        return;
    try {

        if (response.has("responseCode") && response.getInt("responseCode") == 401) {
            //unauthorized:
            runWelcomeActivity();
        }

        switch (flag) {
        case WeaverSdk.ACTION_USER_LOGOUT:
            runWelcomeActivity();
            break;

        case WeaverSdk.ACTION_SERVICES_GET:
            if (response.getBoolean("success")) {
                handleReceivedServices(response.getJSONObject("data"));
            }
            break;

        }

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

From source file:produvia.com.scanner.DevicesActivity.java

/*********************************************************************
 * The WeaverSdk callback indicating that a task update occurred.
 * for example, a new service was discovered in the current network:
 *********************************************************************/
@Override//from  w w w .j a  v  a  2 s.co  m
public void onTaskUpdate(int flag, JSONObject response) {
    if (response == null || mActivityPaused)
        return;
    try {
        //this flag indicates that a new service was discovered in the scan:
        if (flag == WeaverSdk.ACTION_SERVICES_SCAN) {
            if (response.getBoolean("success")) {
                handleReceivedServices(response.getJSONObject("data"));
            }
        }
        //when tha scan is running - it'll provide general state information from time to time:
        else if (flag == WeaverSdk.ACTION_SCAN_STATUS) {
            if (response.getBoolean("success")) {
                if (response.getString("info").equals("Scan running")) {
                    mLastScanStartedAt = Calendar.getInstance();
                    showScanProgress(true);
                } else {
                    mScanCycleCounter += 1;
                    showScanProgress(false);
                    //if we haven't found any light services - we'll show an error message:
                    //if we finished the scan - check if we found any devices:
                    if (mScanCycleCounter > 0 && (mDevices == null || mDevices.size() <= 0)) {
                        setErrorMessage(
                                "Weaver didn't detect any services in the network\nPlease make sure you're connected to the wifi\nand restart the app");
                        //stop the scan:
                        WeaverSdkApi.discoveryService(null, false);
                        return;
                    }
                    //stop the discovery service after max scan cycles:
                    if (mScanCycleCounter >= MAX_SCAN_CYCLES)
                        WeaverSdkApi.discoveryService(null, false);

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

}

From source file:produvia.com.scanner.DevicesActivity.java

private void updateServiceDeviceDatabase(JSONObject data) {
    try {//from   w  w  w.  java 2s  .  c o  m
        //first add the services to the devices:
        JSONArray services = data.getJSONArray("services");
        for (int i = 0; i < services.length(); i++) {
            JSONObject service = services.getJSONObject(i);
            String device_id = service.getString("device_id");
            JSONObject device = data.getJSONObject("devices_info").getJSONObject(device_id);
            if (!device.has("services"))
                device.put("services", new JSONObject());
            device.getJSONObject("services").put(service.getString("id"), service);
        }

        JSONObject devices = data.getJSONObject("devices_info");
        //loop over the devices and merge them into the device display:
        for (Iterator<String> iter = devices.keys(); iter.hasNext();) {
            String device_id = iter.next();
            JSONObject device = devices.getJSONObject(device_id);
            //if a device card is already present - just merge the data:
            boolean found = false;
            int network_card_idx = -1;
            for (int i = 0; i < mDevices.size(); i++) {
                CustomListItem cli = mDevices.get(i);
                if (cli instanceof DeviceCard && ((DeviceCard) cli).getId().equals(device_id)) {
                    ((DeviceCard) cli).updateInfo(device);
                    found = true;
                    break;
                } else if (cli.getDescription().equals(device.getString("network_id"))) {
                    network_card_idx = i;
                }
            }

            if (!found) {
                if (network_card_idx < 0) {
                    JSONObject network = data.getJSONObject("networks_info")
                            .getJSONObject(device.getString("network_id"));
                    String name = "";
                    if (network.has("name") && network.getString("name") != null)
                        name = network.getString("name");
                    network_card_idx = addNetworkCard(name, device.getString("network_id"),
                            network.getBoolean("user_inside_network"));
                }
                network_card_idx += 1;
                //find the correct index for the card sorted by last seen:
                for (; network_card_idx < mDevices.size(); network_card_idx++) {
                    CustomListItem cli = mDevices.get(network_card_idx);
                    if (!(cli instanceof DeviceCard))
                        break;
                    if (((DeviceCard) cli).getLastSeen()
                            .compareTo(DeviceCard.getLastSeenFromString(device.getString("last_seen"))) < 0)
                        break;
                }

                DeviceCard dc = new DeviceCard(device);
                mDevices.add(network_card_idx, dc);
            }
        }
        notifyDataSetChanged();

    } catch (JSONException e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

From source file:produvia.com.scanner.DevicesActivity.java

public void promptUsernamePassword(final JSONObject loginService, final JSONObject responseData,
        final boolean isKey, String description) throws JSONException {

    LayoutInflater li = LayoutInflater.from(DevicesActivity.this);
    View promptsView = li.inflate(R.layout.prompt_userpass, null);
    final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(DevicesActivity.this);
    alertDialogBuilder.setView(promptsView);

    final EditText userInput = (EditText) promptsView.findViewById(R.id.pu_username);
    final EditText passInput = (EditText) promptsView.findViewById(R.id.pu_password);
    //if it's a key type input hide the password field:
    if (isKey) {//  w  w  w.ja v  a 2  s. c  o  m
        passInput.setVisibility(View.GONE);
        userInput.setText(loginService.getJSONObject("properties").getString("key"));
        userInput.setHint("Enter key");
    } else {
        userInput.setText(loginService.getJSONObject("properties").getString("username"));
        passInput.setText(loginService.getJSONObject("properties").getString("password"));
    }

    final TextView prompt_user_pass = (TextView) promptsView.findViewById(R.id.user_pass_title);

    String name = responseData.getJSONObject("devices_info").getJSONObject(loginService.getString("device_id"))
            .getString("name");

    String message;
    if (description == null) {
        message = "Enter " + name + "'s username and password.";
    } else {
        message = description;
    }
    message += "\n(if it's disconnected just press cancel)";

    prompt_user_pass.setText(message);

    // set dialog message
    alertDialogBuilder.setCancelable(false).setNegativeButton("Go", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            String username = (userInput.getText()).toString();
            String password = (passInput.getText()).toString();
            try {
                if (isKey) {
                    loginService.getJSONObject("properties").put("key", username);

                } else {
                    loginService.getJSONObject("properties").put("username", username);
                    loginService.getJSONObject("properties").put("password", password);
                }
                //stick the service into the response data structure and set the service:
                JSONArray services = new JSONArray();
                services.put(loginService);
                responseData.put("services", services);
                WeaverSdkApi.servicesSet(DevicesActivity.this, responseData);
            } catch (JSONException e) {
            }

        }
    }).setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();

}

From source file:com.ibm.iot.android.iotstarter.utils.MessageConductor.java

/**
 * Steer incoming MQTT messages to the proper activities based on their content.
 *
 * @param payload The log of the MQTT message.
 * @param topic The topic the MQTT message was received on.
 * @throws JSONException If the message contains invalid JSON.
 *//*  w  w w  .java 2  s .  c o m*/
public void steerMessage(String payload, String topic) throws JSONException {
    Log.d(TAG, ".steerMessage() entered");
    JSONObject top = new JSONObject(payload);
    JSONObject d = top.getJSONObject("d");

    if (topic.contains(Constants.COLOR_EVENT)) {
        Log.d(TAG, "Color Event");
        int r = d.getInt("r");
        int g = d.getInt("g");
        int b = d.getInt("b");

        // alpha value received is 0.0 < a < 1.0 but Color.argb expects 0 < a < 255
        int alpha = (int) (d.getDouble("alpha") * 255.0);
        if ((r > 255 || r < 0) || (g > 255 || g < 0) || (b > 255 || b < 0) || (alpha > 255 || alpha < 0)) {
            return;
        }

        app.setColor(Color.argb(alpha, r, g, b));
        Intent actionIntent = new Intent(Constants.APP_ID + Constants.INTENT_IOT);
        actionIntent.putExtra(Constants.INTENT_DATA, Constants.COLOR_EVENT);
        context.sendBroadcast(actionIntent);

    } else if (topic.contains(Constants.FRE_EVENT)) {
        JSONObject topp = new JSONObject(payload);
        JSONObject dd = topp.getJSONObject("d");
        int frequency = dd.getInt("f");

        Log.d("MMM", "" + frequency);
        app.setFfe(frequency);

    } else if (topic.contains(Constants.LIGHT_EVENT)) {
        app.handleLightMessage();
    } else if (topic.contains(Constants.TEXT_EVENT)) {
        int unreadCount = app.getUnreadCount();
        String messageText = d.getString("text");
        app.setUnreadCount(++unreadCount);

        // Log message with the following format:
        // [yyyy-mm-dd hh:mm:ss.S] Received text:
        // <message text>
        Date date = new Date();
        String logMessage = "[" + new Timestamp(date.getTime()) + "] Received Text:\n";
        app.getMessageLog().add(logMessage + messageText);

        // Send intent to LOG fragment to mark list data invalidated
        String runningActivity = app.getCurrentRunningActivity();
        //if (runningActivity != null && runningActivity.equals(LogPagerFragment.class.getName())) {
        Intent actionIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOG);
        actionIntent.putExtra(Constants.INTENT_DATA, Constants.TEXT_EVENT);
        context.sendBroadcast(actionIntent);
        //}

        // Send intent to current active fragment / activity to update Unread message count
        // Skip sending intent if active tab is LOG
        // TODO: 'current activity' code needs fixing.
        Intent unreadIntent;
        if (runningActivity.equals(LogPagerFragment.class.getName())) {
            unreadIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOG);
        } else if (runningActivity.equals(LoginPagerFragment.class.getName())) {
            unreadIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOGIN);
        } else if (runningActivity.equals(IoTPagerFragment.class.getName())) {
            unreadIntent = new Intent(Constants.APP_ID + Constants.INTENT_IOT);
        } else if (runningActivity.equals(ProfilesActivity.class.getName())) {
            unreadIntent = new Intent(Constants.APP_ID + Constants.INTENT_PROFILES);
        } else {
            return;
        }

        if (messageText != null) {
            unreadIntent.putExtra(Constants.INTENT_DATA, Constants.UNREAD_EVENT);
            context.sendBroadcast(unreadIntent);
        }
    } else if (topic.contains(Constants.ALERT_EVENT)) {
        // save payload in an arrayList
        int unreadCount = app.getUnreadCount();
        String messageText = d.getString("text");
        app.setUnreadCount(++unreadCount);

        // Log message with the following format:
        // [yyyy-mm-dd hh:mm:ss.S] Received alert:
        // <message text>
        Date date = new Date();
        String logMessage = "[" + new Timestamp(date.getTime()) + "] Received Alert:\n";
        app.getMessageLog().add(logMessage + messageText);

        String runningActivity = app.getCurrentRunningActivity();
        if (runningActivity != null) {
            //if (runningActivity.equals(LogPagerFragment.class.getName())) {
            Intent actionIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOG);
            actionIntent.putExtra(Constants.INTENT_DATA, Constants.TEXT_EVENT);
            context.sendBroadcast(actionIntent);
            //}

            // Send alert intent with message payload to current active activity / fragment.
            // TODO: update for current activity changes.
            Intent alertIntent;
            if (runningActivity.equals(LogPagerFragment.class.getName())) {
                alertIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOG);
            } else if (runningActivity.equals(LoginPagerFragment.class.getName())) {
                alertIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOGIN);
            } else if (runningActivity.equals(IoTPagerFragment.class.getName())) {
                alertIntent = new Intent(Constants.APP_ID + Constants.INTENT_IOT);
            } else if (runningActivity.equals(ProfilesActivity.class.getName())) {
                alertIntent = new Intent(Constants.APP_ID + Constants.INTENT_PROFILES);
            } else {
                return;
            }

            if (messageText != null) {
                alertIntent.putExtra(Constants.INTENT_DATA, Constants.ALERT_EVENT);
                alertIntent.putExtra(Constants.INTENT_DATA_MESSAGE, d.getString("text"));
                context.sendBroadcast(alertIntent);
            }
        }
    }
}

From source file:org.wso2.carbon.connector.integration.test.quickbooks.QuickbooksConnectorIntegrationTest.java

/**
 * Positive test case for createAccount method with mandatory parameters.
 *///from  w  ww  .  j  a  v  a 2s.  co m
@Test(priority = 1, description = "quickbooks {createAccount} integration test with mandatory parameters.")
public void testCreateAccountWithMandatoryParameters() throws IOException, JSONException {

    esbRequestHeadersMap.put("Action", "urn:createAccount");

    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_createAccount_mandatory.json");

    JSONObject esbResponseObject = esbRestResponse.getBody().getJSONObject("Account");
    String accountId = esbResponseObject.getString("Id");
    connectorProperties.put("expenseAccountRef", accountId);

    String apiEndPoint = connectorProperties.getProperty("apiUrl") + "/v3/company/" + companyId + "/account/"
            + accountId;
    String OAuthHeader = getOAuthHeader("GET", apiEndPoint);
    apiRequestHeadersMap.put("Authorization", OAuthHeader);

    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);

    JSONObject apiResponseObject = apiRestResponse.getBody().getJSONObject("Account");

    Assert.assertEquals(connectorProperties.getProperty("accountNameMandatory"),
            apiResponseObject.getString("Name"));
    Assert.assertEquals(esbResponseObject.getJSONObject("MetaData").getString("CreateTime"),
            apiResponseObject.getJSONObject("MetaData").getString("CreateTime"));

}