List of usage examples for org.json JSONObject has
public boolean has(String key)
From source file:io.teak.sdk.Teak.java
static void purchaseSucceeded(final JSONObject purchaseData) { Teak.asyncExecutor.submit(new Runnable() { public void run() { try { if (Teak.isDebug) { Log.d(LOG_TAG, "Purchase succeeded: " + purchaseData.toString(2)); }/*from ww w . j a v a 2 s.c o m*/ final HashMap<String, Object> payload = new HashMap<>(); if (Teak.appConfiguration.installerPackage == null) { Log.e(LOG_TAG, "Purchase succeded from unknown app store."); } else if (Teak.appConfiguration.installerPackage.equals("com.amazon.venezia")) { JSONObject receipt = purchaseData.getJSONObject("receipt"); JSONObject userData = purchaseData.getJSONObject("userData"); payload.put("purchase_token", receipt.get("receiptId")); payload.put("purchase_time_string", receipt.get("purchaseDate")); payload.put("product_id", receipt.get("sku")); payload.put("store_user_id", userData.get("userId")); payload.put("store_marketplace", userData.get("marketplace")); Log.d(LOG_TAG, "Purchase of " + receipt.get("sku") + " detected."); } else { payload.put("purchase_token", purchaseData.get("purchaseToken")); payload.put("purchase_time", purchaseData.get("purchaseTime")); payload.put("product_id", purchaseData.get("productId")); if (purchaseData.has("orderId")) { payload.put("order_id", purchaseData.get("orderId")); } Log.d(LOG_TAG, "Purchase of " + purchaseData.get("productId") + " detected."); } if (Teak.appStore != null) { JSONObject skuDetails = Teak.appStore.querySkuDetails((String) payload.get("product_id")); if (skuDetails != null) { if (skuDetails.has("price_amount_micros")) { payload.put("price_currency_code", skuDetails.getString("price_currency_code")); payload.put("price_amount_micros", skuDetails.getString("price_amount_micros")); } else if (skuDetails.has("price_string")) { payload.put("price_string", skuDetails.getString("price_string")); } } } Session.whenUserIdIsReadyRun(new Session.SessionRunnable() { @Override public void run(Session session) { new Request("/me/purchase", payload, session).run(); } }); } catch (Exception e) { Log.e(LOG_TAG, "Error reporting purchase: " + Log.getStackTraceString(e)); Teak.sdkRaven.reportException(e); } } }); }
From source file:org.brickred.socialauth.provider.HotmailImpl.java
private List<Contact> getContacts(final String url) throws Exception { Response serviceResponse;//from w w w . j a va 2s.c o m 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:org.brickred.socialauth.provider.HotmailImpl.java
private Profile getProfile() throws Exception { Profile p = new Profile(); Response serviceResponse;//from w ww. ja v a 2 s . c o m try { serviceResponse = authenticationStrategy.executeFeed(PROFILE_URL); } catch (Exception e) { throw new SocialAuthException("Failed to retrieve the user profile from " + PROFILE_URL, e); } String result; try { result = serviceResponse.getResponseBodyAsString(Constants.ENCODING); LOG.debug("User Profile :" + result); } catch (Exception e) { throw new SocialAuthException("Failed to read response from " + PROFILE_URL, e); } try { JSONObject resp = new JSONObject(result); if (resp.has("id")) { p.setValidatedId(resp.getString("id")); } if (resp.has("name")) { p.setFullName(resp.getString("name")); } if (resp.has("first_name")) { p.setFirstName(resp.getString("first_name")); } if (resp.has("last_name")) { p.setLastName(resp.getString("last_name")); } if (resp.has("Location")) { p.setLocation(resp.getString("Location")); } if (resp.has("gender")) { p.setGender(resp.getString("gender")); } if (resp.has("ThumbnailImageLink")) { p.setProfileImageURL(resp.getString("ThumbnailImageLink")); } if (resp.has("birth_day") && !resp.isNull("birth_day")) { BirthDate bd = new BirthDate(); bd.setDay(resp.getInt("birth_day")); if (resp.has("birth_month") && !resp.isNull("birth_month")) { bd.setMonth(resp.getInt("birth_month")); } if (resp.has("birth_year") && !resp.isNull("birth_year")) { bd.setYear(resp.getInt("birth_year")); } p.setDob(bd); } if (resp.has("emails")) { JSONObject eobj = resp.getJSONObject("emails"); String email = null; if (eobj.has("preferred")) { email = eobj.getString("preferred"); } if ((email == null || email.isEmpty()) && eobj.has("account")) { email = eobj.getString("account"); } if ((email == null || email.isEmpty()) && eobj.has("personal")) { email = eobj.getString("personal"); } p.setEmail(email); } if (resp.has("locale")) { p.setLanguage(resp.getString("locale")); } serviceResponse.close(); p.setProviderId(getProviderId()); String picUrl = String.format(PROFILE_PICTURE_URL, accessGrant.getKey()); p.setProfileImageURL(picUrl); userProfile = p; return p; } catch (Exception e) { throw new SocialAuthException("Failed to parse the user profile json : " + result, e); } }
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 www.ja v a 2s . c o m 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
/** Create a task container for the given RtmTaskSeries * @throws JSONException/*w w w . ja v a 2s . co 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:com.asd.littleprincesbeauty.data.Task.java
@Override public void setContentByRemoteJSON(JSONObject js) { if (js != null) { try {// ww w . j a v a 2 s. c om // id if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); } // last_modified if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); } // name if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); } // notes if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); } // deleted if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); } // completed if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); } } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); throw new ActionFailureException("fail to get task content from jsonobject"); } } }
From source file:com.asd.littleprincesbeauty.data.Task.java
@Override public void setContentByLocalJSON(JSONObject js) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) || !js.has(GTaskStringUtils.META_HEAD_DATA)) { Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); }/*from w w w . jav a 2 s. c om*/ try { JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { Log.e(TAG, "invalid type"); return; } for (int i = 0; i < dataArray.length(); i++) { JSONObject data = dataArray.getJSONObject(i); if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { setName(data.getString(DataColumns.CONTENT)); break; } } } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } }
From source file:com.asd.littleprincesbeauty.data.Task.java
@Override public int getSyncAction(Cursor c) { try {/*from w w w .j av a 2 s . co m*/ JSONObject noteInfo = null; if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); } if (noteInfo == null) { Log.w(TAG, "it seems that note meta has been deleted"); return SYNC_ACTION_UPDATE_REMOTE; } if (!noteInfo.has(NoteColumns.ID)) { Log.w(TAG, "remote note id seems to be deleted"); return SYNC_ACTION_UPDATE_LOCAL; } // validate the note id now if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { Log.w(TAG, "note id doesn't match"); return SYNC_ACTION_UPDATE_LOCAL; } if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { // there is no local update if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { // no update both side return SYNC_ACTION_NONE; } else { // apply remote to local return SYNC_ACTION_UPDATE_LOCAL; } } else { // validate gtask id if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { Log.e(TAG, "gtask id doesn't match"); return SYNC_ACTION_ERROR; } if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { // local modification only return SYNC_ACTION_UPDATE_REMOTE; } else { return SYNC_ACTION_UPDATE_CONFLICT; } } } catch (Exception e) { Log.e(TAG, e.toString()); e.printStackTrace(); } return SYNC_ACTION_ERROR; }
From source file:cz.karry.vpnc.LunaService.java
@LunaServiceThread.PublicMethod public void connectionInfo(final ServiceMessage msg) throws JSONException, LSException { JSONObject jsonObj = msg.getJSONPayload(); if (!jsonObj.has("name")) { msg.respondError("1", "Improperly formatted request."); return;//from w w w . j a v a2s.co m } String name = jsonObj.getString("name"); JSONObject reply = new JSONObject(); reply.put("name", name); VpnConnection conn = vpnConnections.get(name); ConnectionState state = VpnConnection.ConnectionState.INACTIVE; String log = ""; if (conn != null) { state = conn.getConnectionState(); log = conn.getLog(); if (state == AbstractVpnConnection.ConnectionState.CONNECTED) { reply.put("localAddress", conn.getLocalAddress()); } } try { reply.put("profileName", name); reply.put("state", state); reply.put("log", log); //tcpLogger.log("refresh info: "+reply.toString()); msg.respond(reply.toString()); } catch (LSException ex) { tcpLogger.log(ex.getMessage(), ex); } catch (JSONException ex) { tcpLogger.log(ex.getMessage(), ex); } }
From source file:cz.karry.vpnc.LunaService.java
@LunaServiceThread.PublicMethod public void listenOnChanges(final ServiceMessage msg) throws JSONException, LSException { JSONObject jsonObj = msg.getJSONPayload(); if (!jsonObj.has("name")) { msg.respondError("1", "Improperly formatted request."); return;//from ww w . j av a 2 s. com } String name = jsonObj.getString("name"); VpnConnection conn = vpnConnections.get(name); if (conn != null) { tcpLogger.log("add listener for " + name); conn.addStateListener(new ConnectionStateListenerImpl(msg, conn, this.getNextListenerId())); } }