List of usage examples for org.json JSONObject length
public int length()
From source file:org.wso2.carbon.connector.integration.test.spotify.SpotifyConnectorIntegrationTest.java
/** * Mandatory parameter test case for getSeveralAlbums method. */// w ww . j av a 2 s . c o m @Test(enabled = true, groups = { "wso2.esb" }, description = "spotify {getSeveralAlbums} integration test with mandatory parameter.") public void testGetSeveralAlbumsWithMandatoryParameter() throws Exception { String jsonRequestFilePath = pathToRequestsDirectory + "getSeveralAlbums_Mandatory.txt"; String methodName = "spotify"; final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath); final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml"; proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath))); String modifiedJsonString = String.format(jsonString, spotifyConnectorProperties.getProperty("albumId1") + "," + spotifyConnectorProperties.getProperty("albumId2")); JSONObject jsonResponse; try { jsonResponse = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName), modifiedJsonString); Assert.assertTrue(jsonResponse.length() > 0); } finally { proxyAdmin.deleteProxy(methodName); } }
From source file:org.wso2.carbon.connector.integration.test.spotify.SpotifyConnectorIntegrationTest.java
/** * Mandatory parameter test case for getAnAlbumsTracks method. *///w w w .j a v a 2s . com @Test(enabled = true, groups = { "wso2.esb" }, description = "spotify {getAnAlbumsTracks} integration test with mandatory parameter.") public void testGetAnAlbumsTracksWithMandatoryParameter() throws Exception { String jsonRequestFilePath = pathToRequestsDirectory + "getAnAlbumsTracks_Mandatory.txt"; String methodName = "spotify"; final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath); final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml"; proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath))); String modifiedJsonString = String.format(jsonString, spotifyConnectorProperties.getProperty("albumId1")); JSONObject jsonResponse; try { jsonResponse = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName), modifiedJsonString); Assert.assertTrue(jsonResponse.length() > 0); } finally { proxyAdmin.deleteProxy(methodName); } }
From source file:org.wso2.carbon.connector.integration.test.spotify.SpotifyConnectorIntegrationTest.java
/** * Mandatory parameter test case for searchForAnItem method. *//* w w w.j av a 2s . co m*/ @Test(enabled = true, groups = { "wso2.esb" }, description = "spotify {searchForAnItem} integration test with mandatory parameter.") public void testSearchForAnItemWithMandatoryParameter() throws Exception { String jsonRequestFilePath = pathToRequestsDirectory + "searchForAnItem_Mandatory.txt"; String methodName = "spotify"; final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath); final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml"; proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath))); String modifiedJsonString = String.format(jsonString, spotifyConnectorProperties.getProperty("searchQueryForArtist")); JSONObject jsonResponse; try { jsonResponse = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName), modifiedJsonString); Assert.assertTrue(jsonResponse.length() > 0); } finally { proxyAdmin.deleteProxy(methodName); } }
From source file:org.wso2.carbon.connector.integration.test.spotify.SpotifyConnectorIntegrationTest.java
/** * Mandatory parameter test case for getAListUsersPlaylists method. */// ww w . j av a2s . co m @Test(enabled = true, groups = { "wso2.esb" }, description = "spotify {getAListUsersPlaylists} integration test with mandatory parameter.") public void testGetAListUsersPlaylistsMandatoryParameter() throws Exception { String jsonRequestFilePath = pathToRequestsDirectory + "getAListUsersPlaylists_Mandatory.txt"; String methodName = "spotify"; final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath); String modifiedJsonString = String.format(jsonString, spotifyConnectorProperties.getProperty("clientId"), spotifyConnectorProperties.getProperty("clientSecret"), spotifyConnectorProperties.getProperty("grantType"), spotifyConnectorProperties.getProperty("refreshToken"), spotifyConnectorProperties.getProperty("userId")); final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml"; proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath))); JSONObject jsonResponse; try { jsonResponse = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName), modifiedJsonString); Assert.assertTrue(jsonResponse.length() > 0); } finally { proxyAdmin.deleteProxy(methodName); } }
From source file:com.polychrom.cordova.ActionBarPlugin.java
@Override public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { if (!plugin_actions.contains(action)) { return false; }// w w w .j a v a2s. c o m final Activity ctx = (Activity) cordova; if ("isAvailable".equals(action)) { JSONObject result = new JSONObject(); result.put("value", ctx.getWindow().hasFeature(Window.FEATURE_ACTION_BAR)); callbackContext.success(result); return true; } final ActionBar bar = ctx.getActionBar(); if (bar == null) { Window window = ctx.getWindow(); if (!window.hasFeature(Window.FEATURE_ACTION_BAR)) { callbackContext .error("ActionBar feature not available, Window.FEATURE_ACTION_BAR must be enabled!"); } else { callbackContext.error("Failed to get ActionBar"); } return true; } if (menu == null) { callbackContext.error("Options menu not initialised"); return true; } final StringBuffer error = new StringBuffer(); JSONObject result = new JSONObject(); if ("isShowing".equals(action)) { result.put("value", bar.isShowing()); } else if ("getHeight".equals(action)) { result.put("value", bar.getHeight()); } else if ("getDisplayOptions".equals(action)) { result.put("value", bar.getDisplayOptions()); } else if ("getNavigationMode".equals(action)) { result.put("value", bar.getNavigationMode()); } else if ("getSelectedNavigationItem".equals(action)) { result.put("value", bar.getSelectedNavigationIndex()); } else if ("getSubtitle".equals(action)) { result.put("value", bar.getSubtitle()); } else if ("getTitle".equals(action)) { result.put("value", bar.getTitle()); } else { try { JSONException exception = new Runnable() { public JSONException exception = null; public void run() { try { // This is a bit of a hack (should be specific to the request, not global) bases = new String[] { removeFilename(webView.getOriginalUrl()), removeFilename(webView.getUrl()) }; if ("show".equals(action)) { bar.show(); } else if ("hide".equals(action)) { bar.hide(); } else if ("setMenu".equals(action)) { if (args.isNull(0)) { error.append("menu can not be null"); return; } menu_definition = args.getJSONArray(0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ctx.invalidateOptionsMenu(); } } else if ("setTabs".equals(action)) { if (args.isNull(0)) { error.append("menu can not be null"); return; } bar.removeAllTabs(); tab_callbacks.clear(); if (!buildTabs(bar, args.getJSONArray(0))) { error.append("Invalid tab bar definition"); } } else if ("setDisplayHomeAsUpEnabled".equals(action)) { if (args.isNull(0)) { error.append("showHomeAsUp can not be null"); return; } bar.setDisplayHomeAsUpEnabled(args.getBoolean(0)); } else if ("setDisplayOptions".equals(action)) { if (args.isNull(0)) { error.append("options can not be null"); return; } final int options = args.getInt(0); bar.setDisplayOptions(options); } else if ("setDisplayShowHomeEnabled".equals(action)) { if (args.isNull(0)) { error.append("showHome can not be null"); return; } bar.setDisplayShowHomeEnabled(args.getBoolean(0)); } else if ("setDisplayShowTitleEnabled".equals(action)) { if (args.isNull(0)) { error.append("showTitle can not be null"); return; } bar.setDisplayShowTitleEnabled(args.getBoolean(0)); } else if ("setDisplayUseLogoEnabled".equals(action)) { if (args.isNull(0)) { error.append("useLogo can not be null"); return; } bar.setDisplayUseLogoEnabled(args.getBoolean(0)); } else if ("setHomeButtonEnabled".equals(action)) { if (args.isNull(0)) { error.append("enabled can not be null"); return; } bar.setHomeButtonEnabled(args.getBoolean(0)); } else if ("setIcon".equals(action)) { if (args.isNull(0)) { error.append("icon can not be null"); return; } Drawable drawable = getDrawableForURI(args.getString(0)); bar.setIcon(drawable); } else if ("setListNavigation".equals(action)) { JSONArray items = null; if (args.isNull(0) == false) { items = args.getJSONArray(0); } navigation_adapter.setItems(items); bar.setListNavigationCallbacks(navigation_adapter, navigation_listener); } else if ("setLogo".equals(action)) { if (args.isNull(0)) { error.append("logo can not be null"); return; } Drawable drawable = getDrawableForURI(args.getString(0)); bar.setLogo(drawable); } else if ("setNavigationMode".equals(action)) { if (args.isNull(0)) { error.append("mode can not be null"); return; } final int mode = args.getInt(0); bar.setNavigationMode(mode); } else if ("setSelectedNavigationItem".equals(action)) { if (args.isNull(0)) { error.append("position can not be null"); return; } bar.setSelectedNavigationItem(args.getInt(0)); } else if ("setSubtitle".equals(action)) { if (args.isNull(0)) { error.append("subtitle can not be null"); return; } bar.setSubtitle(args.getString(0)); } else if ("setTitle".equals(action)) { if (args.isNull(0)) { error.append("title can not be null"); return; } bar.setTitle(args.getString(0)); } } catch (JSONException e) { exception = e; } finally { synchronized (this) { this.notify(); } } } // Run task synchronously { synchronized (this) { ctx.runOnUiThread(this); this.wait(); } } }.exception; if (exception != null) { throw exception; } } catch (InterruptedException e) { error.append("Function interrupted on UI thread"); } } if (error.length() == 0) { if (result.length() > 0) { callbackContext.success(result); } else { callbackContext.success(); } } else { callbackContext.error(error.toString()); } return true; }
From source file:it.iziozi.iziozi.gui.IORemoteImageSearchActivity.java
private void searchImages(String queryString) { mRingProgressDialog = ProgressDialog.show(this, getString(R.string.please_wait), getString(R.string.search_in_progress), true); mPictograms = new ArrayList<IOPictogram>(); SharedPreferences prefs = getSharedPreferences(IOApplication.APPLICATION_NAME, Context.MODE_PRIVATE); prefs.getString(IOApplication.APPLICATION_LOCALE, Locale.getDefault().getLanguage()); RequestParams params = new RequestParams(); params.put("q", queryString); params.put("lang", Locale.getDefault().getLanguage()); IOApiClient.get("pictures", params, new JsonHttpResponseHandler() { @Override/*from www.j a v a 2s .c o m*/ public void onStart() { super.onStart(); Log.d("http debug", getRequestURI().toString()); } @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); //something went wrong Toast.makeText(getApplicationContext(), getString(R.string.unexpected_response), Toast.LENGTH_SHORT) .show(); } @Override public void onFinish() { super.onFinish(); mRingProgressDialog.cancel(); } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); //Correct response int iter = response.length(); if (iter == 0) { mEmptyTextView.setVisibility(View.VISIBLE); } else { for (int i = 0; i < iter; i++) { try { JSONObject jsonObject = response.getJSONObject(i); IOPictogram pictogram = new IOPictogram(); pictogram.setId(jsonObject.getInt("id")); pictogram.setFilePath(jsonObject.getString("file")); pictogram.setUrl(jsonObject.getString("deepurl")); String text = jsonObject.getString("text"); pictogram.setDescription( text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase()); //TODO: add type or category mPictograms.add(pictogram); } catch (JSONException e) { e.printStackTrace(); } RemoteImagesGridAdapter gridAdapter = (RemoteImagesGridAdapter) mGridView.getAdapter(); gridAdapter.notifyDataSetChanged(); gridAdapter.notifyDataSetInvalidated(); } } } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); //Timeout, 500, no connection Toast.makeText(getApplicationContext(), getString(R.string.request_error), Toast.LENGTH_SHORT) .show(); } }); }
From source file:org.collectionspace.chain.csp.persistence.services.GenericStorage.java
/** * Get a mini view of the record// w w w. ja v a2 s .c om * Currently used for relatedObj relatedProc Find&Edit and Search * this needs to be refactored as the 4 areas have different data set needs * * @param cache * @param creds * @param filePath * @param extra - used to define which subset of data to use expects related|terms|search|list * @param cachelistitem * @param thisr * @param view_good * @param xxx_view_deurn * @param view_search_optional * @param view_merge * @param view_useCsid * @return * @throws ExistException * @throws UnimplementedException * @throws UnderlyingStorageException * @throws JSONException */ // CSPACE-5988: Allow maps to be passed as parameters, instead of using instance variables. public JSONObject miniViewRetrieveJSON(CSPRequestCache cache, CSPRequestCredentials creds, String filePath, String extra, String cachelistitem, Record thisr, Map<String, String> view_good, Set<String> xxx_view_deurn, Set<String> view_search_optional, Map<String, List<String>> view_merge, Map<String, List<String>> view_useCsid) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { if (cachelistitem == null) { cachelistitem = "/" + thisr.getServicesURL() + "/" + filePath; } if (!cachelistitem.startsWith("/")) { cachelistitem = "/" + cachelistitem; } JSONObject out = new JSONObject(); JSONObject summarylist = new JSONObject(); String summarylistname = "summarylist_"; if (!extra.equals("")) { summarylistname = extra + "_"; } Set<String> to_get = new HashSet<String>(view_good.keySet()); // Try to fullfil from gleaned info //gleaned is info that everytime we read a record we cache certain parts of it for (String fieldname : view_good.keySet()) { //only get the info that is needed String name = fieldname; if (!name.startsWith(summarylistname) && !name.equals("summary") && !name.equals("number")) { to_get.remove(fieldname); continue; } String gleaned = null; String good = view_good.get(fieldname); if (view_merge.containsKey(fieldname)) { List<String> mergeids = view_merge.get(fieldname); for (String id : mergeids) { if (id == null) continue; //iterate for merged ids gleaned = getGleanedValue(cache, cachelistitem, id); if (gleaned != null && gleaned != "") { //if find value stop break; } } } else if (view_useCsid.containsKey(fieldname)) { List<String> useStrings = view_useCsid.get(fieldname); String useField = useStrings.get(0); String useCsidPattern = useStrings.get(1); String useCsid = getGleanedValue(cache, cachelistitem, useField); if (useCsid != null) gleaned = XmlJsonConversion.csid_value(useCsid, useCsidPattern, conn.getIMSBase()); } else { gleaned = getGleanedValue(cache, cachelistitem, good); } if (gleaned == null) { // If the field was optional, but we go no value, go ahead and remove it // from the to_get set, so we do not fan out below. if (view_search_optional.contains(good)) { to_get.remove(fieldname); } continue; } if (xxx_view_deurn.contains(good)) gleaned = xxx_deurn(gleaned); if (name.startsWith(summarylistname)) { // The optionals, even though they are tied to individual views, put // values at the top level, and not in the summary. if (view_search_optional.contains(good)) { out.put(good, gleaned); } else { name = name.substring(summarylistname.length()); summarylist.put(name, gleaned); } } else { out.put(fieldname, gleaned); } to_get.remove(fieldname); } //check summary and number against docNumber docName if (to_get.contains("summary")) { String gleaned = getGleanedValue(cache, cachelistitem, "docName"); if (gleaned != null) { String good = view_good.get("summary"); if (xxx_view_deurn.contains(good)) gleaned = xxx_deurn(gleaned); out.put("summary", gleaned); to_get.remove("summary"); } } //check summary and number against docNumber docName if (to_get.contains("number")) { String gleaned = getGleanedValue(cache, cachelistitem, "docNumber"); if (gleaned != null) { String good = view_good.get("number"); if (xxx_view_deurn.contains(good)) gleaned = xxx_deurn(gleaned); out.put("number", gleaned); to_get.remove("number"); } } // Do a full request only if values in list of fields returned != list from cspace-config if (to_get.size() > 0) { if (log.isInfoEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("Fanning out on cachelistitem: ["); sb.append(cachelistitem); sb.append("] Fields: ["); for (String fieldname : to_get) { sb.append(fieldname); sb.append(" "); } sb.append("]"); log.info(sb.toString()); } JSONObject data = simpleRetrieveJSON(creds, cache, null, cachelistitem, thisr); for (String fieldname : to_get) { String good = view_good.get(fieldname); String value = null; if (view_merge.containsKey(fieldname)) { List<String> mergeids = view_merge.get(fieldname); for (String id : mergeids) { if (id == null) continue; value = JSONUtils.checkKey(data, id); //iterate for merged ids if (value != null && value != "") { //if find value stop break; } } } else if (view_useCsid.containsKey(fieldname)) { List<String> useStrings = view_useCsid.get(fieldname); String useField = useStrings.get(0); String useCsidPattern = useStrings.get(1); String useCsid = JSONUtils.checkKey(data, useField); if (useCsid != null) { value = XmlJsonConversion.csid_value(useCsid, useCsidPattern, conn.getIMSBase()); } } else { value = JSONUtils.checkKey(data, good); } //this might work with repeat objects if (value != null) { String vkey = fieldname; if (xxx_view_deurn.contains(good)) value = xxx_deurn(value); if (vkey.startsWith(summarylistname)) { String name = vkey.substring(summarylistname.length()); summarylist.put(name, value); } else { out.put(vkey, value); } } else { String vkey = fieldname; if (vkey.startsWith(summarylistname)) { String name = vkey.substring(summarylistname.length()); summarylist.put(name, ""); } else { out.put(vkey, ""); } } } } if (summarylist.length() > 0) { out.put("summarylist", summarylist); } return out; }
From source file:net.oauth.consumer.OAuth2Consumer.java
private synchronized Map<String, String> parseJSONObject(JSONObject json) throws JSONException { Map<String, String> parameters = null; if (json != null && json.length() > 0) { parameters = new LinkedHashMap<String, String>(); @SuppressWarnings("unchecked") Iterator<String> iter = json.keys(); if (iter != null) { while (iter.hasNext()) { String key = iter.next(); parameters.put(key, json.getString(key)); }//from w w w. j a va2 s .co m } } return parameters; }
From source file:org.dasein.cloud.joyent.compute.Dataset.java
private @Nullable MachineImage toMachineImage(@Nullable JSONObject json) throws CloudException { if (json == null) { return null; }// ww w . j av a2 s.co m String regionId = getContext().getRegionId(); if (regionId == null) { throw new CloudException("No region ID was specified for this request"); } String imageId = null, name = null, description = null, version = null, owner = "--joyent--"; Architecture architecture = Architecture.I64; Platform platform = Platform.UNKNOWN; long created = 0L; Boolean isPublic = null; try { if (json.has("id")) { imageId = json.getString("id"); } if (json.has("name")) { name = json.getString("name"); } if (json.has("description")) { description = json.getString("description"); } if (json.has("os")) { String os = (name == null ? json.getString("os") : name + " " + json.getString("os")); platform = Platform.guess(os); if (os.contains("32")) { architecture = Architecture.I32; } } if (json.has("created")) { created = getProvider().parseTimestamp(json.getString("created")); } if (json.has("version")) { version = json.getString("version"); name = name + ":" + version; } if (json.has("public")) { isPublic = json.getBoolean("public"); owner = isPublic ? "--joyent--" : getContext().getAccountNumber(); } if (json.has("requirements")) { JSONObject requirements = json.getJSONObject("requirements"); if (requirements.length() > 0) { // TODO: Allow image requirements in MachineImage // MachineImage does not currently allow requirements to be communicated, // therefore we will not be able to satisfy them. return null; } } } catch (JSONException e) { throw new CloudException(e); } if (imageId == null) { return null; } if (name == null) { name = imageId; } if (description == null) { description = name + " (" + platform + ") [#" + imageId + "]"; } //old version only supported public images and did not return owner attribute final MachineImage machineImage = MachineImage.getMachineImageInstance(owner, regionId, imageId, MachineImageState.ACTIVE, name, description, architecture, platform).createdAt(created); if (isPublic != null) { machineImage.setTag("public", String.valueOf(isPublic)); if (isPublic) { machineImage.sharedWithPublic(); } } return machineImage; }
From source file:com.BreakingBytes.SifterReader.SifterReader.java
private String getFilterSlug() { String projDetailURL = new String(); int issuesPerPage = IssuesActivity.MAX_PER_PAGE; JSONArray status = new JSONArray(); JSONArray priority = new JSONArray(); int numStatuses; int numPriorities; boolean[] filterStatus; boolean[] filterPriority; try {// ww w .ja va 2 s . c om JSONObject filters = mSifterHelper.getFiltersFile(); if (filters.length() == 0) return new String(); issuesPerPage = filters.getInt(IssuesActivity.PER_PAGE); status = filters.getJSONArray(IssuesActivity.STATUS); priority = filters.getJSONArray(IssuesActivity.PRIORITY); numStatuses = status.length(); numPriorities = priority.length(); filterStatus = new boolean[numStatuses]; filterPriority = new boolean[numPriorities]; for (int i = 0; i < numStatuses; i++) filterStatus[i] = status.getBoolean(i); for (int i = 0; i < numPriorities; i++) filterPriority[i] = priority.getBoolean(i); } catch (Exception e) { e.printStackTrace(); mSifterHelper.onException(e.toString()); return new String(); } projDetailURL = "?" + IssuesActivity.PER_PAGE + "=" + issuesPerPage; projDetailURL += "&" + IssuesActivity.GOTO_PAGE + "=1"; JSONObject statuses = new JSONObject(); JSONObject priorities = new JSONObject(); JSONArray statusNames = new JSONArray(); JSONArray priorityNames = new JSONArray(); try { JSONObject sifterJSONObject = mSifterHelper.getSifterFilters(); statuses = sifterJSONObject.getJSONObject(IssuesActivity.STATUSES); priorities = sifterJSONObject.getJSONObject(IssuesActivity.PRIORITIES); statusNames = statuses.names(); priorityNames = priorities.names(); } catch (Exception e) { e.printStackTrace(); mSifterHelper.onException(e.toString()); return new String(); } try { String filterSlug = "&s="; for (int i = 0; i < numStatuses; i++) { if (filterStatus[i]) filterSlug += String.valueOf(statuses.getInt(statusNames.getString(i))) + "-"; } if (filterSlug.length() > 3) { filterSlug = filterSlug.substring(0, filterSlug.length() - 1); projDetailURL += filterSlug; } filterSlug = "&p="; for (int i = 0; i < numPriorities; i++) { if (filterPriority[i]) filterSlug += String.valueOf(priorities.getInt(priorityNames.getString(i))) + "-"; } if (filterSlug.length() > 3) { filterSlug = filterSlug.substring(0, filterSlug.length() - 1); projDetailURL += filterSlug; } } catch (JSONException e) { e.printStackTrace(); mSifterHelper.onException(e.toString()); return new String(); } return projDetailURL; }