List of usage examples for org.json.simple JSONArray isEmpty
public boolean isEmpty()
From source file:com.worldline.easycukes.rest.client.RestService.java
/** * Allows to get the specified property randomly from the response array of * a previous REST call/*from ww w . j a v a2 s .c om*/ * * @param property * @return the value if it's found (else it'll be null) * @throws ParseException */ public String getRandomlyPropertyFromResponseArray(@NonNull String property) throws ParseException { final JSONArray jsonArray = JSONHelper.toJSONArray(response.getResponseString()); if (jsonArray != null && !jsonArray.isEmpty()) return JSONHelper.getValue((JSONObject) jsonArray.get(new Random().nextInt(jsonArray.size())), property); return null; }
From source file:bammerbom.ultimatecore.bukkit.UltimateUpdater.java
/** * Make a connection to the BukkitDev API and request the newest file's * details.//from ww w .j a va 2s . c om * * @return true if successful. */ private boolean read() { try { final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); conn.addRequestProperty("User-Agent", UltimateUpdater.USER_AGENT); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.isEmpty()) { r.log("No updates found."); this.result = UpdateResult.FAIL_BADID; return false; } UltimateUpdater.versionName = (String) ((Map) array.get(array.size() - 1)) .get(UltimateUpdater.TITLE_VALUE); this.versionLink = (String) ((Map) array.get(array.size() - 1)).get(UltimateUpdater.LINK_VALUE); this.versionType = (String) ((Map) array.get(array.size() - 1)).get(UltimateUpdater.TYPE_VALUE); this.versionGameVersion = (String) ((Map) array.get(array.size() - 1)) .get(UltimateUpdater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { r.log("Invalid API key."); this.result = UpdateResult.FAIL_APIKEY; } else { r.log("Could not connect to bukkit.org, update check failed. " + (e.getCause() != null ? "(" + e.getCause() + ")" : "")); this.result = UpdateResult.FAIL_DBO; } return false; } }
From source file:mml.handler.get.MMLGetAnnotationsHandler.java
/** * Handle a request for options/*from www. j a va 2 s . co m*/ * @param request the http request * @param response the http response * @param urn the urn (ignored) * @throws MMLException */ @Override public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException { try { JSONArray annotations = new JSONArray(); docid = request.getParameter(Params.DOCID); version1 = request.getParameter(Params.VERSION1); if (docid != null && version1 != null) { Connection conn = Connector.getConnection(); String[] docids = conn.listDocuments(Database.SCRATCH, docid + ".*", JSONKeys.DOCID); if (docids != null && docids.length > 0) { for (int i = 0; i < docids.length; i++) { JSONObject jObj = fetchAnnotation(conn, Database.SCRATCH, docids[i]); if (jObj != null) annotations.add(jObj); } } if (annotations.isEmpty()) // nothing in SCRATCH space { docids = conn.listDocuments(Database.ANNOTATIONS, docid + ".*", JSONKeys.DOCID); if (docids != null && docids.length > 0) { for (int i = 0; i < docids.length; i++) { JSONObject jObj = fetchAnnotation(conn, Database.ANNOTATIONS, docids[i]); if (jObj != null) annotations.add(jObj); } } } } String res = annotations.toJSONString(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.getWriter().write(res); } catch (Exception e) { throw new MMLException(e); } }
From source file:com.live.aac_jenius.globalgroupmute.utilities.Updater.java
/** * Make a connection to the BukkitDev API and request the newest file's details. * * @return true if successful.//w w w . ja va 2 s.c om */ private boolean read() { try { final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); if (this.apiKey != null) { conn.addRequestProperty("X-API-Key", this.apiKey); } conn.addRequestProperty("User-Agent", Updater.USER_AGENT); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.isEmpty()) { this.sender.sendMessage( this.prefix + "The updater could not find any files for the project id " + this.id); this.result = UpdateResult.FAIL_BADID; return false; } this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)) .get(Updater.VERSION_VALUE); return true; } catch (final IOException ex) { if (ex.getMessage().contains("HTTP response code: 403")) { this.sender.sendMessage(this.prefix + "dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml\nPlease double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.sender.sendMessage(this.prefix + "The updater could not contact dev.bukkit.org for updating.\nIf you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } this.plugin.getLogger().log(Level.SEVERE, null, ex); return false; } }
From source file:com.drevelopment.couponcodes.bukkit.updater.Updater.java
/** * Make a connection to the BukkitDev API and request the newest file's details. * * @return true if successful.// w w w.ja va 2 s .com */ private boolean read() { try { final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); if (this.apiKey != null) { conn.addRequestProperty("X-API-Key", this.apiKey); } conn.addRequestProperty("User-Agent", Updater.USER_AGENT); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.isEmpty()) { this.plugin.getLogger() .warning("The updater could not find any files for the project id " + this.id); this.result = UpdateResult.FAIL_BADID; return false; } JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1); this.versionName = (String) latestUpdate.get(Updater.TITLE_VALUE); this.versionLink = (String) latestUpdate.get(Updater.LINK_VALUE); this.versionType = (String) latestUpdate.get(Updater.TYPE_VALUE); this.versionGameVersion = (String) latestUpdate.get(Updater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.plugin.getLogger() .severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating."); this.plugin.getLogger().severe( "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } this.plugin.getLogger().log(Level.SEVERE, null, e); return false; } }
From source file:jp.aegif.nemaki.rest.UserResource.java
/** * Search user by id TODO Use Solr/* www . j a va 2 s . co m*/ * * @param query * @return */ @SuppressWarnings("unchecked") @GET @Path("/search") @Produces(MediaType.APPLICATION_JSON) public String search(@PathParam("repositoryId") String repositoryId, @QueryParam("query") String query) { boolean status = true; JSONObject result = new JSONObject(); JSONArray errMsg = new JSONArray(); List<User> users; JSONArray queriedUsers = new JSONArray(); users = principalService.getUsers(repositoryId); for (User user : users) { if (user.getUserId().startsWith(query) || user.getName().startsWith(query)) { JSONObject userJSON = convertUserToJson(user); queriedUsers.add(userJSON); } } if (queriedUsers.isEmpty()) { status = false; addErrMsg(errMsg, ITEM_USER, ErrorCode.ERR_NOTFOUND); } else { result.put("result", queriedUsers); } result = makeResult(status, result, errMsg); return result.toJSONString(); }
From source file:br.com.oauthtwo.OAuthTwoClient.java
@Override public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException { AccessTokenInfo tokenInfo = new AccessTokenInfo(); KeyManagerConfiguration config = KeyManagerHolder.getKeyManagerInstance().getKeyManagerConfiguration(); String introspectionURL = config.getParameter(OAuthTwoConstants.INTROSPECTION_URL); String introspectionConsumerKey = config.getParameter(OAuthTwoConstants.INTROSPECTION_CK); String introspectionConsumerSecret = config.getParameter(OAuthTwoConstants.INTROSPECTION_CS); String encodedSecret = Base64 .encode(new String(introspectionConsumerKey + ":" + introspectionConsumerSecret).getBytes()); BufferedReader reader = null; try {/*w w w . j a v a 2 s . c om*/ URIBuilder uriBuilder = new URIBuilder(introspectionURL); uriBuilder.addParameter("access_token", accessToken); uriBuilder.build(); HttpGet httpGet = new HttpGet(uriBuilder.build()); HttpClient client = new DefaultHttpClient(); httpGet.setHeader("Authorization", "Basic " + encodedSecret); HttpResponse response = client.execute(httpGet); int responseCode = response.getStatusLine().getStatusCode(); LOGGER.log(Level.INFO, "HTTP Response code : " + responseCode); // {"audience":"MappedClient","scopes":["test"],"principal":{"name":"mappedclient","roles":[],"groups":[],"adminPrincipal":false, // "attributes":{}},"expires_in":1433059160531} HttpEntity entity = response.getEntity(); JSONObject parsedObject; String errorMessage = null; reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8")); if (HttpStatus.SC_OK == responseCode) { // pass bufferReader object and get read it and retrieve the // parsedJson object parsedObject = getParsedObjectByReader(reader); if (parsedObject != null) { Map valueMap = parsedObject; Object principal = valueMap.get("principal"); if (principal == null) { tokenInfo.setTokenValid(false); return tokenInfo; } Map principalMap = (Map) principal; String clientId = (String) principalMap.get("clientId"); Long expiryTimeString = (Long) valueMap.get("expires_in"); String endUserName = (String) principalMap.get("name"); LOGGER.log(Level.INFO, "OAuthTwoClient - clientId:" + clientId + " expires_in:" + expiryTimeString); // Returning false if mandatory attributes are missing. if (clientId == null || expiryTimeString == null) { tokenInfo.setTokenValid(false); tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_EXPIRED); return tokenInfo; } long currentTime = System.currentTimeMillis(); long expiryTime = expiryTimeString; if (expiryTime > currentTime) { tokenInfo.setTokenValid(true); tokenInfo.setConsumerKey(clientId); tokenInfo.setValidityPeriod(expiryTime - currentTime); // Considering Current Time as the issued time. tokenInfo.setIssuedTime(currentTime); tokenInfo.setEndUserName(endUserName); tokenInfo.setAccessToken(accessToken); // tokenInfo. JSONArray scopesArray = (JSONArray) valueMap.get("scopes"); if (scopesArray != null && !scopesArray.isEmpty()) { String[] scopes = new String[scopesArray.size()]; for (int i = 0; i < scopes.length; i++) { scopes[i] = (String) scopesArray.get(i); } tokenInfo.setScope(scopes); } } else { tokenInfo.setTokenValid(false); tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE); return tokenInfo; } } else { LOGGER.log(Level.SEVERE, "Invalid Token " + accessToken); tokenInfo.setTokenValid(false); tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE); return tokenInfo; } } // for other HTTP error codes we just pass generic message. else { LOGGER.log(Level.SEVERE, "Invalid Token " + accessToken); tokenInfo.setTokenValid(false); tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE); return tokenInfo; } } catch (UnsupportedEncodingException e) { handleException("The Character Encoding is not supported. " + e.getMessage(), e); } catch (ClientProtocolException e) { handleException( "HTTP request error has occurred while sending request to OAuth Provider. " + e.getMessage(), e); } catch (IOException e) { handleException("Error has occurred while reading or closing buffer reader. " + e.getMessage(), e); } catch (URISyntaxException e) { handleException("Error occurred while building URL with params." + e.getMessage(), e); } catch (ParseException e) { handleException("Error while parsing response json " + e.getMessage(), e); } finally { IOUtils.closeQuietly(reader); } LOGGER.log(Level.INFO, "OAuthTwoClient - getTokenMetada - return SUCCESSFULY" + tokenInfo.getJSONString()); return tokenInfo; }
From source file:com.googlecode.fascinator.common.JsonSimple.java
/** * Find the first valid JsonObject in a JSONArray. * * @param array : The array to search/* ww w . j av a 2s . co m*/ * @return JsonObject : A JSON object * @throws IOException if there was an error */ private JsonObject getFromArray(JSONArray array) { if (array.isEmpty()) { log.warn("Found only empty array, starting new object"); return new JsonObject(); } // Grab the first element Object object = array.get(0); if (object == null) { log.warn("Null entry, starting new object"); return new JsonObject(); } // Nested array, go deeper if (object instanceof JSONArray) { return getFromArray((JSONArray) object); } return (JsonObject) object; }
From source file:client.InterfaceJeu.java
public void verifierCartes() { //on compare avec les cartes jouables //on crer un JSON Array depuis les cartes selectionnes Iterator it = cartesSelectionnees.iterator(); JSONArray arr = new JSONArray(); while (it.hasNext()) { JLabel o = (JLabel) it.next(); JSONObject obj = new JSONObject(); obj.put("couleur", o.getName().split("-")[1]); obj.put("hauteur", o.getName().split("-")[0]); arr.add(obj);//from w ww .j a v a 2 s .c om } System.out.println(arr); //si ok on enabled le bouton jouer if (!interSession) { if (!arr.isEmpty() && cartesJouables.contains(arr)) { jButton1.setEnabled(true); } else { jButton1.setEnabled(false); } } else { if (role.equals("president")) { if (arr.size() == 2) { jButton1.setEnabled(true); } else { jButton1.setEnabled(false); } } else if (role.equals("vicepresident")) { if (arr.size() == 1) { jButton1.setEnabled(true); } else { jButton1.setEnabled(false); } } } }
From source file:com.p000ison.dev.simpleclans2.converter.Converter.java
public void convertClans() throws SQLException { ResultSet result = from.query("SELECT * FROM `sc_clans`;"); while (result.next()) { JSONObject flags = new JSONObject(); String name = result.getString("name"); String tag = result.getString("tag"); boolean verified = result.getBoolean("verified"); boolean friendly_fire = result.getBoolean("friendly_fire"); long founded = result.getLong("founded"); long last_used = result.getLong("last_used"); String flagsString = result.getString("flags"); String cape = result.getString("cape_url"); ConvertedClan clan = new ConvertedClan(tag); clan.setPackedAllies(result.getString("packed_allies")); clan.serPackedRivals(result.getString("packed_rivals")); if (friendly_fire) { flags.put("ff", friendly_fire); }/*from w ww .j a v a 2 s . c o m*/ if (cape != null && !cape.isEmpty()) { flags.put("cape-url", cape); } JSONParser parser = new JSONParser(); try { JSONObject object = (JSONObject) parser.parse(flagsString); String world = object.get("homeWorld").toString(); if (!world.isEmpty()) { int x = ((Long) object.get("homeX")).intValue(); int y = ((Long) object.get("homeY")).intValue(); int z = ((Long) object.get("homeZ")).intValue(); flags.put("home", x + ":" + y + ":" + z + ":" + world + ":0:0"); } clan.setRawWarring((JSONArray) object.get("warring")); } catch (ParseException e) { Logging.debug(e, true); continue; } insertClan(name, tag, verified, founded, last_used, flags.isEmpty() ? null : flags.toJSONString(), result.getDouble("balance")); String selectLastQuery = "SELECT `id` FROM `sc2_clans` ORDER BY ID DESC LIMIT 1;"; ResultSet selectLast = to.query(selectLastQuery); selectLast.next(); clan.setId(selectLast.getLong("id")); selectLast.close(); insertBB(Arrays.asList(result.getString("packed_bb").split("\\s*(\\||$)")), clan.getId()); clans.add(clan); } for (ConvertedClan clan : clans) { JSONArray allies = new JSONArray(); JSONArray rivals = new JSONArray(); JSONArray warring = new JSONArray(); for (String allyTag : clan.getRawAllies()) { long allyID = getIDByTag(allyTag); if (allyID != -1) { allies.add(allyID); } } for (String rivalTag : clan.getRawAllies()) { long rivalID = getIDByTag(rivalTag); if (rivalID != -1) { rivals.add(rivalID); } } for (String warringTag : clan.getRawWarring()) { long warringID = getIDByTag(warringTag); if (warringID != -1) { warring.add(warringID); } } if (!allies.isEmpty()) { updateClan.setString(1, allies.toJSONString()); } else { updateClan.setNull(1, Types.VARCHAR); } if (!rivals.isEmpty()) { updateClan.setString(2, rivals.toJSONString()); } else { updateClan.setNull(2, Types.VARCHAR); } if (!warring.isEmpty()) { updateClan.setString(3, warring.toJSONString()); } else { updateClan.setNull(3, Types.VARCHAR); } updateClan.setLong(4, clan.getId()); updateClan.executeUpdate(); } }