List of usage examples for org.json JSONArray length
public int length()
From source file:com.github.koraktor.steamcondenser.community.AppNews.java
/** * Loads the news for the given game with the given restrictions * * @param appId The unique Steam Application ID of the game (e.g. * <code>440</code> for Team Fortress 2). See * http://developer.valvesoftware.com/wiki/Steam_Application_IDs for * all application IDs//w w w . j a va2 s. c o m * @param count The maximum number of news to load (default: 5). There's no * reliable way to load all news. Use really a really great number * instead * @param maxLength The maximum content length of the news (default: nil). * If a maximum length is defined, the content of the news will only * be at most <code>maxLength</code> characters long plus an * ellipsis * @return A list of news for the specified game with the given options * @throws WebApiException if a request to Steam's Web API fails */ public static List<AppNews> getNewsForApp(int appId, int count, Integer maxLength) throws WebApiException { try { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("appid", appId); params.put("count", count); params.put("maxlength", maxLength); JSONObject data = new JSONObject(WebApi.getJSON("ISteamNews", "GetNewsForApp", 2, params)); List<AppNews> newsItems = new ArrayList<AppNews>(); JSONArray newsData = data.getJSONObject("appnews").getJSONArray("newsitems"); for (int i = 0; i < newsData.length(); i++) { newsItems.add(new AppNews(appId, newsData.getJSONObject(i))); } return newsItems; } catch (JSONException e) { throw new WebApiException("Could not parse JSON data.", e); } }
From source file:com.abeo.tia.noordin.AddCaseStep2of4.java
public void dropdownBankDeveloperSolicitor() { RequestParams params = null;/*from ww w. j a v a 2s .com*/ params = new RequestParams(); RestService.post(METHOD_PROPERTY_BDS_DROPDOWN, params, new BaseJsonHttpResponseHandler<String>() { @Override public void onFailure(int arg0, Header[] arg1, Throwable arg2, String arg3, String arg4) { // TODO Auto-generated method stub System.out.println(arg3); } @Override public void onSuccess(int arg0, Header[] arg1, String arg2, String arg3) { // TODO Auto-generated method stub System.out.println("Property Activity GetDropdown Success Details "); try { // Create new list jsonlistBank = new ArrayList<HashMap<String, String>>(); jsonlistDeveloper = new ArrayList<HashMap<String, String>>(); jsonlistSolicitor = new ArrayList<HashMap<String, String>>(); jsonResponse = new JSONObject(arg2); JSONArray jsonBank = jsonResponse.getJSONArray("Bank"); for (int j = 0; j < jsonBank.length(); j++) { JSONObject bank = jsonBank.getJSONObject(j); id_b = bank.getString("BankCode").toString(); name_b = bank.getString("BankName").toString(); // SEND JSON DATA INTO SPINNER TITLE LIST HashMap<String, String> bankList = new HashMap<String, String>(); // Send JSON Data to list activity System.out.println("SEND JSON BANK LIST"); bankList.put("Id_T", id_b); System.out.println(name); bankList.put("Name_T", name_b); System.out.println(name); System.out.println(" END SEND JSON BANK LIST"); jsonlistBank.add(bankList); System.out.println("JSON BANK LIST"); System.out.println(jsonlistProject); } // Spinner set Array Data in Drop down sAdapBANK = new SimpleAdapter(AddCaseStep2of4.this, jsonlistBank, R.layout.spinner_item, new String[] { "Id_T", "Name_T" }, new int[] { R.id.Id, R.id.Name }); spinnerpropertyLSTCHG_BANKNAME.setAdapter(sAdapBANK); for (int j = 0; j < jsonlistBank.size(); j++) { if (jsonlistBank.get(j).get("Name_T").equals(bankDetailResponse)) { spinnerpropertyLSTCHG_BANKNAME.setSelection(j); break; } } JSONArray jsonDeveloper = jsonResponse.getJSONArray("Developer"); for (int j = 0; j < jsonDeveloper.length(); j++) { JSONObject dev = jsonDeveloper.getJSONObject(j); id = dev.getString("DevCode").toString(); name = dev.getString("DevName").toString(); // SEND JSON DATA INTO SPINNER TITLE LIST HashMap<String, String> devList = new HashMap<String, String>(); // Send JSON Data to list activity System.out.println("SEND JSON DEV LIST"); devList.put("Id_B", id); System.out.println(name); devList.put("Name_B", name); System.out.println(name); System.out.println(" END SEND JSON DEV LIST"); jsonlistDeveloper.add(devList); System.out.println("JSON DEV LIST"); System.out.println(jsonlistDeveloper); } // Spinner set Array Data in Drop down sAdapDEV = new SimpleAdapter(AddCaseStep2of4.this, jsonlistDeveloper, R.layout.spinner_item, new String[] { "Id_B", "Name_B" }, new int[] { R.id.Id, R.id.Name }); spinnerpropertyDEVELOPER.setAdapter(sAdapDEV); for (int j = 0; j < jsonlistDeveloper.size(); j++) { if (jsonlistDeveloper.get(j).get("Id_B").equals(developerCodeResponse)) { spinnerpropertyDEVELOPER.setSelection(j); break; } } JSONArray jsonSolicitor = jsonResponse.getJSONArray("Solicitor"); for (int j = 0; j < jsonSolicitor.length(); j++) { JSONObject solic = jsonSolicitor.getJSONObject(j); id = solic.getString("SoliCode").toString(); name = solic.getString("SoliName").toString(); // SEND JSON DATA INTO SPINNER TITLE LIST HashMap<String, String> solicList = new HashMap<String, String>(); // Send JSON Data to list activity System.out.println("SEND JSON SOLICITOR LIST"); solicList.put("Id_T", id); System.out.println(name); solicList.put("Name_T", name); System.out.println(name); System.out.println(" END SEND JSON SOLICITOR LIST"); jsonlistSolicitor.add(solicList); System.out.println("JSON SOLICITOR LIST"); System.out.println(jsonlistSolicitor); } // Spinner set Array Data in Drop down sAdapSOLIC = new SimpleAdapter(AddCaseStep2of4.this, jsonlistSolicitor, R.layout.spinner_item, new String[] { "Id_T", "Name_T" }, new int[] { R.id.Id, R.id.Name }); spinnerpropertyDEVSOLICTOR.setAdapter(sAdapSOLIC); for (int j = 0; j < jsonlistSolicitor.size(); j++) { if (jsonlistSolicitor.get(j).get("Id_T").equals(devSolictorCodeResponse)) { spinnerpropertyDEVSOLICTOR.setSelection(j); break; } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(arg2); } @Override protected String parseResponse(String arg0, boolean arg1) throws Throwable { // Get Json response System.out.println("Property GetDropdown parse Response"); System.out.println(arg0); return null; } }); }
From source file:com.goliathonline.android.kegbot.io.RemoteDrinksHandler.java
/** {@inheritDoc} */ @Override/* www. ja va 2 s. co m*/ public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver) throws JSONException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Walk document, parsing any incoming entries int drink_id = 0; JSONObject result = parser.getJSONObject("result"); JSONArray drinks = result.getJSONArray("drinks"); JSONObject drink; for (int i = 0; i < drinks.length(); i++) { if (drink_id == 0) { // && ENTRY.equals(parser.getName() // Process single spreadsheet row at a time drink = drinks.getJSONObject(i); final String drinkId = sanitizeId(drink.getString("id")); final Uri drinkUri = Drinks.buildDrinkUri(drinkId); // Check for existing details, only update when changed final ContentValues values = queryDrinkDetails(drinkUri, resolver); final long localUpdated = values.getAsLong(SyncColumns.UPDATED); final long serverUpdated = 500; //entry.getUpdated(); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "found drink " + drinkId); Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated); } if (localUpdated != KegbotContract.UPDATED_NEVER) continue; final Uri drinkKegUri = Drinks.buildKegUri(drinkId); final Uri drinkUserUri = Drinks.buildUserUri(drinkId); // Clear any existing values for this session, treating the // incoming details as authoritative. batch.add(ContentProviderOperation.newDelete(drinkUri).build()); batch.add(ContentProviderOperation.newDelete(drinkKegUri).build()); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Drinks.CONTENT_URI); builder.withValue(SyncColumns.UPDATED, serverUpdated); builder.withValue(Drinks.DRINK_ID, drinkId); // Inherit starred value from previous row if (values.containsKey(Drinks.DRINK_STARRED)) { builder.withValue(Drinks.DRINK_STARRED, values.getAsInteger(Drinks.DRINK_STARRED)); } if (drink.has("session_id")) builder.withValue(Drinks.SESSION_ID, drink.getInt("session_id")); if (drink.has("status")) builder.withValue(Drinks.STATUS, drink.getString("status")); if (drink.has("user_id")) builder.withValue(Drinks.USER_ID, drink.getString("user_id")); if (drink.has("keg_id")) builder.withValue(Drinks.KEG_ID, drink.getInt("keg_id")); if (drink.has("volume_ml")) builder.withValue(Drinks.VOLUME, drink.getDouble("volume_ml")); if (drink.has("pour_time")) builder.withValue(Drinks.POUR_TIME, drink.getString("pour_time")); // Normal session details ready, write to provider batch.add(builder.build()); // Assign kegs final int kegId = drink.getInt("keg_id"); batch.add(ContentProviderOperation.newInsert(drinkKegUri).withValue(DrinksKeg.DRINK_ID, drinkId) .withValue(DrinksKeg.KEG_ID, kegId).build()); // Assign users if (drink.has("user_id")) { final String userId = drink.getString("user_id"); batch.add(ContentProviderOperation.newInsert(drinkUserUri) .withValue(DrinksUser.DRINK_ID, drinkId).withValue(DrinksUser.USER_ID, userId).build()); } } } return batch; }
From source file:org.liberty.android.fantastischmemo.downloader.FEDirectory.java
private List<DownloadItem> retrieveList() throws Exception { List<DownloadItem> diList = new ArrayList<DownloadItem>(); String url = FE_API_DIRECTORY; String jsonString = downloaderUtils.downloadJSONString(url); JSONObject jsonObject = new JSONObject(jsonString); String status = jsonObject.getString("response_type"); Log.v(TAG, "JSON String: " + jsonString); if (!status.equals("ok")) { Log.v(TAG, "JSON String: " + jsonString); throw new IOException("Status is not OK. Status: " + status); }//from w w w . ja v a2s . com JSONArray directoryArray = jsonObject.getJSONArray("results"); /* * Each result has tags which is an array containing * tags and a string of tag group title */ for (int i = 0; i < directoryArray.length(); i++) { JSONArray tagsArray = directoryArray.getJSONObject(i).getJSONArray("tags"); for (int j = 0; j < tagsArray.length(); j++) { JSONObject jsonItem = tagsArray.getJSONObject(j); String s = jsonItem.getString("tag"); DownloadItem di = new DownloadItem(DownloadItem.ItemType.Database, s, "", ""); di.setType(DownloadItem.ItemType.Category); diList.add(di); } } return diList; }
From source file:org.brickred.socialauth.provider.HotmailImpl.java
private List<Contact> getContacts(final String url) throws Exception { Response serviceResponse;//from w ww. java2 s .c om try { serviceResponse = authenticationStrategy.executeFeed(url); } catch (Exception e) { throw new SocialAuthException("Error while getting contacts from " + url, e); } if (serviceResponse.getStatus() != 200) { throw new SocialAuthException( "Error while getting contacts from " + url + "Status : " + serviceResponse.getStatus()); } String result; try { result = serviceResponse.getResponseBodyAsString(Constants.ENCODING); } catch (Exception e) { throw new ServerDataException("Failed to get response from " + url, e); } LOG.debug("User Contacts list in JSON " + result); JSONObject resp = new JSONObject(result); List<Contact> plist = new ArrayList<Contact>(); if (resp.has("data")) { JSONArray addArr = resp.getJSONArray("data"); LOG.debug("Contacts Found : " + addArr.length()); for (int i = 0; i < addArr.length(); i++) { JSONObject obj = addArr.getJSONObject(i); Contact p = new Contact(); if (obj.has("email_hashes")) { JSONArray emailArr = obj.getJSONArray("email_hashes"); if (emailArr.length() > 0) { p.setEmailHash(emailArr.getString(0)); } } if (obj.has("name")) { p.setDisplayName(obj.getString("name")); } if (obj.has("first_name")) { p.setFirstName(obj.getString("first_name")); } if (obj.has("last_name")) { p.setLastName(obj.getString("last_name")); } if (obj.has("id")) { p.setId(obj.getString("id")); } plist.add(p); } } serviceResponse.close(); return plist; }
From source file:com.soomla.store.domain.VirtualCategory.java
/** Constructor * * Generates an instance of {@link VirtualCategory} from a JSONObject. * @param jsonObject is a JSONObject representation of the wanted {@link VirtualCategory}. * @throws JSONException/*from ww w .j a va2 s . c o m*/ */ public VirtualCategory(JSONObject jsonObject) throws JSONException { mName = jsonObject.getString(JSONConsts.CATEGORY_NAME); JSONArray goodsArr = jsonObject.getJSONArray(JSONConsts.CATEGORY_GOODSITEMIDS); for (int i = 0; i < goodsArr.length(); i++) { String goodItemId = goodsArr.getString(i); mGoodsItemIds.add(goodItemId); } }
From source file:org.dasein.cloud.benchmark.Suite.java
static public void main(String... args) throws Exception { ArrayList<Map<String, Object>> suites = new ArrayList<Map<String, Object>>(); ArrayList<Map<String, Object>> tests = new ArrayList<Map<String, Object>>(); for (String suiteFile : args) { HashMap<String, Object> suite = new HashMap<String, Object>(); ArrayList<Benchmark> benchmarks = new ArrayList<Benchmark>(); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(suiteFile))); StringBuilder json = new StringBuilder(); String line;/*from ww w.ja v a 2 s. com*/ while ((line = reader.readLine()) != null) { json.append(line); json.append("\n"); } JSONObject ob = new JSONObject(json.toString()); suite.put("name", ob.getString("name")); suite.put("description", ob.getString("description")); JSONArray benchmarkClasses = ob.getJSONArray("benchmarks"); for (int i = 0; i < benchmarkClasses.length(); i++) { String cname = benchmarkClasses.getString(i); benchmarks.add((Benchmark) Class.forName(cname).newInstance()); } JSONArray clouds = ob.getJSONArray("clouds"); for (int i = 0; i < clouds.length(); i++) { JSONObject cloud = clouds.getJSONObject(i); if (cloud.has("regions")) { JSONObject regions = cloud.getJSONObject("regions"); String[] regionIds = JSONObject.getNames(regions); if (regionIds != null) { for (String regionId : regionIds) { final JSONObject regionCfg = regions.getJSONObject(regionId); String cname = cloud.getString("providerClass"); CloudProvider provider = (CloudProvider) Class.forName(cname).newInstance(); JSONObject ctxCfg = cloud.getJSONObject("context"); ProviderContext ctx = new ProviderContext(); ctx.setEndpoint(regionCfg.getString("endpoint")); ctx.setAccountNumber(ctxCfg.getString("accountNumber")); ctx.setRegionId(regionId); if (ctxCfg.has("accessPublic")) { ctx.setAccessPublic(ctxCfg.getString("accessPublic").getBytes("utf-8")); } if (ctxCfg.has("accessPrivate")) { ctx.setAccessPrivate(ctxCfg.getString("accessPrivate").getBytes("utf-8")); } ctx.setCloudName(ctxCfg.getString("cloudName")); ctx.setProviderName(ctxCfg.getString("providerName")); if (ctxCfg.has("x509Cert")) { ctx.setX509Cert(ctxCfg.getString("x509Cert").getBytes("utf-8")); } if (ctxCfg.has("x509Key")) { ctx.setX509Key(ctxCfg.getString("x509Key").getBytes("utf-8")); } if (ctxCfg.has("customProperties")) { JSONObject p = ctxCfg.getJSONObject("customProperties"); String[] names = JSONObject.getNames(p); if (names != null) { Properties props = new Properties(); for (String name : names) { String value = p.getString(name); if (value != null) { props.put(name, value); } } ctx.setCustomProperties(props); } } provider.connect(ctx); Suite s = new Suite(benchmarks, provider); tests.add(s.runBenchmarks(regionCfg)); } } } } suite.put("benchmarks", tests); suites.add(suite); } System.out.println((new JSONArray(suites)).toString()); }
From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java
protected void performSync() { labelMap = new HashMap<String, String>(); lastSync = new Time(); preferences.recordSyncStart();/*from www . jav a2 s . co m*/ Log.i(OpencrxUtils.TAG, "Starting sync!"); try { // load user information JSONObject user = invoker.userUpdateOpencrx(); saveUserData(user); String userCrxId = user.getString("crxid_user"); Time cur = new Time(); String lastServerSync = Preferences.getStringValue(OpencrxUtilities.PREF_SERVER_LAST_SYNC); try { if (lastServerSync != null) { lastSync.parse(lastServerSync); } else { // very long time ago lastSync.set(1, 1, 1980); } } catch (TimeFormatException ex) { lastSync.set(1, 1, 1980); } String lastNotificationId = Preferences.getStringValue(OpencrxUtilities.PREF_SERVER_LAST_NOTIFICATION); String lastActivityId = Preferences.getStringValue(OpencrxUtilities.PREF_SERVER_LAST_ACTIVITY); // read dashboards updateCreators(); // read contacts updateContacts(); // read labels updateResources(userCrxId); // read activity process graph graph = invoker.getActivityProcessGraph(); ArrayList<OpencrxTaskContainer> remoteTasks = new ArrayList<OpencrxTaskContainer>(); JSONArray tasks = invoker.tasksShowListOpencrx(graph); for (int i = 0; i < tasks.length(); i++) { JSONObject task = tasks.getJSONObject(i); OpencrxTaskContainer remote = parseRemoteTask(task); // update reminder flags for incoming remote tasks to prevent annoying if (remote.task.hasDueDate() && remote.task.getValue(Task.DUE_DATE) < DateUtilities.now()) remote.task.setFlag(Task.REMINDER_FLAGS, Task.NOTIFY_AFTER_DEADLINE, false); dataService.findLocalMatch(remote); remoteTasks.add(remote); } // TODO: delete Log.i(OpencrxUtils.TAG, "Matching local to remote..."); matchLocalTasksToRemote(remoteTasks); // TODO: delete Log.i(OpencrxUtils.TAG, "Matching local to remote finished"); // TODO: delete Log.i(OpencrxUtils.TAG, "Synchronizing tasks..."); SyncData<OpencrxTaskContainer> syncData = populateSyncData(remoteTasks); try { synchronizeTasks(syncData); } finally { syncData.localCreated.close(); syncData.localUpdated.close(); } // TODO: delete Log.i(OpencrxUtils.TAG, "Synchronizing tasks finished"); cur.setToNow(); Preferences.setString(OpencrxUtilities.PREF_SERVER_LAST_SYNC, cur.format2445()); preferences.recordSuccessfulSync(); Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH); ContextManager.getContext().sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ); // store lastIds in Preferences Preferences.setString(OpencrxUtilities.PREF_SERVER_LAST_NOTIFICATION, lastNotificationId); Preferences.setString(OpencrxUtilities.PREF_SERVER_LAST_ACTIVITY, lastActivityId); labelMap = null; lastSync = null; // TODO: delete Log.i(OpencrxUtils.TAG, "Sync successfull"); } catch (IllegalStateException e) { // occurs when application was closed } catch (Exception e) { handleException("opencrx-sync", e, true); //$NON-NLS-1$ } }
From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java
/** Create a task container for the given RtmTaskSeries * @throws JSONException//from w ww .ja va 2 s . c o m * @throws IOException * @throws ApiServiceException */ private OpencrxTaskContainer parseRemoteTask(JSONObject remoteTask) throws JSONException, ApiServiceException, IOException { String resourceId = Preferences.getStringValue(OpencrxUtilities.PREF_RESOURCE_ID); String crxId = remoteTask.getString("repeating_value"); JSONArray labels = invoker.resourcesShowForTask(crxId); int secondsSpentOnTask = invoker.getSecondsSpentOnTask(crxId, resourceId); Task task = new Task(); ArrayList<Metadata> metadata = new ArrayList<Metadata>(); if (remoteTask.has("task")) remoteTask = remoteTask.getJSONObject("task"); task.setValue(Task.TITLE, ApiUtilities.decode(remoteTask.getString("title"))); task.setValue(Task.NOTES, remoteTask.getString("detailedDescription")); task.setValue(Task.CREATION_DATE, ApiUtilities.producteevToUnixTime(remoteTask.getString("time_created"), 0)); task.setValue(Task.COMPLETION_DATE, remoteTask.getInt("status") == 1 ? DateUtilities.now() : 0); task.setValue(Task.DELETION_DATE, remoteTask.getInt("deleted") == 1 ? DateUtilities.now() : 0); task.setValue(Task.ELAPSED_SECONDS, secondsSpentOnTask); task.setValue(Task.MODIFICATION_DATE, remoteTask.getLong("modifiedAt")); long dueDate = ApiUtilities.producteevToUnixTime(remoteTask.getString("deadline"), 0); if (remoteTask.optInt("all_day", 0) == 1) task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate)); else task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, dueDate)); task.setValue(Task.IMPORTANCE, 5 - remoteTask.getInt("star")); for (int i = 0; i < labels.length(); i++) { JSONObject label = labels.getJSONObject(i); Metadata tagData = new Metadata(); tagData.setValue(Metadata.KEY, OpencrxDataService.TAG_KEY); tagData.setValue(OpencrxDataService.TAG, label.getString("name")); metadata.add(tagData); } OpencrxTaskContainer container = new OpencrxTaskContainer(task, metadata, remoteTask); return container; }
From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java
/** * Read labels into label map// w w w . j av a 2 s . c om * @param userCrxId * @param dashboardId * @throws JSONException * @throws ApiServiceException * @throws IOException */ private void readLabels(JSONArray labels, String userCrxId) throws JSONException, ApiServiceException, IOException { for (int i = 0; i < labels.length(); i++) { JSONObject label = labels.getJSONObject(i); putLabelIntoCache(label); String contactId = label.optString("contact_id"); if (userCrxId.equals(contactId)) { Preferences.setString(OpencrxUtilities.PREF_RESOURCE_ID, label.getString("id")); } } }