List of usage examples for org.json JSONObject isNull
public boolean isNull(String key)
From source file:com.imaginary.home.cloud.CloudTest.java
@Test public void initializePairing() throws Exception { HashMap<String, Object> action = new HashMap<String, Object>(); action.put("action", "initializePairing"); HttpClient client = getClient();//w w w. ja v a2 s .co m HttpPut method = new HttpPut(cloudAPI + "/location/" + locationId); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "put:/location/" + locationId + ":" + apiKeyId + ":" + timestamp + ":" + VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(action)).toString(), "application/json", "UTF-8")); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_OK) { String json = EntityUtils.toString(response.getEntity()); JSONObject u = new JSONObject(json); String pairingCode = (u.has("pairingCode") && !u.isNull("pairingCode")) ? u.getString("pairingCode") : null; out("Pairing code: " + pairingCode); Assert.assertNotNull("Pairing code may not be null", pairingCode); if (CloudTest.pairingCode == null) { CloudTest.pairingCode = pairingCode; } } else { Assert.fail("Failed to initialize pairing (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); } }
From source file:com.imaginary.home.cloud.CloudTest.java
@Test public void pair() throws Exception { HashMap<String, Object> map = new HashMap<String, Object>(); long key = (System.currentTimeMillis() % 100000); map.put("pairingCode", pairingCode); map.put("name", "Test Controller " + key); HttpClient client = getClient();/*from www . j av a2 s . c o m*/ HttpPost method = new HttpPost(cloudAPI + "/relay"); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(map)).toString(), "application/json", "UTF-8")); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_CREATED) { String json = EntityUtils.toString(response.getEntity()); JSONObject keys = new JSONObject(json); String relayKeyId = (keys.has("apiKeyId") && !keys.isNull("apiKeyId")) ? keys.getString("apiKeyId") : null; String relayKeySecret = (keys.has("apiKeySecret") && !keys.isNull("apiKeySecret")) ? keys.getString("apiKeySecret") : null; out("Key ID: " + relayKeyId); out("Key secret: " + relayKeySecret); Assert.assertNotNull("Relay key ID may not be null", relayKeyId); Assert.assertNotNull("Relay key secret may not be null", relayKeySecret); if (CloudTest.relayKeyId == null) { CloudTest.relayKeyId = relayKeyId; CloudTest.relayKeySecret = relayKeySecret; } CloudTest.pairingCode = null; } else { Assert.fail("Failed to finish pairing (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); } }
From source file:com.imaginary.home.cloud.CloudTest.java
@Test public void token() throws Exception { HttpClient client = getClient();//from w w w . ja v a2 s .c o m HttpPost method = new HttpPost(cloudAPI + "/token"); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", relayKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(relayKeySecret.getBytes("utf-8"), "post:/token:" + relayKeyId + ":" + timestamp + ":" + VERSION)); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_CREATED) { String json = EntityUtils.toString(response.getEntity()); JSONObject t = new JSONObject(json); String token = (t.has("token") && !t.isNull("token")) ? t.getString("token") : null; out("Token: " + token); Assert.assertNotNull("Token may not be null", token); CloudTest.token = token; } else { Assert.fail("Failed to generate token (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); } }
From source file:net.dv8tion.jda.core.handle.VoiceServerUpdateHandler.java
@Override protected Long handleInternally(JSONObject content) { final long guildId = content.getLong("guild_id"); api.getClient().getQueuedAudioConnectionMap().remove(guildId); if (api.getGuildLock().isLocked(guildId)) return guildId; if (content.isNull("endpoint")) { //Discord did not provide an endpoint yet, we are to wait until discord has resources to provide // an endpoint, which will result in them sending another VOICE_SERVER_UPDATE which we will handle // to actually connect to the audio server. return null; }/*from w w w . java 2 s .c o m*/ String endpoint = content.getString("endpoint"); String token = content.getString("token"); Guild guild = api.getGuildMap().get(guildId); if (guild == null) throw new IllegalArgumentException( "Attempted to start audio connection with Guild that doesn't exist! JSON: " + content); String sessionId = guild.getSelfMember().getVoiceState().getSessionId(); if (sessionId == null) throw new IllegalArgumentException( "Attempted to create audio connection without having a session ID. Did VOICE_STATE_UPDATED fail?"); //Strip the port from the endpoint. endpoint = endpoint.replace(":80", ""); AudioManagerImpl audioManager = (AudioManagerImpl) guild.getAudioManager(); synchronized (audioManager.CONNECTION_LOCK) //Synchronized to prevent attempts to close while setting up initial objects. { if (audioManager.isConnected()) audioManager.prepareForRegionChange(); if (!audioManager.isAttemptingToConnect()) { WebSocketClient.LOG.debug( "Received a VOICE_SERVER_UPDATE but JDA is not currently connected nor attempted to connect " + "to a VoiceChannel. Assuming that this is caused by another client running on this account. Ignoring the event."); return null; } AudioWebSocket socket = new AudioWebSocket(audioManager.getListenerProxy(), endpoint, api, guild, sessionId, token, audioManager.isAutoReconnect()); AudioConnection connection = new AudioConnection(socket, audioManager.getQueuedAudioConnection()); audioManager.setAudioConnection(connection); socket.startConnection(); return null; } }
From source file:de.fahrgemeinschaft.EditRideFragment3.java
public void setRide(Ride ride) { try {/*from w w w . ja v a 2s . c o m*/ JSONObject d = ride.getDetails(); if (!d.isNull(CONTACT.EMAIL)) email.text.setText(d.getString(CONTACT.EMAIL)); else { email.text.setText(prefs.getString(CONTACT.EMAIL, prefs.getString(ProfileFragment.LOGIN, EMPTY))); } if (!d.isNull(CONTACT.LANDLINE)) land.text.setText(d.getString(CONTACT.LANDLINE)); else { land.text.setText(prefs.getString(CONTACT.LANDLINE, EMPTY)); } if (!d.isNull(CONTACT.MOBILE)) mobile.text.setText(d.getString(CONTACT.MOBILE)); else { mobile.text.setText(prefs.getString(CONTACT.MOBILE, EMPTY)); } if (ride.getMode().equals(Ride.Mode.TRAIN)) { plate.setVisibility(View.GONE); } else { plate.setVisibility(View.VISIBLE); if (!d.isNull(CONTACT.PLATE)) { plate.text.setText(d.getString(CONTACT.PLATE)); } else { plate.text.setText(prefs.getString(CONTACT.PLATE, EMPTY)); } } name.text.setText(prefs.getString(ProfileFragment.LASTNAME, EMPTY)); if (d.isNull(FahrgemeinschaftConnector.PRIVACY)) d.put(FahrgemeinschaftConnector.PRIVACY, new JSONObject()); JSONObject p = d.getJSONObject(FahrgemeinschaftConnector.PRIVACY); if (!p.isNull(CONTACT.EMAIL)) email.setPrivacy(p.getInt(CONTACT.EMAIL)); // 'm' else setPublic(email, p, CONTACT.EMAIL); if (!p.isNull(CONTACT.LANDLINE)) land.setPrivacy(p.getInt(CONTACT.LANDLINE)); else setPublic(land, p, CONTACT.LANDLINE); if (!p.isNull(CONTACT.MOBILE)) mobile.setPrivacy(p.getInt(CONTACT.MOBILE)); else setPublic(mobile, p, CONTACT.MOBILE); if (!p.isNull(CONTACT.PLATE)) plate.setPrivacy(p.getInt(CONTACT.PLATE)); else setPublic(plate, p, CONTACT.PLATE); if (!p.isNull(NAME)) name.setPrivacy(p.getInt(NAME)); else setPublic(name, p, NAME); } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.nextgis.firereporter.GetFiresService.java
protected void FillData(int nType, String sJSON) { GetDataStoped();/*from w w w . j a v a 2 s . c o m*/ try { JSONObject jsonMainObject = new JSONObject(sJSON); if (jsonMainObject.getBoolean("error")) { String sMsg = jsonMainObject.getString("msg"); SendError(sMsg); return; } if (jsonMainObject.has("rows") && !jsonMainObject.isNull("rows")) { JSONArray jsonArray = jsonMainObject.getJSONArray("rows"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); //Log.i(ParseJSON.class.getName(), jsonObject.getString("text")); long nId = jsonObject.getLong("fid"); long nKey = 10000000000L * nType + nId; //as we have values from separte tables we can get same key - to prevent this add big value multiplied on source type if (mmoFires.containsKey(nKey)) continue; int nIconId = 0; if (nType == 1) {//user nIconId = R.drawable.ic_eye; } else if (nType == 2) {//nasa nIconId = R.drawable.ic_nasa; } String sDate = jsonObject.getString("date"); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date dtFire = dateFormat.parse(sDate); double dfLat = jsonObject.getDouble("lat"); double dfLon = jsonObject.getDouble("lon"); double dfDist = jsonObject.getDouble("dist"); FireItem item = new FireItem(this, nType, nId, dtFire, dfLon, dfLat, dfDist, nIconId); mmoFires.put(nKey, item); SendItem(item); String sMsg = String.format("%s/%.1f %s/%s", item.GetShortCoordinates(), dfDist / 1000, getString(R.string.km), item.GetDateAsString()); onNotify(nType, sMsg); } } } catch (Exception e) { SendError(e.getLocalizedMessage());// e.printStackTrace(); } }
From source file:me.mast3rplan.phantombot.cache.ChannelHostCache.java
private void updateCache() throws Exception { Map<String, JSONObject> newCache = Maps.newHashMap(); JSONObject j; if (id == 0) { j = TwitchAPIv3.instance().GetChannel(channel); if (j.getBoolean("_success")) { if (j.getInt("_http") == 200) { id = j.getInt("_id"); }/*from w w w .ja v a2s . c o m*/ } } if (id == 0) { return; } j = TwitchAPIv3.instance().GetHostUsers(id); if (j.getBoolean("_success")) { if (j.getInt("_http") == 200) { JSONArray hosts = j.getJSONArray("hosts"); for (int i = 0; i < hosts.length(); i++) { newCache.put(hosts.getJSONObject(i).getString("host_login"), hosts.getJSONObject(i)); } } else { try { throw new Exception("[HTTPErrorException] HTTP " + j.getInt("status") + " " + j.getString("error") + ". req=" + j.getString("_type") + " " + j.getString("_url") + " " + j.getString("_post") + " " + (j.has("message") && !j.isNull("message") ? "message=" + j.getString("message") : "content=" + j.getString("_content"))); } catch (Exception e) { com.gmt2001.Console.out .println("ChannelHostCache.updateCache>>Failed to update hosts: " + e.getMessage()); com.gmt2001.Console.err.logStackTrace(e); } } } else { try { throw new Exception("[" + j.getString("_exception") + "] " + j.getString("_exceptionMessage")); } catch (Exception e) { if (e.getMessage().startsWith("[SocketTimeoutException]") || e.getMessage().startsWith("[IOException]")) { Calendar c = Calendar.getInstance(); if (lastFail.after(new Date())) { numfail++; } else { numfail = 1; } c.add(Calendar.MINUTE, 1); lastFail = c.getTime(); if (numfail >= 5) { timeoutExpire = c.getTime(); } } com.gmt2001.Console.out .println("ChannelHostCache.updateCache>>Failed to update hosts: " + e.getMessage()); com.gmt2001.Console.err.logStackTrace(e); } } List<String> hosted = Lists.newArrayList(); List<String> unhosted = Lists.newArrayList(); for (String key : newCache.keySet()) { if (cache == null || !cache.containsKey(key)) { hosted.add(key); } } if (cache != null) { for (String key : cache.keySet()) { if (!newCache.containsKey(key)) { unhosted.add(key); } } } this.cache = newCache; for (String hoster : hosted) { EventBus.instance() .post(new TwitchHostedEvent(hoster, PhantomBot.instance().getChannel("#" + this.channel))); } for (String unhoster : unhosted) { EventBus.instance() .post(new TwitchUnhostedEvent(unhoster, PhantomBot.instance().getChannel("#" + this.channel))); } if (firstUpdate) { firstUpdate = false; EventBus.instance() .post(new TwitchHostsInitializedEvent(PhantomBot.instance().getChannel("#" + this.channel))); } }
From source file:com.thedrycake.tempincity.util.JsonUtils.java
/** * Retrieve a String value from a JSON Object. * //from ww w .j ava2 s . co m * @param json * the JSON Object. * @param name * the name. * @param defaultValue * the default value. * @return the String value if it exists, otherwise the default value. */ public static String getString(JSONObject jsonObject, String name, String defaultValue) { return jsonObject != null && !jsonObject.isNull(name) ? jsonObject.optString(name, defaultValue) : defaultValue; }
From source file:com.microsoft.applicationinsights.test.framework.telemetries.TelemetryItem.java
private void initTelemetryItemWithCommonProperties(JSONObject json) throws URISyntaxException, JSONException { System.out.println("Extracting JSON common properties (" + this.docType + ")"); JSONObject context = json.getJSONObject("context"); JSONObject sessionJson = context.getJSONObject("session"); String sessionId = !sessionJson.isNull("id") ? sessionJson.getString("id") : ""; JSONObject userJson = context.getJSONObject("user"); String userId = !userJson.isNull("anonId") ? userJson.getString("anonId") : ""; String operationId = context.getJSONObject("operation").getString("id"); String operationName = context.getJSONObject("operation").getString("name"); JSONObject custom = context.getJSONObject("custom"); JSONArray dimensions = custom.getJSONArray("dimensions"); String runId = null;/*from w ww. jav a 2 s . co m*/ for (int i = 0; i < dimensions.length(); i++) { JSONObject jsonObject = dimensions.getJSONObject(i); if (!jsonObject.isNull("runid")) { runId = jsonObject.getString("runid"); break; } } this.setProperty("userId", userId); this.setProperty("sessionId", sessionId); this.setProperty("runId", runId); this.setProperty("operationId", operationId); this.setProperty("operationName", operationName); }
From source file:sh.calaba.driver.server.CalabashNodeConfiguration.java
/** * Reads the driver configuration from given config. * //www.j a v a 2 s . com * @param configuration The driver config. * @throws JSONException On JSON errors. */ private void readDriverConfiguration(JSONObject configuration) throws JSONException { hubHost = configuration.getString("hubHost"); hubPort = configuration.getInt("hubPort"); driverHost = configuration.getString("host"); driverPort = configuration.getInt("port"); driverRegistrationEnabled = configuration.getBoolean("register"); driverMaxSession = configuration.getInt("maxSession"); mobileAppPath = configuration.getString("autApk"); mobileTestAppPath = configuration.getString("autTestApk"); installApksEnabled = configuration.getBoolean("installApks"); cleanSavedUserDataEnabled = configuration.getBoolean("cleanSavedUserData"); proxy = configuration.isNull("proxy") ? "org.openqa.grid.selenium.proxy.DefaultRemoteProxy" : configuration.getString("proxy"); }