List of usage examples for org.json JSONObject getString
public String getString(String key) throws JSONException
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 a2s. c o 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 {// w w w . java 2 s.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 promptLogin(final JSONObject loginService, final JSONObject responseData) { runOnUiThread(new Runnable() { public void run() { try { String type = loginService.getString("type"); //there was a login error. login again if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_NORMAL)) { //prompt for username and password and retry: promptUsernamePassword(loginService, responseData, false, null); } else if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_KEY)) { promptUsernamePassword(loginService, responseData, true, loginService.getString("description")); } else if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_PRESS2LOGIN)) { //prompt for username and password and retry: int countdown = loginService.has("login_timeout") ? loginService.getInt("login_timeout") : 15;//from w ww. j a va 2 s.com final AlertDialog alertDialog = new AlertDialog.Builder(DevicesActivity.this).create(); alertDialog.setTitle(loginService.getString("description")); alertDialog.setCancelable(false); alertDialog.setCanceledOnTouchOutside(false); alertDialog.setMessage(loginService.getString("description") + "\n" + "Attempting to login again in " + countdown + " seconds..."); alertDialog.show(); // new CountDownTimer(countdown * 1000, 1000) { @Override public void onTick(long millisUntilFinished) { try { alertDialog.setMessage(loginService.getString("description") + "\n" + "Attempting to login again in " + millisUntilFinished / 1000 + " seconds..."); } catch (JSONException e) { } } @Override public void onFinish() { alertDialog.dismiss(); new Thread(new Runnable() { public void run() { try { JSONArray services = new JSONArray(); services.put(loginService); responseData.put("services", services); WeaverSdkApi.servicesSet(DevicesActivity.this, responseData); } catch (JSONException e) { } } }).start(); } }.start(); } } catch (JSONException e) { e.printStackTrace(); } } }); }
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 ww .j a v a 2 s. co 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 .ja v a2s . co 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:com.github.mhendred.face4j.model.RemovedTag.java
public RemovedTag(final JSONObject jObj) throws JSONException { this.removed_tid = jObj.getString("removed_tid"); this.detected_tid = jObj.getString("detected_tid"); }
From source file:org.wso2.carbon.connector.integration.test.quickbooks.QuickbooksConnectorIntegrationTest.java
/** * Positive test case for createAccount method with mandatory parameters. *//* w w w.j ava2 s. c o 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")); }
From source file:org.wso2.carbon.connector.integration.test.quickbooks.QuickbooksConnectorIntegrationTest.java
/** * Positive test case for createAccount method with optional parameters. *//*from w w w . ja va2 s . c om*/ @Test(priority = 1, description = "quickbooks {createAccount} integration test with optional parameters.") public void testCreateAccountWithOptionalParameters() throws IOException, JSONException { esbRequestHeadersMap.put("Action", "urn:createAccount"); RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_createAccount_optional.json"); JSONObject esbResponseObject = esbRestResponse.getBody().getJSONObject("Account"); String accountId = esbResponseObject.getString("Id"); connectorProperties.put("bankAccoutId", 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("accountNameOptional"), apiResponseObject.getString("Name")); Assert.assertEquals("LKR", apiResponseObject.getJSONObject("CurrencyRef").getString("value")); Assert.assertEquals("Savings", apiResponseObject.getString("AccountSubType")); Assert.assertEquals("Test description", apiResponseObject.getString("Description")); }
From source file:org.wso2.carbon.connector.integration.test.quickbooks.QuickbooksConnectorIntegrationTest.java
/** * Positive test case for createCustomer method with mandatory parameters. *///from w ww .j a v a 2 s . c om @Test(priority = 1, description = "quickbooks {createCustomer} integration test with mandatory parameters.") public void testCreateCustomerWithMandatoryParameters() throws IOException, JSONException { esbRequestHeadersMap.put("Action", "urn:createCustomer"); RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_createCustomer_mandatory.json"); JSONObject esbResponseObject = esbRestResponse.getBody().getJSONObject("Customer"); String customerId = esbResponseObject.getString("Id"); connectorProperties.setProperty("customerId", customerId); String apiEndPoint = connectorProperties.getProperty("apiUrl") + "/v3/company/" + companyId + "/customer/" + customerId; String OAuthHeader = getOAuthHeader("GET", apiEndPoint); apiRequestHeadersMap.put("Authorization", OAuthHeader); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap); JSONObject apiResponseObject = apiRestResponse.getBody().getJSONObject("Customer"); Assert.assertEquals(connectorProperties.getProperty("customerNameMandatory"), apiResponseObject.getString("FamilyName")); Assert.assertEquals(esbResponseObject.getJSONObject("MetaData").getString("CreateTime"), apiResponseObject.getJSONObject("MetaData").getString("CreateTime")); }
From source file:org.wso2.carbon.connector.integration.test.quickbooks.QuickbooksConnectorIntegrationTest.java
/** * Positive test case for createCustomer method with optional parameters. *///from w ww . j a va 2 s . c om @Test(priority = 1, description = "quickbooks {createCustomer} integration test with optional parameters.") public void testCreateCustomerWithOptionalParameters() throws IOException, JSONException { esbRequestHeadersMap.put("Action", "urn:createCustomer"); RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_createCustomer_optional.json"); JSONObject esbResponseObject = esbRestResponse.getBody().getJSONObject("Customer"); String customerId = esbResponseObject.getString("Id"); connectorProperties.put("customerRef", customerId); String apiEndPoint = connectorProperties.getProperty("apiUrl") + "/v3/company/" + companyId + "/customer/" + customerId; String OAuthHeader = getOAuthHeader("GET", apiEndPoint); apiRequestHeadersMap.put("Authorization", OAuthHeader); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap); JSONObject apiResponseObject = apiRestResponse.getBody().getJSONObject("Customer"); Assert.assertEquals(connectorProperties.getProperty("customerNameOptional"), apiResponseObject.getString("FamilyName")); Assert.assertEquals("+947111", apiResponseObject.getJSONObject("PrimaryPhone").getString("FreeFormNumber")); Assert.assertEquals("WSO2", apiResponseObject.getString("CompanyName")); }