List of usage examples for org.json JSONArray length
public int length()
From source file:org.loklak.api.iot.NOAAAlertServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Query post = RemoteAccess.evaluate(request); // manage DoS if (post.isDoS_blackout()) { response.sendError(503, "your request frequency is too high"); return;// w ww . jav a2s. c om } String content = new String(Files.readAllBytes(Paths.get(DAO.conf_dir + "/iot/scripts/counties.xml"))); try { // Conversion of the XML Layers through PERL into the required JSON for well structured XML /* <resources> <string-array name="preference_county_entries_us"> <item>Entire Country</item> </string-array> <string-array name="preference_county_entryvalues_us"> <item>https://alerts.weather.gov/cap/us.php?x=0</item> </string-array> . . . Similarly every 2 DOM elements together in <resources> constitute a pair. </resources> */ JSONObject json = XML.toJSONObject(content); PrintWriter sos = response.getWriter(); JSONObject resourceObject = json.getJSONObject("resources"); JSONArray stringArray = resourceObject.getJSONArray("string-array"); JSONObject result = new JSONObject(true); // Extract and map the itemname and the url strings /* { "item": "Entire Country", "name": "preference_county_entries_us" }, { "item": "https://alerts.weather.gov/cap/us.php?x=0", "name": "preference_county_entryvalues_us" } */ for (int i = 0; i < stringArray.length(); i += 2) { JSONObject keyJSONObject = stringArray.getJSONObject(i); JSONObject valueJSONObject = stringArray.getJSONObject(i + 1); Object kItemObj = keyJSONObject.get("item"); Object vItemObj = valueJSONObject.get("item"); // Since instances are variable, we need to check if they're Arrays or Strings // The processing for the Key : Value mappings will change for each type of instance if (kItemObj instanceof JSONArray) { if (vItemObj instanceof JSONArray) { JSONArray kArray = keyJSONObject.getJSONArray("item"); JSONArray vArray = valueJSONObject.getJSONArray("item"); for (int location = 0; location < kArray.length(); location++) { String kValue = kArray.getString(location); String vValue = vArray.getString(location); result.put(kValue, vValue); } } } else { // They are plain strings String kItemValue = keyJSONObject.getString("item"); String vItemValue = valueJSONObject.getString("item"); result.put(kItemValue, vItemValue); } } // Sample response in result has to be something like /* { "Entire Country": "https://alerts.weather.gov/cap/us.php?x=0", "Entire State": "https://alerts.weather.gov/cap/wy.php?x=0", "Autauga": "https://alerts.weather.gov/cap/wwaatmget.php?x=ALC001&y=0", "Baldwin": "https://alerts.weather.gov/cap/wwaatmget.php?x=GAC009&y=0", "Barbour": "https://alerts.weather.gov/cap/wwaatmget.php?x=WVC001&y=0", "Bibb": "https://alerts.weather.gov/cap/wwaatmget.php?x=GAC021&y=0", . . . And so on. } */ sos.print(result.toString(2)); sos.println(); } catch (IOException e) { Log.getLog().warn(e); JSONObject json = new JSONObject(true); json.put("error", "Looks like there is an error in the conversion"); json.put("type", "Error"); PrintWriter sos = response.getWriter(); sos.print(json.toString(2)); sos.println(); } }
From source file:net.willwebberley.gowertides.utils.WeatherDatabase.java
public Boolean insertWeatherData(String data, SQLiteDatabase db) { try {//from ww w . j av a 2 s . co m JSONArray jsonArray = new JSONArray(data); for (int i = 0; i < jsonArray.length(); i++) { JSONObject array = jsonArray.getJSONObject(i); JSONObject jsonObject = array.getJSONObject("weather"); long timestamp = jsonObject.getLong("timestamp"); int year = jsonObject.getInt("year"); int month = jsonObject.getInt("month"); int day = jsonObject.getInt("day"); int max_temp_c = jsonObject.getInt("max_temp_c"); int max_temp_f = jsonObject.getInt("max_temp_f"); int min_temp_c = jsonObject.getInt("min_temp_c"); int min_temp_f = jsonObject.getInt("min_temp_f"); int wind_speed_miles = jsonObject.getInt("wind_speed_miles"); int wind_speed_km = jsonObject.getInt("wind_speed_km"); String wind_direction = jsonObject.getString("wind_direction"); int wind_degree = jsonObject.getInt("wind_degree"); String icon_url = jsonObject.getString("icon_url"); String description = jsonObject.getString("weather_description"); Double precipitation = jsonObject.getDouble("precipitation"); String inS = "INSERT INTO weather VALUES(" + timestamp + "," + year + "," + month + "," + day + "," + max_temp_c + "," + max_temp_f + "," + min_temp_c + "," + min_temp_f + "," + wind_speed_miles + "," + wind_speed_km + ",'" + wind_direction + "'," + wind_degree + ",'" + icon_url + "','" + description + "'," + precipitation + ")"; db.execSQL(inS); } } catch (Exception e) { System.out.println(e); return false; } return true; }
From source file:net.willwebberley.gowertides.utils.WeatherDatabase.java
public Boolean insertSurfData(String data, SQLiteDatabase db) { /* Delete any current versions with the same request timestamps */ try {/*w w w . j av a 2s . co m*/ JSONArray jsonArray = new JSONArray(data); for (int i = 0; i < jsonArray.length(); i++) { JSONObject surf = jsonArray.getJSONObject(i); db.execSQL("DELETE FROM surf WHERE timestamp = " + surf.getLong("timestamp")); } } catch (Exception e) { System.err.println("Could not delete data"); } /* Now actually do the inserts! */ try { JSONArray jsonArray = new JSONArray(data); for (int i = 0; i < jsonArray.length(); i++) { JSONObject surf = jsonArray.getJSONObject(i); int location = surf.getInt("location"); long timestamp = surf.getLong("timestamp"); long localtime = surf.getLong("local_time"); int year = surf.getInt("year"); int month = surf.getInt("month"); int day = surf.getInt("day"); int hour = surf.getInt("hour"); int minute = surf.getInt("minute"); int faded_rating = surf.getInt("faded_rating"); int solid_rating = surf.getInt("solid_rating"); double min_surf = surf.getDouble("min_surf_height"); double abs_min_surf = surf.getDouble("abs_min_surf_height"); double max_surf = surf.getDouble("max_surf_height"); double abs_max_surf = surf.getDouble("abs_max_surf_height"); double swell_height = surf.getDouble("swell_height"); double swell_period = surf.getDouble("swell_period"); double swell_angle = surf.getDouble("swell_angle"); String swell_direction = surf.getString("swell_direction"); String swell_chart_url = surf.getString("swell_chart"); String period_chart_url = surf.getString("period_chart"); String wind_chart_url = surf.getString("wind_chart"); String pressure_chart_url = surf.getString("pressure_chart"); String sst_chart_url = surf.getString("sst_chart"); String inS = "INSERT INTO surf VALUES(" + location + "," + timestamp + "," + localtime + "," + year + "," + month + "," + day + "," + hour + "," + minute + "," + faded_rating + "," + solid_rating + "," + min_surf + "," + abs_min_surf + "," + max_surf + "," + abs_max_surf + "," + swell_height + "," + swell_period + "," + swell_angle + ",'" + swell_direction + "','" + swell_chart_url + "','" + period_chart_url + "','" + wind_chart_url + "','" + pressure_chart_url + "','" + sst_chart_url + "')"; db.execSQL(inS); } } catch (Exception e) { System.out.println(e); return false; } return true; }
From source file:com.jsonstore.api.JSONStoreFindOptions.java
/** * @exclude Used internally/*from w ww .ja v a 2 s. c o m*/ */ public JSONStoreFindOptions(JSONObject options) throws JSONException, JSONStoreInvalidSortObjectException { filter = new HashMap<String, Boolean>(); sort = new LinkedHashMap<String, SortDirection>(); String limitStr = options.optString(JSONStoreFindOptions.OPTION_LIMIT, null); if (limitStr != null) { Integer limitParse = Integer.parseInt(limitStr); setLimit(limitParse); } String offsetStr = options.optString(JSONStoreFindOptions.OPTION_OFFSET, null); if (offsetStr != null) { Integer offsetParse = Integer.parseInt(offsetStr); setOffset(offsetParse); } JSONArray sortArray = options.optJSONArray(JSONStoreFindOptions.OPTION_SORT_ARRAY); if (sortArray != null) { for (int idx = 0; idx < sortArray.length(); idx++) { JSONObject sortObject = sortArray.getJSONObject(idx); Iterator<String> keys = sortObject.keys(); String key = keys.next(); if (keys.hasNext()) { throw new JSONStoreInvalidSortObjectException( "One of the sort objects in the sort array has more than one field."); } //Parse the direction of the sort for this search field: String sortDirectionStr = sortObject.getString(key); if (sortDirectionStr.equalsIgnoreCase(DatabaseConstants.ASCENDING)) { sortBySearchFieldAscending(key); } else if (sortDirectionStr.equalsIgnoreCase(DatabaseConstants.DESCENDING)) { sortBySearchFieldDescending(key); } else { throw new JSONStoreInvalidSortObjectException( "Invalid sorting direction (ascending or descending) specified."); } } } JSONArray filterParse = options.optJSONArray(JSONStoreFindOptions.OPTION_FILTER); if (filterParse != null) { for (int idx = 0; idx < filterParse.length(); idx++) { addSearchFilter(filterParse.getString(idx)); } } }
From source file:com.facebook.share.ShareApi.java
private static void handleImagesOnAction(Bundle parameters) { // In general, graph objects are passed by reference (ID/URL). But if this is an OG Action, // we need to pass the entire values of the contents of the 'image' property, as they // contain important metadata beyond just a URL. String imageStr = parameters.getString("image"); if (imageStr != null) { try {//www . ja va 2 s . c o m // Check to see if this is an json array. Will throw if not JSONArray images = new JSONArray(imageStr); for (int i = 0; i < images.length(); ++i) { JSONObject jsonImage = images.optJSONObject(i); if (jsonImage != null) { putImageInBundleWithArrayFormat(parameters, i, jsonImage); } else { // If we don't have jsonImage we probably just have a url String url = images.getString(i); parameters.putString(String.format(Locale.ROOT, "image[%d][url]", i), url); } } parameters.remove("image"); return; } catch (JSONException ex) { // We couldn't parse the string as an array } // If the image is not in an array it might just be an single photo try { JSONObject image = new JSONObject(imageStr); putImageInBundleWithArrayFormat(parameters, 0, image); parameters.remove("image"); } catch (JSONException exception) { // The image was not in array format or a json object and can be safely passed // without modification } } }
From source file:org.brickred.socialauth.provider.MendeleyImpl.java
/** * Gets the list of followers of the user and their screen name. * //from w w w. j a va 2 s .c o m * @return List of contact objects representing Contacts. Only name, screen * name and profile URL will be available */ @Override public List<Contact> getContactList() throws Exception { if (!isVerify) { throw new SocialAuthException("Please call verifyResponse function first to get Access Token"); } String url = CONTACTS_URL; List<Contact> plist = new ArrayList<Contact>(); LOG.info("Fetching contacts from " + url); Response serviceResponse = null; try { serviceResponse = authenticationStrategy.executeFeed(url); } catch (Exception ie) { throw new SocialAuthException("Failed to retrieve the contacts from " + url, ie); } String result; try { result = serviceResponse.getResponseBodyAsString(Constants.ENCODING); } catch (Exception e) { throw new ServerDataException("Failed to get response from " + url); } try { LOG.debug("User Contacts list in json : " + result); JSONArray data = new JSONArray(result); LOG.debug("Found contacts : " + data.length()); for (int i = 0; i < data.length(); i++) { JSONObject obj = data.getJSONObject(i); Contact p = new Contact(); String name = obj.getString("name"); if (name != null) { String nameArr[] = name.split(" "); if (nameArr.length > 1) { p.setFirstName(nameArr[0]); p.setLastName(nameArr[1]); } else { p.setFirstName(obj.getString("name")); } p.setDisplayName(name); } p.setId(obj.getString("profile_id")); plist.add(p); } } catch (Exception e) { throw new ServerDataException("Failed to parse the user friends json : " + result, e); } return plist; }
From source file:net.dv8tion.jda.core.handle.GuildMemberUpdateHandler.java
private List<Role> toRolesList(GuildImpl guild, JSONArray array) { LinkedList<Role> roles = new LinkedList<>(); for (int i = 0; i < array.length(); i++) { final long id = array.getLong(i); Role r = guild.getRolesMap().get(id); if (r != null) { roles.add(r);//from w w w . java 2 s . c o m } else { api.getEventCache().cache(EventCache.Type.ROLE, id, () -> { handle(responseNumber, allContent); }); EventCache.LOG .debug("Got GuildMember update but one of the Roles for the Member is not yet cached."); return null; } } return roles; }
From source file:org.eclipse.orion.internal.server.servlets.file.FileHandlerV1.java
private void handlePatchContents(HttpServletRequest request, BufferedReader requestReader, HttpServletResponse response, IFileStore file) throws IOException, CoreException, NoSuchAlgorithmException, JSONException, ServletException { JSONObject changes = OrionServlet.readJSONRequest(request); //read file to memory Reader fileReader = new InputStreamReader(file.openInputStream(EFS.NONE, null)); StringWriter oldFile = new StringWriter(); IOUtilities.pipe(fileReader, oldFile, true, false); StringBuffer oldContents = oldFile.getBuffer(); JSONArray changeList = changes.getJSONArray("diff"); for (int i = 0; i < changeList.length(); i++) { JSONObject change = changeList.getJSONObject(i); long start = change.getLong("start"); long end = change.getLong("end"); String text = change.getString("text"); oldContents.replace((int) start, (int) end, text); }//from w w w. ja v a 2 s .c o m String newContents = oldContents.toString(); boolean failed = false; if (changes.has("contents")) { String contents = changes.getString("contents"); if (!newContents.equals(contents)) { failed = true; newContents = contents; } } Writer fileWriter = new OutputStreamWriter(file.openOutputStream(EFS.NONE, null), "UTF-8"); IOUtilities.pipe(new StringReader(newContents), fileWriter, false, true); if (failed) { statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_ACCEPTABLE, "Bad File Diffs. Please paste this content in a bug report: \u00A0\u00A0 " + changes.toString(), null)); return; } // return metadata with the new Etag handleGetMetadata(request, response, response.getWriter(), file); }
From source file:net.portalblockz.portalbot.serverdata.JSONConfigManager.java
public void serializeBlacklist() { JSONArray blackList = configObject.optJSONArray("blacklist-words"); if (blackList != null) { for (int i = 0; i < blackList.length(); i++) { if (!blacklistWords.contains(blackList.getString(i).toLowerCase())) { blacklistWords.add(blackList.getString(i).toLowerCase()); }/*from w w w.ja va 2 s. com*/ } } }
From source file:net.portalblockz.portalbot.serverdata.JSONConfigManager.java
public void serializeRepos() { JSONArray repoArray = configObject.optJSONArray("git-repos"); if (repoArray != null) { for (int i = 0; i < repoArray.length(); i++) { JSONObject repoData = repoArray.optJSONObject(i); if (repoData != null) { String name = repoData.getString("name"); String dispName = repoData.optString("dispName"); dispName = (dispName == null || dispName.length() < 1) ? name : dispName; List<String> repoChannels = new ArrayList<>(); for (int n = 0; n < repoData.getJSONArray("channels").length(); n++) { repoChannels.add(repoData.getJSONArray("channels").getString(n).toLowerCase()); }//from w ww. ja va 2 s . co m repoMap.put(name.toLowerCase(), repoChannels); repoDispNames.put(name.toLowerCase(), dispName); } } } }