List of usage examples for org.json JSONArray length
public int length()
From source file:net.dv8tion.jda.core.handle.GuildEmojisUpdateHandler.java
@Override protected Long handleInternally(JSONObject content) { final long guildId = content.getLong("guild_id"); if (api.getGuildLock().isLocked(guildId)) return guildId; GuildImpl guild = (GuildImpl) api.getGuildMap().get(guildId); if (guild == null) { api.getEventCache().cache(EventCache.Type.GUILD, guildId, () -> handle(responseNumber, allContent)); return null; }/*from w w w . java 2s . c o m*/ JSONArray array = content.getJSONArray("emojis"); TLongObjectMap<Emote> emoteMap = guild.getEmoteMap(); List<Emote> oldEmotes = new ArrayList<>(emoteMap.valueCollection()); //snapshot of emote cache List<Emote> newEmotes = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { JSONObject current = array.getJSONObject(i); final long emoteId = current.getLong("id"); EmoteImpl emote = (EmoteImpl) emoteMap.get(emoteId); EmoteImpl oldEmote = null; if (emote == null) { emote = new EmoteImpl(emoteId, guild); newEmotes.add(emote); } else { // emote is in our cache which is why we don't want to remove it in cleanup later oldEmotes.remove(emote); oldEmote = emote.clone(); } emote.setName(current.getString("name")).setManaged(current.getBoolean("managed")); //update roles JSONArray roles = current.getJSONArray("roles"); Set<Role> newRoles = emote.getRoleSet(); Set<Role> oldRoles = new HashSet<>(newRoles); //snapshot of cached roles for (int j = 0; j < roles.length(); j++) { Role role = guild.getRoleById(roles.getString(j)); newRoles.add(role); oldRoles.remove(role); } //cleanup old cached roles that were not found in the JSONArray for (Role r : oldRoles) { // newRoles directly writes to the set contained in the emote newRoles.remove(r); } // finally, update the emote emoteMap.put(emote.getIdLong(), emote); // check for updated fields and fire events handleReplace(oldEmote, emote); } //cleanup old emotes that don't exist anymore for (Emote e : oldEmotes) { emoteMap.remove(e.getIdLong()); api.getEventManager().handle(new EmoteRemovedEvent(api, responseNumber, e)); } for (Emote e : newEmotes) { api.getEventManager().handle(new EmoteAddedEvent(api, responseNumber, e)); } return null; }
From source file:org.zaizi.sensefy.api.utils.JSONHelper.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public static List toList(JSONArray array) throws JSONException { List list = new ArrayList(); for (int i = 0; i < array.length(); i++) { list.add(fromJson(array.get(i))); }// ww w . java2 s . co m return list; }
From source file:org.everit.json.schema.TestSuiteTest.java
@Parameters(name = "{2}") public static List<Object[]> params() { List<Object[]> rval = new ArrayList<>(); Reflections refs = new Reflections("org.everit.json.schema.draft4", new ResourcesScanner()); Set<String> paths = refs.getResources(Pattern.compile(".*\\.json")); for (String path : paths) { if (path.indexOf("/optional/") > -1 || path.indexOf("/remotes/") > -1) { continue; }/*from w w w .j a va 2s. com*/ String fileName = path.substring(path.lastIndexOf('/') + 1); JSONArray arr = loadTests(TestSuiteTest.class.getResourceAsStream("/" + path)); for (int i = 0; i < arr.length(); ++i) { JSONObject schemaTest = arr.getJSONObject(i); JSONArray testcaseInputs = schemaTest.getJSONArray("tests"); for (int j = 0; j < testcaseInputs.length(); ++j) { JSONObject input = testcaseInputs.getJSONObject(j); Object[] params = new Object[5]; params[0] = "[" + fileName + "]/" + schemaTest.getString("description"); params[1] = schemaTest.get("schema"); params[2] = "[" + fileName + "]/" + input.getString("description"); params[3] = input.get("data"); params[4] = input.getBoolean("valid"); rval.add(params); } } } return rval; }
From source file:net.cellcloud.talk.HttpSpeaker.java
private void requestHeartbeat() { // URL//ww w . ja va 2s .c o m StringBuilder url = new StringBuilder("http://"); url.append(this.address.getHostString()).append(":").append(this.address.getPort()); url.append(URI_HEARTBEAT); // ?? try { ContentResponse response = this.client.newRequest(url.toString()).method(HttpMethod.GET) .header(HttpHeader.COOKIE, this.cookie).send(); if (response.getStatus() == HttpResponse.SC_OK) { // this.hbFailedCounts = 0; JSONObject responseData = this.readContent(response.getContent()); if (responseData.has(HttpHeartbeatHandler.Primitives)) { // ? JSONArray primitives = responseData.getJSONArray(HttpHeartbeatHandler.Primitives); for (int i = 0, size = primitives.length(); i < size; ++i) { JSONObject primJSON = primitives.getJSONObject(i); // ?? this.doDialogue(primJSON); } } } else { // ++this.hbFailedCounts; Logger.w(HttpSpeaker.class, "Heartbeat failed"); } } catch (InterruptedException | TimeoutException | ExecutionException e) { // ++this.hbFailedCounts; } catch (JSONException e) { Logger.log(getClass(), e, LogLevel.ERROR); } // hbMaxFailed ? if (this.hbFailedCounts >= this.hbMaxFailed) { this.hangUp(); } }
From source file:org.loklak.android.client.SearchClient.java
public static Timeline search(final String protocolhostportstub, final String query, final Timeline.Order order, final String source, final int count, final int timezoneOffset, final long timeout) throws IOException { Timeline tl = new Timeline(order); String urlstring = ""; try {/*from w w w. j av a 2s . co m*/ urlstring = protocolhostportstub + "/api/search.json?q=" + URLEncoder.encode(query.replace(' ', '+'), "UTF-8") + "&timezoneOffset=" + timezoneOffset + "&maximumRecords=" + count + "&source=" + (source == null ? "all" : source) + "&minified=true&timeout=" + timeout; JSONObject json = JsonIO.loadJson(urlstring); if (json == null || json.length() == 0) return tl; JSONArray statuses = json.getJSONArray("statuses"); if (statuses != null) { for (int i = 0; i < statuses.length(); i++) { JSONObject tweet = statuses.getJSONObject(i); JSONObject user = tweet.getJSONObject("user"); if (user == null) continue; tweet.remove("user"); UserEntry u = new UserEntry(user); MessageEntry t = new MessageEntry(tweet); tl.add(t, u); } } if (json.has("search_metadata")) { JSONObject metadata = json.getJSONObject("search_metadata"); if (metadata.has("hits")) { tl.setHits((Integer) metadata.get("hits")); } if (metadata.has("scraperInfo")) { String scraperInfo = (String) metadata.get("scraperInfo"); tl.setScraperInfo(scraperInfo); } } } catch (Throwable e) { Log.e("SeachClient", e.getMessage(), e); } //System.out.println(parser.text()); return tl; }
From source file:com.phonegap.FileTransfer.java
/** * Convenience method to read a parameter from the list of JSON args. * @param args the args passed to the Plugin * @param position the position to retrieve the arg from * @param defaultString the default to be used if the arg does not exist * @return String with the retrieved value *///from w w w. j a v a 2 s .co m private String getArgument(JSONArray args, int position, String defaultString) { String arg = defaultString; if (args.length() >= position) { arg = args.optString(position); if (arg == null || "null".equals(arg)) { arg = defaultString; } } return arg; }
From source file:conroller.UserController.java
public static ArrayList<UserModel> userDetailsTable() throws IOException, JSONException { String userName, fullName, email, address, gender, telNo, password, typeOfUser; ArrayList<UserModel> arrayList = new ArrayList<>(); phpConnection.setConnection(//from w w w. j av a 2s . c o m "http://itmahaweliauthority.net23.net/MahaweliAuthority/userPHPfiles/UserGetView.php"); JSONObject jSONObject = new JSONObject(phpConnection.readData()); JSONArray array = jSONObject.getJSONArray("server_response"); for (int i = 0; i < array.length(); i++) { JSONObject details = array.getJSONObject(i); try { userName = String.valueOf(details.getString("userName")); } catch (Exception e) { userName = null; } try { fullName = String.valueOf(details.getString("fullName")); } catch (Exception e) { fullName = null; } try { email = String.valueOf(details.getString("email")); } catch (Exception e) { email = null; } try { address = String.valueOf(details.getString("address")); } catch (Exception e) { address = null; } try { gender = String.valueOf(details.getString("gender")); } catch (Exception e) { gender = null; } try { telNo = String.valueOf(details.getString("telNo")); } catch (Exception e) { telNo = null; } try { password = String.valueOf(details.getString("password")); } catch (Exception e) { password = null; } try { typeOfUser = String.valueOf(details.getString("typeOfUser")); } catch (Exception e) { typeOfUser = null; } UserModel data = new UserModel(userName, fullName, email, address, gender, telNo, password, typeOfUser); arrayList.add(data); } return arrayList; }
From source file:conroller.UserController.java
private static ArrayList<UserModel> getJSONData(String response) throws IOException, JSONException { String userName, fullName, email, address, gender, telNo, password, typeOfUser; ArrayList<UserModel> arrayList = new ArrayList<>(); final JSONObject jSONObject = new JSONObject(response); final JSONArray array = jSONObject.getJSONArray("server_response"); for (int i = 0; i < array.length(); i++) { final JSONObject details = array.getJSONObject(i); try {/*from w ww . j a v a 2 s . co m*/ userName = String.valueOf(details.getString("userName")); } catch (Exception ex) { userName = null; } try { fullName = String.valueOf(details.getString("fullName")); } catch (Exception e) { fullName = null; } try { email = String.valueOf(details.getString("email")); } catch (Exception e) { email = null; } try { address = String.valueOf(details.getString("address")); } catch (Exception e) { address = null; } try { gender = String.valueOf(details.getString("gender")); } catch (Exception e) { gender = null; } try { telNo = String.valueOf(details.getString("telNo")); } catch (Exception e) { telNo = null; } try { password = String.valueOf(details.getString("password")); } catch (Exception e) { password = null; } try { typeOfUser = String.valueOf(details.getString("typeOfUser")); } catch (Exception e) { typeOfUser = null; } UserModel model = new UserModel(userName, fullName, email, address, gender, telNo, password, typeOfUser); arrayList.add(model); } return arrayList; }
From source file:rocks.teammolise.myunimol.webapp.login.HomeServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w .ja va2 s . co m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //il tipo di risultato della servlet response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { if (request.getSession().getAttribute("userInfo") == null) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); return; } UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userInfo"); String username = userInfo.getUsername(); String password = userInfo.getPassword(); JSONObject recordBook = new APIConsumer().consume("getRecordBook", username, password); JSONObject result = new JSONObject(); result.put("average", recordBook.getDouble("average")); result.put("weightedAverage", recordBook.getDouble("weightedAverage")); JSONArray exams = recordBook.getJSONArray("exams"); float acquiredCFU = 0; int totalExams = 0; for (int i = 0; i < exams.length(); i++) { if (!exams.getJSONObject(i).getString("vote").contains("/")) { acquiredCFU += exams.getJSONObject(i).getInt("cfu"); totalExams++; } } double percentCfuUgly = (acquiredCFU * 100) / userInfo.getTotalCFU(); //Arrotonda la percentuale alla prima cifra decimale double percentCfu = Math.round(percentCfuUgly * 10D) / 10D; result.put("totalCFU", (int) userInfo.getTotalCFU()); result.put("acquiredCFU", (int) acquiredCFU); result.put("percentCFU", percentCfu); result.put("totalExams", totalExams); out.write(result.toString()); } catch (UnirestException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); } catch (JSONException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); } finally { out.close(); } }
From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.InviteToSharedAppFeedObj.java
public static JSONObject json(Collection<Contact> contacts, String feedName, String packageName) { JSONObject obj = new JSONObject(); try {//ww w. j a v a2 s. c om obj.put("packageName", packageName); obj.put("sharedFeedName", feedName); JSONArray participants = new JSONArray(); Iterator<Contact> it = contacts.iterator(); while (it.hasNext()) { String localId = "@l" + it.next().id; participants.put(participants.length(), localId); } // Need to add ourself to participants participants.put(participants.length(), "@l" + Contact.MY_ID); obj.put("participants", participants); } catch (JSONException e) { } return obj; }