List of usage examples for org.json JSONObject getBoolean
public boolean getBoolean(String key) throws JSONException
From source file:com.userhook.UserHook.java
public static Notification handlePushMessage(Map<String, String> data) { String message = data.get("message"); String title = ""; if (data.containsKey("title") && data.get("title") != null) { title = data.get("title"); } else {/*from ww w . j av a 2 s.c o m*/ title = applicationContext.getApplicationInfo().loadLabel(applicationContext.getPackageManager()) .toString(); } Map<String, Object> payload = new HashMap<>(); if (data.containsKey("payload")) { try { JSONObject json = new JSONObject(data.get("payload")); payload = UHJsonUtils.toMap(json); // check if this is a feedback reply if (json.has("new_feedback") && json.getBoolean("new_feedback")) { UserHook.setHasNewFeedback(true); } else { UserHook.setHasNewFeedback(false); } } catch (JSONException e) { Log.e("uh", "error parsing push notification payload"); } } // message received Intent intent; if (pushMessageListener != null) { intent = pushMessageListener.onPushMessage(payload); } else { // default to opening the main activity intent = applicationContext.getPackageManager() .getLaunchIntentForPackage(applicationContext.getPackageName()); } // convert data to a try Map<String,String> since it will come in as an ArrayMap if (data instanceof ArrayMap) { HashMap<String, String> hashMap = new HashMap<>(); for (String key : data.keySet()) { hashMap.put(key, data.get(key)); } data = hashMap; } intent.putExtra(UserHook.UH_PUSH_DATA, (Serializable) data); intent.putExtra(UserHook.UH_PUSH_TRACKED, false); if (payload.size() > 0) { intent.putExtra(UserHook.UH_PUSH_PAYLOAD, data.get("payload")); } //PendingIntent.FLAG_UPDATE_CURRENT is required to pass along our Intent Extras PendingIntent pendingIntent = PendingIntent.getActivity(applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); try { ApplicationInfo appInfo = applicationContext.getPackageManager() .getApplicationInfo(applicationContext.getPackageName(), PackageManager.GET_META_DATA); int pushIcon = appInfo.icon; // check for a custom push icon if (pushNotificationIcon > 0) { pushIcon = pushNotificationIcon; } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(applicationContext) .setSmallIcon(pushIcon).setContentText(message).setContentTitle(title).setAutoCancel(true) .setContentIntent(pendingIntent); // use default sound notificationBuilder.setDefaults(Notification.DEFAULT_SOUND); return notificationBuilder.build(); } catch (Exception e) { Log.e("uh", "error create push notification", e); return null; } }
From source file:hongik.android.project.best.MenuActivity.java
public void drawintent() throws Exception { String query = ("func=menudetail&license=" + license + "&item=" + item); DBConnector conn = new DBConnector(query); conn.start();//from w w w. j av a2 s . c o m conn.join(); JSONObject jsonResult = conn.getResult(); boolean result = jsonResult.getBoolean("result"); if (!result) return; JSONObject json = jsonResult.getJSONArray("values").getJSONObject(0); String sname = json.getString("SNAME"); String item = json.getString("PRICE"); String img = json.getString("IMG"); ImageView imageView = (ImageView) findViewById(R.id.menudetail_image); TextViewPlus tvItem = (TextViewPlus) findViewById(R.id.menudetail_item); TextViewPlus tvStore = (TextViewPlus) findViewById(R.id.menudetail_name); TextViewPlus tvPrice = (TextViewPlus) findViewById(R.id.menudetail_price); tvItem.setText(this.item); tvStore.setText(sname); tvPrice.setText(item); ImageLoader imageLoader = new ImageLoader(img); imageLoader.start(); imageLoader.join(); Bitmap bitmap = imageLoader.getBitmap(); imageView.setImageBitmap(bitmap); }
From source file:org.ESLM.Parser.ExerciseFactory.java
public static Instruction createInstruction(JSONObject JSONExercise) throws BadFormedJSONExerciseException { switch (JSONExercise.optString("type")) { case ("OneAnswerQuestion"): { String question = JSONExercise.getString("question"); String[] answers = createAnswers(JSONExercise.getJSONArray("answers")); int correctAnswerIndex = JSONExercise.getInt("correctAnswer"); return new OneAnswerInstruction(question, answers, correctAnswerIndex); }// ww w . j a v a 2 s . c o m case ("YesNoQuestion"): { String question = JSONExercise.getString("question"); boolean correctAnswer = JSONExercise.getBoolean("correctAnswer"); return new YesNoInstruction(question, correctAnswer); } case ("SimpleQuestion"): { String question = JSONExercise.getString("question"); String answer = JSONExercise.getString("answer"); return new SimpleQuestionInstruction(question, answer); } case ("IrregularVerbExercise"): { String infinitive = JSONExercise.getString("infinitive"); String pastSimple = JSONExercise.getString("pastSimple"); String pastParticiple = JSONExercise.getString("pastParticiple"); String[] correctAnswer = { infinitive, pastSimple, pastParticiple }; String translation = JSONExercise.getString("translation"); boolean alsoRegular = JSONExercise.getBoolean("alsoRegular"); return new IrregularVerbInstruction(correctAnswer, translation, alsoRegular); } case ("VocabularyExercise"): { String sourceLanguage = JSONExercise.getString("sourceLanguage"); String goalLanguage = JSONExercise.getString("goalLanguage"); JSONArray JSONVocabularyList = JSONExercise.getJSONArray("list"); HashMap<String, String> vocabularyList = parseVocabularyList(JSONVocabularyList); return new VocabularyInstruction(vocabularyList, sourceLanguage, goalLanguage); } default: throw new BadFormedJSONExerciseException("No type or unknown type of exercise.", JSONExercise); } }
From source file:com.norman0406.slimgress.API.Item.ItemMedia.java
public ItemMedia(JSONArray json) throws JSONException { super(ItemType.Media, json); JSONObject item = json.getJSONObject(2); JSONObject imageByUrl = item.getJSONObject("imageByUrl"); JSONObject storyItem = item.getJSONObject("storyItem"); mMediaImageUrl = imageByUrl.getString("imageUrl"); mMediaUrl = storyItem.getString("primaryUrl"); mMediaDescription = storyItem.getString("shortDescription"); mMediaHasBeenViewed = storyItem.getBoolean("hasBeenViewed"); mMediaReleaseDate = storyItem.getString("releaseDate"); }
From source file:com.leanengine.RestService.java
private static boolean resultFromJson(JSONObject json) throws LeanException { try {/*ww w . j a v a2s . c o m*/ return json.getBoolean("result"); } catch (JSONException e) { throw new LeanException(LeanError.Type.ServerError, "Malformed JSON reply: missing field 'result'."); } }
From source file:com.piusvelte.sonet.SonetComments.java
private void loadComments() { mComments.clear();//from ww w .ja v a2 s. co m setListAdapter(new SimpleAdapter(SonetComments.this, mComments, R.layout.comment, new String[] { Entities.FRIEND, Statuses.MESSAGE, Statuses.CREATEDTEXT, getString(R.string.like) }, new int[] { R.id.friend, R.id.message, R.id.created, R.id.like })); mMessage.setEnabled(false); mMessage.setText(R.string.loading); final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() { @Override protected String doInBackground(Void... none) { // load the status itself if (mData != null) { SonetCrypto sonetCrypto = SonetCrypto.getInstance(getApplicationContext()); UriMatcher um = new UriMatcher(UriMatcher.NO_MATCH); String authority = Sonet.getAuthority(SonetComments.this); um.addURI(authority, SonetProvider.VIEW_STATUSES_STYLES + "/*", SonetProvider.STATUSES_STYLES); um.addURI(authority, SonetProvider.TABLE_NOTIFICATIONS + "/*", SonetProvider.NOTIFICATIONS); Cursor status; switch (um.match(mData)) { case SonetProvider.STATUSES_STYLES: status = getContentResolver().query(Statuses_styles.getContentUri(SonetComments.this), new String[] { Statuses_styles.ACCOUNT, Statuses_styles.SID, Statuses_styles.ESID, Statuses_styles.WIDGET, Statuses_styles.SERVICE, Statuses_styles.FRIEND, Statuses_styles.MESSAGE, Statuses_styles.CREATED }, Statuses_styles._ID + "=?", new String[] { mData.getLastPathSegment() }, null); if (status.moveToFirst()) { mService = status.getInt(4); mServiceName = getResources().getStringArray(R.array.service_entries)[mService]; mAccount = status.getLong(0); mSid = sonetCrypto.Decrypt(status.getString(1)); mEsid = sonetCrypto.Decrypt(status.getString(2)); Cursor widget = getContentResolver().query( Widgets_settings.getContentUri(SonetComments.this), new String[] { Widgets.TIME24HR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(status.getInt(3)), Long.toString(mAccount) }, null); if (widget.moveToFirst()) { mTime24hr = widget.getInt(0) == 1; } else { Cursor b = getContentResolver().query( Widgets_settings.getContentUri(SonetComments.this), new String[] { Widgets.TIME24HR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(status.getInt(3)), Long.toString(Sonet.INVALID_ACCOUNT_ID) }, null); if (b.moveToFirst()) { mTime24hr = b.getInt(0) == 1; } else { Cursor c = getContentResolver() .query(Widgets_settings.getContentUri(SonetComments.this), new String[] { Widgets.TIME24HR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID), Long.toString(Sonet.INVALID_ACCOUNT_ID) }, null); if (c.moveToFirst()) { mTime24hr = c.getInt(0) == 1; } else { mTime24hr = false; } c.close(); } b.close(); } widget.close(); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, mSid); commentMap.put(Entities.FRIEND, status.getString(5)); commentMap.put(Statuses.MESSAGE, status.getString(6)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(status.getLong(7), mTime24hr)); commentMap.put(getString(R.string.like), mService == TWITTER ? getString(R.string.retweet) : mService == IDENTICA ? getString(R.string.repeat) : ""); mComments.add(commentMap); // load the session Cursor account = getContentResolver().query(Accounts.getContentUri(SonetComments.this), new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SID }, Accounts._ID + "=?", new String[] { Long.toString(mAccount) }, null); if (account.moveToFirst()) { mToken = sonetCrypto.Decrypt(account.getString(0)); mSecret = sonetCrypto.Decrypt(account.getString(1)); mAccountSid = sonetCrypto.Decrypt(account.getString(2)); } account.close(); } status.close(); break; case SonetProvider.NOTIFICATIONS: Cursor notification = getContentResolver().query( Notifications.getContentUri(SonetComments.this), new String[] { Notifications.ACCOUNT, Notifications.SID, Notifications.ESID, Notifications.FRIEND, Notifications.MESSAGE, Notifications.CREATED }, Notifications._ID + "=?", new String[] { mData.getLastPathSegment() }, null); if (notification.moveToFirst()) { // clear notification ContentValues values = new ContentValues(); values.put(Notifications.CLEARED, 1); getContentResolver().update(Notifications.getContentUri(SonetComments.this), values, Notifications._ID + "=?", new String[] { mData.getLastPathSegment() }); mAccount = notification.getLong(0); mSid = sonetCrypto.Decrypt(notification.getString(1)); mEsid = sonetCrypto.Decrypt(notification.getString(2)); mTime24hr = false; // load the session Cursor account = getContentResolver().query(Accounts.getContentUri(SonetComments.this), new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SID, Accounts.SERVICE }, Accounts._ID + "=?", new String[] { Long.toString(mAccount) }, null); if (account.moveToFirst()) { mToken = sonetCrypto.Decrypt(account.getString(0)); mSecret = sonetCrypto.Decrypt(account.getString(1)); mAccountSid = sonetCrypto.Decrypt(account.getString(2)); mService = account.getInt(3); } account.close(); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, mSid); commentMap.put(Entities.FRIEND, notification.getString(3)); commentMap.put(Statuses.MESSAGE, notification.getString(4)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(notification.getLong(5), mTime24hr)); commentMap.put(getString(R.string.like), mService == TWITTER ? getString(R.string.retweet) : getString(R.string.repeat)); mComments.add(commentMap); mServiceName = getResources().getStringArray(R.array.service_entries)[mService]; } notification.close(); break; default: mComments.clear(); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, ""); commentMap.put(Entities.FRIEND, ""); commentMap.put(Statuses.MESSAGE, "error, status not found"); commentMap.put(Statuses.CREATEDTEXT, ""); commentMap.put(getString(R.string.like), ""); mComments.add(commentMap); } String response = null; HttpGet httpGet; SonetOAuth sonetOAuth; boolean liked = false; String screen_name = ""; switch (mService) { case TWITTER: sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET, mToken, mSecret); if ((response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest( new HttpGet(String.format(TWITTER_USER, TWITTER_BASE_URL, mEsid))))) != null) { try { JSONObject user = new JSONObject(response); screen_name = "@" + user.getString(Sscreen_name) + " "; } catch (JSONException e) { Log.e(TAG, e.toString()); } } publishProgress(screen_name); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(new HttpGet(String.format(TWITTER_MENTIONS, TWITTER_BASE_URL, String.format(TWITTER_SINCE_ID, mSid))))); break; case FACEBOOK: if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(FACEBOOK_LIKES, FACEBOOK_BASE_URL, mSid, Saccess_token, mToken)))) != null) { try { JSONArray likes = new JSONObject(response).getJSONArray(Sdata); for (int i = 0, i2 = likes.length(); i < i2; i++) { JSONObject like = likes.getJSONObject(i); if (like.getString(Sid).equals(mAccountSid)) { liked = true; break; } } } catch (JSONException e) { Log.e(TAG, e.toString()); } } publishProgress(getString(liked ? R.string.unlike : R.string.like)); response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet( String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid, Saccess_token, mToken))); break; case MYSPACE: sonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY, BuildConfig.MYSPACE_SECRET, mToken, mSecret); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(new HttpGet(String .format(MYSPACE_URL_STATUSMOODCOMMENTS, MYSPACE_BASE_URL, mEsid, mSid)))); break; case LINKEDIN: sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY, BuildConfig.LINKEDIN_SECRET, mToken, mSecret); httpGet = new HttpGet(String.format(LINKEDIN_UPDATE, LINKEDIN_BASE_URL, mSid)); for (String[] header : LINKEDIN_HEADERS) httpGet.setHeader(header[0], header[1]); if ((response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpGet))) != null) { try { JSONObject data = new JSONObject(response); if (data.has("isCommentable") && !data.getBoolean("isCommentable")) { publishProgress(getString(R.string.uncommentable)); } if (data.has("isLikable")) { publishProgress(getString( data.has("isLiked") && data.getBoolean("isLiked") ? R.string.unlike : R.string.like)); } else { publishProgress(getString(R.string.unlikable)); } } catch (JSONException e) { Log.e(TAG, e.toString()); } } else { publishProgress(getString(R.string.unlikable)); } httpGet = new HttpGet(String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid)); for (String[] header : LINKEDIN_HEADERS) httpGet.setHeader(header[0], header[1]); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpGet)); break; case FOURSQUARE: response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet( String.format(FOURSQUARE_GET_CHECKIN, FOURSQUARE_BASE_URL, mSid, mToken))); break; case IDENTICA: sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY, BuildConfig.IDENTICA_SECRET, mToken, mSecret); if ((response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest( new HttpGet(String.format(IDENTICA_USER, IDENTICA_BASE_URL, mEsid))))) != null) { try { JSONObject user = new JSONObject(response); screen_name = "@" + user.getString(Sscreen_name) + " "; } catch (JSONException e) { Log.e(TAG, e.toString()); } } publishProgress(screen_name); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(new HttpGet(String.format(IDENTICA_MENTIONS, IDENTICA_BASE_URL, String.format(IDENTICA_SINCE_ID, mSid))))); break; case GOOGLEPLUS: //TODO: // get plussed status break; case CHATTER: // Chatter requires loading an instance if ((mChatterInstance == null) || (mChatterToken == null)) { if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpPost( String.format(CHATTER_URL_ACCESS, BuildConfig.CHATTER_KEY, mToken)))) != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.has("instance_url") && jobj.has(Saccess_token)) { mChatterInstance = jobj.getString("instance_url"); mChatterToken = jobj.getString(Saccess_token); } } catch (JSONException e) { Log.e(TAG, e.toString()); } } } if ((mChatterInstance != null) && (mChatterToken != null)) { httpGet = new HttpGet(String.format(CHATTER_URL_LIKES, mChatterInstance, mSid)); httpGet.setHeader("Authorization", "OAuth " + mChatterToken); if ((response = SonetHttpClient.httpResponse(mHttpClient, httpGet)) != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.getInt(Stotal) > 0) { JSONArray likes = jobj.getJSONArray("likes"); for (int i = 0, i2 = likes.length(); i < i2; i++) { JSONObject like = likes.getJSONObject(i); if (like.getJSONObject(Suser).getString(Sid).equals(mAccountSid)) { mChatterLikeId = like.getString(Sid); liked = true; break; } } } } catch (JSONException e) { Log.e(TAG, e.toString()); } } publishProgress(getString(liked ? R.string.unlike : R.string.like)); httpGet = new HttpGet(String.format(CHATTER_URL_COMMENTS, mChatterInstance, mSid)); httpGet.setHeader("Authorization", "OAuth " + mChatterToken); response = SonetHttpClient.httpResponse(mHttpClient, httpGet); } else { response = null; } break; } return response; } return null; } @Override protected void onProgressUpdate(String... params) { mMessage.setText(""); if (params != null) { if ((mService == TWITTER) || (mService == IDENTICA)) { mMessage.append(params[0]); } else { if (mService == LINKEDIN) { if (params[0].equals(getString(R.string.uncommentable))) { mSend.setEnabled(false); mMessage.setEnabled(false); mMessage.setText(R.string.uncommentable); } else { setCommentStatus(0, params[0]); } } else { setCommentStatus(0, params[0]); } } } mMessage.setEnabled(true); } @Override protected void onPostExecute(String response) { if (response != null) { int i2; try { JSONArray comments; mSimpleDateFormat = null; switch (mService) { case TWITTER: comments = new JSONArray(response); if ((i2 = comments.length()) > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); if (comment.getString(Sin_reply_to_status_id) == mSid) { HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, comment.getString(Sid)); commentMap.put(Entities.FRIEND, comment.getJSONObject(Suser).getString(Sname)); commentMap.put(Statuses.MESSAGE, comment.getString(Stext)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText( parseDate(comment.getString(Screated_at), TWITTER_DATE_FORMAT), mTime24hr)); commentMap.put(getString(R.string.like), getString(R.string.retweet)); mComments.add(commentMap); } } } else { noComments(); } break; case FACEBOOK: comments = new JSONObject(response).getJSONArray(Sdata); if ((i2 = comments.length()) > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, comment.getString(Sid)); commentMap.put(Entities.FRIEND, comment.getJSONObject(Sfrom).getString(Sname)); commentMap.put(Statuses.MESSAGE, comment.getString(Smessage)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(comment.getLong(Screated_time) * 1000, mTime24hr)); commentMap.put(getString(R.string.like), getString(comment.has(Suser_likes) && comment.getBoolean(Suser_likes) ? R.string.unlike : R.string.like)); mComments.add(commentMap); } } else { noComments(); } break; case MYSPACE: comments = new JSONObject(response).getJSONArray(Sentry); if ((i2 = comments.length()) > 0) { for (int i = 0; i < i2; i++) { JSONObject entry = comments.getJSONObject(i); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, entry.getString(ScommentId)); commentMap.put(Entities.FRIEND, entry.getJSONObject(Sauthor).getString(SdisplayName)); commentMap.put(Statuses.MESSAGE, entry.getString(Sbody)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText( parseDate(entry.getString(SpostedDate), MYSPACE_DATE_FORMAT), mTime24hr)); commentMap.put(getString(R.string.like), ""); mComments.add(commentMap); } } else { noComments(); } break; case LINKEDIN: JSONObject jsonResponse = new JSONObject(response); if (jsonResponse.has(S_total) && (jsonResponse.getInt(S_total) != 0)) { comments = jsonResponse.getJSONArray(Svalues); if ((i2 = comments.length()) > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); JSONObject person = comment.getJSONObject(Sperson); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, comment.getString(Sid)); commentMap.put(Entities.FRIEND, person.getString(SfirstName) + " " + person.getString(SlastName)); commentMap.put(Statuses.MESSAGE, comment.getString(Scomment)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(comment.getLong(Stimestamp), mTime24hr)); commentMap.put(getString(R.string.like), ""); mComments.add(commentMap); } } else { noComments(); } } break; case FOURSQUARE: comments = new JSONObject(response).getJSONObject(Sresponse).getJSONObject(Scheckin) .getJSONObject(Scomments).getJSONArray(Sitems); if ((i2 = comments.length()) > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); JSONObject user = comment.getJSONObject(Suser); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, comment.getString(Sid)); commentMap.put(Entities.FRIEND, user.getString(SfirstName) + " " + user.getString(SlastName)); commentMap.put(Statuses.MESSAGE, comment.getString(Stext)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(comment.getLong(ScreatedAt) * 1000, mTime24hr)); commentMap.put(getString(R.string.like), ""); mComments.add(commentMap); } } else { noComments(); } break; case IDENTICA: comments = new JSONArray(response); if ((i2 = comments.length()) > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); if (comment.getString(Sin_reply_to_status_id) == mSid) { HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, comment.getString(Sid)); commentMap.put(Entities.FRIEND, comment.getJSONObject(Suser).getString(Sname)); commentMap.put(Statuses.MESSAGE, comment.getString(Stext)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText( parseDate(comment.getString(Screated_at), TWITTER_DATE_FORMAT), mTime24hr)); commentMap.put(getString(R.string.like), getString(R.string.repeat)); mComments.add(commentMap); } } } else { noComments(); } break; case GOOGLEPLUS: //TODO: load comments HttpPost httpPost = new HttpPost(GOOGLE_ACCESS); List<NameValuePair> httpParams = new ArrayList<NameValuePair>(); httpParams.add(new BasicNameValuePair("client_id", BuildConfig.GOOGLECLIENT_ID)); httpParams .add(new BasicNameValuePair("client_secret", BuildConfig.GOOGLECLIENT_SECRET)); httpParams.add(new BasicNameValuePair("refresh_token", mToken)); httpParams.add(new BasicNameValuePair("grant_type", "refresh_token")); try { httpPost.setEntity(new UrlEncodedFormEntity(httpParams)); if ((response = SonetHttpClient.httpResponse(mHttpClient, httpPost)) != null) { JSONObject j = new JSONObject(response); if (j.has(Saccess_token)) { String access_token = j.getString(Saccess_token); if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(GOOGLEPLUS_ACTIVITY, GOOGLEPLUS_BASE_URL, mSid, access_token)))) != null) { // check for a newer post, if it's the user's own, then set CLEARED=0 try { JSONObject item = new JSONObject(response); if (item.has(Sobject)) { JSONObject object = item.getJSONObject(Sobject); if (object.has(Sreplies)) { int commentCount = 0; JSONObject replies = object.getJSONObject(Sreplies); if (replies.has(StotalItems)) { //TODO: load comments commentCount = replies.getInt(StotalItems); } } } } catch (JSONException e) { Log.e(TAG, e.toString()); } } } } } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } catch (JSONException e) { Log.e(TAG, e.toString()); } break; case CHATTER: JSONObject chats = new JSONObject(response); if (chats.getInt(Stotal) > 0) { comments = chats.getJSONArray(Scomments); if ((i2 = comments.length()) > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, comment.getString(Sid)); commentMap.put(Entities.FRIEND, comment.getJSONObject(Suser).getString(Sname)); commentMap.put(Statuses.MESSAGE, comment.getJSONObject(Sbody).getString(Stext)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText( parseDate(comment.getString(ScreatedDate), CHATTER_DATE_FORMAT), mTime24hr)); commentMap.put(getString(R.string.like), ""); mComments.add(commentMap); } } else { noComments(); } } else { noComments(); } break; } } catch (JSONException e) { Log.e(TAG, e.toString()); } } else { noComments(); } setListAdapter(new SimpleAdapter(SonetComments.this, mComments, R.layout.comment, new String[] { Entities.FRIEND, Statuses.MESSAGE, Statuses.CREATEDTEXT, getString(R.string.like) }, new int[] { R.id.friend, R.id.message, R.id.created, R.id.like })); if (loadingDialog.isShowing()) loadingDialog.dismiss(); } private void noComments() { HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, ""); commentMap.put(Entities.FRIEND, ""); commentMap.put(Statuses.MESSAGE, getString(R.string.no_comments)); commentMap.put(Statuses.CREATEDTEXT, ""); commentMap.put(getString(R.string.like), ""); mComments.add(commentMap); } private long parseDate(String date, String format) { if (date != null) { // hack for the literal 'Z' if (date.substring(date.length() - 1).equals("Z")) { date = date.substring(0, date.length() - 2) + "+0000"; } Date created = null; if (format != null) { if (mSimpleDateFormat == null) { mSimpleDateFormat = new SimpleDateFormat(format, Locale.ENGLISH); // all dates should be GMT/UTC mSimpleDateFormat.setTimeZone(sTimeZone); } try { created = mSimpleDateFormat.parse(date); return created.getTime(); } catch (ParseException e) { Log.e(TAG, e.toString()); } } else { // attempt to parse RSS date if (mSimpleDateFormat != null) { try { created = mSimpleDateFormat.parse(date); return created.getTime(); } catch (ParseException e) { Log.e(TAG, e.toString()); } } for (String rfc822 : sRFC822) { mSimpleDateFormat = new SimpleDateFormat(rfc822, Locale.ENGLISH); mSimpleDateFormat.setTimeZone(sTimeZone); try { if ((created = mSimpleDateFormat.parse(date)) != null) { return created.getTime(); } } catch (ParseException e) { Log.e(TAG, e.toString()); } } } } return System.currentTimeMillis(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); loadingDialog.show(); asyncTask.execute(); }
From source file:me.mast3rplan.phantombot.cache.UsernameCache.java
public String resolve(String username, Map<String, String> tags) { String lusername = username.toLowerCase(); if (cache.containsKey(lusername)) { return cache.get(lusername); } else {/*from w ww.j av a2s .c o m*/ if (tags.containsKey("display-name") && tags.get("display-name").equalsIgnoreCase(lusername)) { cache.put(lusername, tags.get("display-name")); if (PhantomBot.enableDebugging) { com.gmt2001.Console.out .println(">>UsernameCache detected using v3: " + tags.get("display-name")); } return tags.get("display-name"); } if (username.equalsIgnoreCase("jtv") || username.equalsIgnoreCase("twitchnotify") || new Date().before(timeoutExpire)) { return username; } try { JSONObject user = TwitchAPIv3.instance().GetUser(lusername); if (user.getBoolean("_success")) { if (user.getInt("_http") == 200) { String displayName = user.getString("display_name"); cache.put(lusername, displayName); return displayName; } else { try { throw new Exception("[HTTPErrorException] HTTP " + user.getInt("status") + " " + user.getString("error") + ". req=" + user.getString("_type") + " " + user.getString("_url") + " " + user.getString("_post") + " " + (user.has("message") && !user.isNull("message") ? "message=" + user.getString("message") : "content=" + user.getString("_content"))); } catch (Exception e) { com.gmt2001.Console.out.println( "UsernameCache.updateCache>>Failed to get username: " + e.getMessage()); com.gmt2001.Console.err.logStackTrace(e); return username; } } } else { if (user.getString("_exception").equalsIgnoreCase("SocketTimeoutException") || user.getString("_exception").equalsIgnoreCase("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(); } } return username; } } catch (Exception e) { com.gmt2001.Console.err.printStackTrace(e); return username; } } }
From source file:com.mcnc.parecis.bizmob.task.Login20Task.java
@Override protected Response doInBackground(Object... arg0) { Response response = new Response(); final Request request = getRequest(); final BaseActivity activity = request.getSrcActivity(); String callback = ""; String legacy_trcode = ""; JSONObject root = null;/*from w w w . j a va 2s . com*/ JSONObject param = null; JSONObject auth_info = null; JSONObject legacy_message = null; String progressMsg = ""; ConfigurationModel cm = ConfigurationModel.getConfigurationModel(); long start = System.currentTimeMillis(); try { Logger.d(TAG, "doInBackground"); root = (JSONObject) request.getData(); param = root.getJSONObject("param"); // if (param.has("progress_message")) { progressMsg = param.getString("progress_message"); AbstractActivity.PROGRESS_MESSAGE = progressMsg; activity.runOnUiThread(new Runnable() { @Override public void run() { if (activity.getDlg() != null) { activity.getDlg().setMessage(AbstractActivity.PROGRESS_MESSAGE); } } }); } callback = param.getString("callback"); // ?? . //message = param.getJSONObject("message"); auth_info = param.getJSONObject("auth_info"); legacy_trcode = param.getString("legacy_trcode"); legacy_message = param.getJSONObject("legacy_message"); String password = ""; String user_id = ""; password = auth_info.getString("password"); user_id = auth_info.getString("user_id"); JSONObject data = new JSONObject(); JSONObject newParam = new JSONObject(); JSONObject newMassage = new JSONObject(); JSONObject newHeader = new JSONObject(); JSONObject newBody = new JSONObject(); data.put("param", newParam); newParam.put("message", newMassage); newMassage.put("header", newHeader); newMassage.put("body", newBody); newHeader.put("result", true); newHeader.put("error_code", ""); newHeader.put("error_text", ""); newHeader.put("info_text", ""); newHeader.put("message_version", "0.9"); newHeader.put("login_session_id", ""); newHeader.put("trcode", "LOGIN"); newBody.put("password", password); newBody.put("legacy_trcode", legacy_trcode); newBody.put("legacy_message", legacy_message); newBody.put("user_id", user_id); newBody.put("os_type", Def.OS_TYPE_NAME); boolean emulFlag = false; if (android.os.Build.MODEL.contains("sdk")) { emulFlag = true; } TelephonyManager manager = (TelephonyManager) request.getSrcActivity() .getSystemService(Context.TELEPHONY_SERVICE); boolean manual_phone_number = false; String mobilenum = ""; String tempNumber = ""; if (manager != null) { tempNumber = manager.getLine1Number(); if (tempNumber == null) { mobilenum = cm.getStringSharedPreferences("MANUAL_NUMBER"); manual_phone_number = true; } else if (tempNumber.equals("")) { manual_phone_number = true; mobilenum = cm.getStringSharedPreferences("MANUAL_NUMBER"); } else { if (emulFlag == true) { manual_phone_number = true; mobilenum = cm.getStringSharedPreferences("MANUAL_NUMBER"); } else { manual_phone_number = false; mobilenum = tempNumber; } } } else { mobilenum = cm.getStringSharedPreferences("MANUAL_NUMBER"); if (mobilenum.equals(ConfigurationModel.PREFERENCE_NOTFOUND)) { mobilenum = ""; } manual_phone_number = true; } String device_id = ""; if (manager != null) { device_id = manager.getDeviceId(); if (device_id == null) { device_id = Secure.getString(activity.getContentResolver(), Secure.ANDROID_ID); } } else { device_id = Secure.getString(activity.getContentResolver(), Secure.ANDROID_ID); } newBody.put("manual_phone_number", manual_phone_number); newBody.put("device_id", device_id); // emulator flag true ? device? ? if (auth_info.has("emulator_flag")) { newBody.put("emulator_flag", auth_info.getBoolean("emulator_flag")); } else { newBody.put("emulator_flag", emulFlag); } newBody.put("app_key", Def.APPLICTION_NAME); newBody.put("phone_number", mobilenum); request.setData(data); request.setTrCode("LOGIN"); response.setCallback(callback); JSONObject result = sendReq(request); JSONObject header = null; JSONObject body = null; if (result.has("header")) { header = result.getJSONObject("header"); } boolean remote = false; boolean access_limit = false; if (header.getBoolean("result")) { if (result.has("body")) { body = result.getJSONObject("body"); } // License ? Login20Task SUCCESS ? ?? Task ? ??? // License ?? ? String device_type = cm.getStringSharedPreferences("device_type"); Def.LICENSE_NO_VALUE = body.getString("license_no"); Def.USER_TYPE_VALUE = body.getString("user_type"); //ActivationTask? ? ? ?? Def.DEVICE_TYPE_VALUE = device_type; Def.USER_ID_VALUE = user_id; Def.DEVICE_ID_VALUE = device_id; Def.COMPANY_ID_VALUE = body.getString("company_id"); //"attachment_download": true, //"access_limit": false, //"legacy_message": "", //"legacy_trcode": "" // App Tester boolean app_tester = body.getBoolean("app_tester"); boolean app_tester_before = cm.getBooleanSharedPreferences(ConfigurationModel.APP_TESTER); // Update ? ? ? ? ??. if (app_tester != app_tester_before) { String CONTENT_ROOT = ImageUtil.ROOT_PATH + ImageUtil.CONTENT_ROOT + "/"; activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity, "?? .", Toast.LENGTH_LONG).show(); } }); File f = new File(CONTENT_ROOT); if (f.exists()) { FileUtils.delete(f); } cm.setBooleanSharedPreferences(ConfigurationModel.APP_TESTER, app_tester); cm.setVersionContentMajor(0); cm.setVersionContentMinor(0); activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity, MSG_CHANGE_USER_TYPE, Toast.LENGTH_LONG).show(); } }); activity.finish(); return null; } // remote wipe remote = body.getBoolean("remote_wipe"); if (remote) { activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity, MSG_REMOTEWPE, Toast.LENGTH_LONG).show(); } }); activity.finish(); return null; } // assess limmit access_limit = body.getBoolean("access_limit"); if (access_limit) { activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity, MSG_ACCESS_LIMIIT, Toast.LENGTH_LONG).show(); } }); activity.finish(); return null; } JSONObject reust_legacy_message = body.getJSONObject("legacy_message"); response.setData(reust_legacy_message); } else { Logger.d(TAG, "bizMob result false : " + result); response.setError(false); response.setData(result); } } catch (Exception e) { e.printStackTrace(); Logger.d(TAG, "Send Error : " + e.getMessage()); JSONObject root1 = new JSONObject(); JSONObject header = new JSONObject(); try { root1.put("header", header); header.put("result", false); if (e instanceof HttpResponseException) { // HTTTP header.put("error_code", "HTTP" + ((HttpResponseException) e).getStatusCode()); header.put("error_text", e.getMessage()); } else if (e instanceof HttpHostConnectException) { // Connect header.put("error_code", "NE0001"); header.put("error_text", e.getMessage()); } else if (e instanceof ConnectTimeoutException) { // Connect header.put("error_code", "NE0001"); header.put("error_text", e.getMessage()); } else if (e instanceof SocketTimeoutException) { // Read header.put("error_code", "NE0002"); header.put("error_text", e.getMessage()); } else if (e instanceof IOException) { // ? ? ? header.put("error_code", "NE0003"); header.put("error_text", e.getMessage()); } else if (e instanceof NullPointerException) { header.put("error_code", "CE0001"); // ? ? header.put("error_text", "NullPointerException"); } else { header.put("error_code", "CE0001"); // ? ? header.put("error_text", e.getMessage()); } } catch (JSONException e1) { e1.printStackTrace(); } response.setError(false); response.setData(root1); } finally { // ?? if (progressMsg.length() > 0) { AbstractActivity.PROGRESS_MESSAGE = AbstractActivity.DEFAULT_PROGRESS_MESSAGE; } // ? ?? ? ?. long end = System.currentTimeMillis(); long processTime = end - start; if (processTime < 200 && processTime > 0) { try { Thread.sleep(200 - processTime); } catch (InterruptedException e) { } } } response.setRequest(request); setResponse(response); return response; }
From source file:org.droidparts.test.testcase.serialize.JSONTestCase.java
public void testPrimitives() throws Exception { JSONSerializer<Primitives> serializer = makeSerializer(Primitives.class); Primitives primitives = serializer.deserialize(getPrimitives()); assertNotNull(primitives.strArr);//from www .jav a 2 s . c o m assertEquals(9000, (long) primitives.longList.get(0)); // JSONObject obj = serializer.serialize(primitives); // assertEquals(1, obj.getInt("int1")); assertEquals(2, obj.getInt("int2")); assertEquals(0.5, obj.getDouble("float1")); assertEquals(2.5, obj.getDouble("float2")); assertEquals(true, obj.getBoolean("boolean1")); assertEquals(true, obj.getBoolean("boolean2")); assertEquals(true, obj.getBoolean("boolean3")); assertEquals(false, obj.getBoolean("boolean4")); assertEquals("str", obj.getString("string1")); assertEquals(2, obj.getJSONArray("string_array").length()); assertEquals("two", obj.getJSONArray("string_array").getString(1)); }
From source file:com.dwdesign.tweetings.util.Utils.java
public static Bundle parseArguments(final String string) { final Bundle bundle = new Bundle(); if (string != null) { try {/* w ww. j av a 2 s. c om*/ final JSONObject json = new JSONObject(string); final Iterator<?> it = json.keys(); while (it.hasNext()) { final Object key_obj = it.next(); if (key_obj == null) { continue; } final String key = key_obj.toString(); final Object value = json.get(key); if (value instanceof Boolean) { bundle.putBoolean(key, json.getBoolean(key)); } else if (value instanceof Integer) { // Simple workaround for account_id if (INTENT_KEY_ACCOUNT_ID.equals(key)) { bundle.putLong(key, json.getLong(key)); } else { bundle.putInt(key, json.getInt(key)); } } else if (value instanceof Long) { bundle.putLong(key, json.getLong(key)); } else if (value instanceof String) { bundle.putString(key, json.getString(key)); } else { Log.w(LOGTAG, "Unknown type " + value.getClass().getSimpleName() + " in arguments key " + key); } } } catch (final JSONException e) { e.printStackTrace(); } catch (final ClassCastException e) { e.printStackTrace(); } } return bundle; }