Example usage for org.json JSONException toString

List of usage examples for org.json JSONException toString

Introduction

In this page you can find the example usage for org.json JSONException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:de.hscoburg.etif.vbis.lagerix.android.barcode.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException {

    CharSequence contents = HttpHelper.downloadViaHttp(
            "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;//from w  w w .jav  a2s  .c  o  m
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>(authorsArray.length());
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e.toString());
    }

    Collection<String> newTexts = new ArrayList<String>();
    maybeAddText(title, newTexts);
    maybeAddTextSeries(authors, newTexts);
    maybeAddText(pages == null || pages.length() == 0 ? null : pages + "pp.", newTexts);

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}

From source file:com.piusvelte.sonet.SonetNotifications.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Integer, String, Boolean> asyncTask = new AsyncTask<Integer, String, Boolean>() {

        @Override/*from w  ww  .  ja v a  2 s . c o m*/
        protected Boolean doInBackground(Integer... arg0) {
            if (arg0[0] == R.id.menu_notifications_refresh) {
                // select all accounts with notifications set
                Cursor widgets = getContentResolver().query(
                        Widgets_settings.getDistinctContentUri(SonetNotifications.this),
                        new String[] { Widgets.ACCOUNT }, Widgets.ACCOUNT + "!=-1 and (" + Widgets.LIGHTS
                                + "=1 or " + Widgets.VIBRATE + "=1 or " + Widgets.SOUND + "=1)",
                        null, null);
                if (widgets.moveToFirst()) {
                    mSonetCrypto = SonetCrypto.getInstance(getApplicationContext());
                    HttpClient httpClient = SonetHttpClient.getThreadSafeClient(getApplicationContext());
                    while (!widgets.isAfterLast()) {
                        long accountId = widgets.getLong(0);
                        ArrayList<String> notificationSids = new ArrayList<String>();
                        Cursor account = getContentResolver().query(
                                Accounts.getContentUri(SonetNotifications.this),
                                new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE,
                                        Accounts.SID },
                                Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
                        if (account.moveToFirst()) {
                            // for each account, for each notification, check for updates
                            // if there are no updates past 24hrs and cleared, delete
                            String token = mSonetCrypto.Decrypt(account.getString(0));
                            String secret = mSonetCrypto.Decrypt(account.getString(1));
                            int service = account.getInt(2);
                            String accountEsid = mSonetCrypto.Decrypt(account.getString(3));
                            mSimpleDateFormat = null;
                            if (service == TWITTER) {
                                Cursor currentNotifications = getContentResolver().query(
                                        Notifications.getContentUri(SonetNotifications.this),
                                        new String[] { Notifications.SID }, Notifications.ACCOUNT + "=?",
                                        new String[] { Long.toString(accountId) }, null);
                                // loop over notifications
                                if (currentNotifications.moveToFirst()) {
                                    // store sids, to avoid duplicates when requesting the latest feed
                                    String sid = mSonetCrypto.Decrypt(currentNotifications.getString(0));
                                    if (!notificationSids.contains(sid)) {
                                        notificationSids.add(sid);
                                    }
                                }
                                currentNotifications.close();
                                // limit to newest status
                                SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY,
                                        BuildConfig.TWITTER_SECRET, token, secret);
                                String last_sid = null;
                                Cursor last_status = getContentResolver().query(
                                        Statuses.getContentUri(SonetNotifications.this),
                                        new String[] { Statuses.SID }, Statuses.ACCOUNT + "=?",
                                        new String[] { Long.toString(accountId) },
                                        Statuses.CREATED + " ASC LIMIT 1");
                                if (last_status.moveToFirst()) {
                                    last_sid = mSonetCrypto.Decrypt(last_status.getString(0));
                                }
                                last_status.close();
                                // get all mentions since the oldest status for this account
                                String response = SonetHttpClient.httpResponse(httpClient,
                                        sonetOAuth.getSignedRequest(
                                                new HttpGet(String.format(TWITTER_MENTIONS, TWITTER_BASE_URL,
                                                        last_sid != null
                                                                ? String.format(TWITTER_SINCE_ID, last_sid)
                                                                : ""))));
                                if (response != null) {
                                    try {
                                        JSONArray comments = new JSONArray(response);
                                        for (int i = 0, i2 = comments.length(); i < i2; i++) {
                                            JSONObject comment = comments.getJSONObject(i);
                                            JSONObject user = comment.getJSONObject(Suser);
                                            if (!user.getString(Sid).equals(accountEsid)
                                                    && !notificationSids.contains(comment.getString(Sid))) {
                                                String friend = user.getString(Sname);
                                                addNotification(comment.getString(Sid), user.getString(Sid),
                                                        friend, comment.getString("text"),
                                                        parseDate(comment.getString("created_at"),
                                                                TWITTER_DATE_FORMAT),
                                                        accountId, friend + " mentioned you on Twitter");
                                            }
                                        }
                                    } catch (JSONException e) {
                                        Log.e(TAG, service + ":" + e.toString());
                                    }
                                }
                            } else if (service == IDENTICA) {
                                Cursor currentNotifications = getContentResolver().query(
                                        Notifications.getContentUri(SonetNotifications.this),
                                        new String[] { Notifications.SID }, Notifications.ACCOUNT + "=?",
                                        new String[] { Long.toString(accountId) }, null);
                                // loop over notifications
                                if (currentNotifications.moveToFirst()) {
                                    // store sids, to avoid duplicates when requesting the latest feed
                                    String sid = mSonetCrypto.Decrypt(currentNotifications.getString(0));
                                    if (!notificationSids.contains(sid)) {
                                        notificationSids.add(sid);
                                    }
                                }
                                currentNotifications.close();
                                // limit to newest status
                                SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY,
                                        BuildConfig.IDENTICA_SECRET, token, secret);
                                String last_sid = null;
                                Cursor last_status = getContentResolver().query(
                                        Statuses.getContentUri(SonetNotifications.this),
                                        new String[] { Statuses.SID }, Statuses.ACCOUNT + "=?",
                                        new String[] { Long.toString(accountId) },
                                        Statuses.CREATED + " ASC LIMIT 1");
                                if (last_status.moveToFirst()) {
                                    last_sid = mSonetCrypto.Decrypt(last_status.getString(0));
                                }
                                last_status.close();
                                // get all mentions since the oldest status for this account
                                String response = SonetHttpClient.httpResponse(httpClient,
                                        sonetOAuth.getSignedRequest(
                                                new HttpGet(String.format(IDENTICA_MENTIONS, IDENTICA_BASE_URL,
                                                        last_sid != null
                                                                ? String.format(IDENTICA_SINCE_ID, last_sid)
                                                                : ""))));
                                if (response != null) {
                                    try {
                                        JSONArray comments = new JSONArray(response);
                                        for (int i = 0, i2 = comments.length(); i < i2; i++) {
                                            JSONObject comment = comments.getJSONObject(i);
                                            JSONObject user = comment.getJSONObject(Suser);
                                            if (!user.getString(Sid).equals(accountEsid)
                                                    && !notificationSids.contains(comment.getString(Sid))) {
                                                String friend = user.getString(Sname);
                                                addNotification(comment.getString(Sid), user.getString(Sid),
                                                        friend, comment.getString("text"),
                                                        parseDate(comment.getString("created_at"),
                                                                TWITTER_DATE_FORMAT),
                                                        accountId, friend + " mentioned you on Identi.ca");
                                            }
                                        }
                                    } catch (JSONException e) {
                                        Log.e(TAG, service + ":" + e.toString());
                                    }
                                }
                            } else {
                                Cursor currentNotifications = getContentResolver().query(
                                        Notifications.getContentUri(SonetNotifications.this),
                                        new String[] { Notifications._ID, Notifications.SID,
                                                Notifications.UPDATED, Notifications.CLEARED,
                                                Notifications.ESID },
                                        Notifications.ACCOUNT + "=?", new String[] { Long.toString(accountId) },
                                        null);
                                if (currentNotifications.moveToFirst()) {
                                    String response;
                                    SonetOAuth sonetOAuth;
                                    switch (service) {
                                    case FACEBOOK:
                                        // loop over notifications
                                        while (!currentNotifications.isAfterLast()) {
                                            long notificationId = currentNotifications.getLong(0);
                                            String sid = mSonetCrypto
                                                    .Decrypt(currentNotifications.getString(1));
                                            long updated = currentNotifications.getLong(2);
                                            boolean cleared = currentNotifications.getInt(3) == 1;
                                            // store sids, to avoid duplicates when requesting the latest feed
                                            if (!notificationSids.contains(sid)) {
                                                notificationSids.add(sid);
                                            }
                                            // get comments for current notifications
                                            if ((response = SonetHttpClient.httpResponse(httpClient,
                                                    new HttpGet(
                                                            String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL,
                                                                    sid, Saccess_token, token)))) != null) {
                                                // check for a newer post, if it's the user's own, then set CLEARED=0
                                                try {
                                                    JSONArray comments = new JSONObject(response)
                                                            .getJSONArray(Sdata);
                                                    int i2 = comments.length();
                                                    if (i2 > 0) {
                                                        for (int i = 0; i < i2; i++) {
                                                            JSONObject comment = comments.getJSONObject(i);
                                                            long created_time = comment.getLong(Screated_time)
                                                                    * 1000;
                                                            if (created_time > updated) {
                                                                // new comment
                                                                ContentValues values = new ContentValues();
                                                                values.put(Notifications.UPDATED, created_time);
                                                                JSONObject from = comment.getJSONObject(Sfrom);
                                                                if (accountEsid.equals(from.getString(Sid))) {
                                                                    // user's own comment, clear the notification
                                                                    values.put(Notifications.CLEARED, 1);
                                                                } else if (cleared) {
                                                                    values.put(Notifications.NOTIFICATION,
                                                                            String.format(getString(
                                                                                    R.string.friendcommented),
                                                                                    from.getString(Sname)));
                                                                    values.put(Notifications.CLEARED, 0);
                                                                } else {
                                                                    values.put(Notifications.NOTIFICATION,
                                                                            String.format(getString(
                                                                                    R.string.friendcommented),
                                                                                    from.getString(Sname)
                                                                                            + " and others"));
                                                                }
                                                                getContentResolver().update(
                                                                        Notifications.getContentUri(
                                                                                SonetNotifications.this),
                                                                        values, Notifications._ID + "=?",
                                                                        new String[] { Long
                                                                                .toString(notificationId) });
                                                            }
                                                        }
                                                    }
                                                } catch (JSONException e) {
                                                    Log.e(TAG, service + ":" + e.toString());
                                                }
                                            }
                                            currentNotifications.moveToNext();
                                        }
                                        // check the latest feed
                                        if ((response = SonetHttpClient.httpResponse(httpClient,
                                                new HttpGet(String.format(FACEBOOK_HOME, FACEBOOK_BASE_URL,
                                                        Saccess_token, token)))) != null) {
                                            try {
                                                JSONArray jarr = new JSONObject(response).getJSONArray(Sdata);
                                                // if there are updates, clear the cache
                                                int d2 = jarr.length();
                                                if (d2 > 0) {
                                                    for (int d = 0; d < d2; d++) {
                                                        JSONObject o = jarr.getJSONObject(d);
                                                        String sid = o.getString(Sid);
                                                        // if already notified, ignore
                                                        if (!notificationSids.contains(sid)) {
                                                            // only parse status types, not photo, video or link
                                                            if (o.has(Stype) && o.has(Sfrom)) {
                                                                JSONObject f = o.getJSONObject(Sfrom);
                                                                if (f.has(Sname) && f.has(Sid)) {
                                                                    String notification = null;
                                                                    String esid = f.getString(Sid);
                                                                    String friend = f.getString(Sname);
                                                                    if (o.has(Sto)) {
                                                                        // handle wall messages from one friend to another
                                                                        JSONObject t = o.getJSONObject(Sto);
                                                                        if (t.has(Sdata)) {
                                                                            JSONObject n = t.getJSONArray(Sdata)
                                                                                    .getJSONObject(0);
                                                                            if (n.has(Sname)) {
                                                                                if (n.has(Sid) && (n
                                                                                        .getString(Sid)
                                                                                        .equals(accountEsid))) {
                                                                                    notification = String
                                                                                            .format(getString(
                                                                                                    R.string.friendcommented),
                                                                                                    friend);
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                    int commentCount = 0;
                                                                    if (o.has(Scomments)) {
                                                                        JSONObject jo = o
                                                                                .getJSONObject(Scomments);
                                                                        if (jo.has(Sdata)) {
                                                                            JSONArray comments = jo
                                                                                    .getJSONArray(Sdata);
                                                                            commentCount = comments.length();
                                                                            // notifications
                                                                            if ((sid != null)
                                                                                    && (commentCount > 0)) {
                                                                                // default hasCommented to whether or not these comments are for the own user's status
                                                                                boolean hasCommented = notification != null
                                                                                        || esid.equals(
                                                                                                accountEsid);
                                                                                for (int c2 = 0; c2 < commentCount; c2++) {
                                                                                    JSONObject c3 = comments
                                                                                            .getJSONObject(c2);
                                                                                    if (c3.has(Sfrom)) {
                                                                                        JSONObject c4 = c3
                                                                                                .getJSONObject(
                                                                                                        Sfrom);
                                                                                        if (c4.getString(Sid)
                                                                                                .equals(accountEsid)) {
                                                                                            if (!hasCommented) {
                                                                                                // the user has commented on this thread, notify any updates
                                                                                                hasCommented = true;
                                                                                            }
                                                                                            // clear any notifications, as the user is already aware
                                                                                            if (notification != null) {
                                                                                                notification = null;
                                                                                            }
                                                                                        } else if (hasCommented) {
                                                                                            // don't notify about user's own comments
                                                                                            // send the parent comment sid
                                                                                            notification = String
                                                                                                    .format(getString(
                                                                                                            R.string.friendcommented),
                                                                                                            c4.getString(
                                                                                                                    Sname));
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                    if (notification != null) {
                                                                        String message = o.has(Smessage)
                                                                                ? o.getString(Smessage)
                                                                                : null;
                                                                        if (!o.getString(Stype).equals(Sstatus)
                                                                                && o.has(Slink)) {
                                                                            message = message == null
                                                                                    ? "[" + o.getString(Stype)
                                                                                            + "]"
                                                                                    : "[" + o.getString(Stype)
                                                                                            + "]";
                                                                        }
                                                                        // new notification
                                                                        addNotification(sid, esid, friend,
                                                                                message,
                                                                                o.getLong(Screated_time) * 1000,
                                                                                accountId, notification);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            } catch (JSONException e) {
                                                Log.e(TAG, service + ":" + e.toString());
                                            }
                                        }
                                        break;
                                    case MYSPACE:
                                        sonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY,
                                                BuildConfig.MYSPACE_SECRET, token, secret);
                                        // loop over notifications
                                        while (!currentNotifications.isAfterLast()) {
                                            long notificationId = currentNotifications.getLong(0);
                                            String sid = mSonetCrypto
                                                    .Decrypt(currentNotifications.getString(1));
                                            long updated = currentNotifications.getLong(2);
                                            boolean cleared = currentNotifications.getInt(3) == 1;
                                            String esid = mSonetCrypto
                                                    .Decrypt(currentNotifications.getString(4));
                                            // store sids, to avoid duplicates when requesting the latest feed
                                            if (!notificationSids.contains(sid)) {
                                                notificationSids.add(sid);
                                            }
                                            // get comments for current notifications
                                            if ((response = SonetHttpClient.httpResponse(httpClient,
                                                    sonetOAuth.getSignedRequest(new HttpGet(
                                                            String.format(MYSPACE_URL_STATUSMOODCOMMENTS,
                                                                    MYSPACE_BASE_URL, esid, sid))))) != null) {
                                                // check for a newer post, if it's the user's own, then set CLEARED=0
                                                try {
                                                    JSONArray comments = new JSONObject(response)
                                                            .getJSONArray(Sentry);
                                                    int i2 = comments.length();
                                                    if (i2 > 0) {
                                                        for (int i = 0; i < i2; i++) {
                                                            JSONObject comment = comments.getJSONObject(i);
                                                            long created_time = parseDate(
                                                                    comment.getString(SpostedDate),
                                                                    MYSPACE_DATE_FORMAT);
                                                            if (created_time > updated) {
                                                                // new comment
                                                                ContentValues values = new ContentValues();
                                                                values.put(Notifications.UPDATED, created_time);
                                                                JSONObject author = comment
                                                                        .getJSONObject(Sauthor);
                                                                if (accountEsid.equals(author.getString(Sid))) {
                                                                    // user's own comment, clear the notification
                                                                    values.put(Notifications.CLEARED, 1);
                                                                } else if (cleared) {
                                                                    values.put(Notifications.NOTIFICATION,
                                                                            String.format(getString(
                                                                                    R.string.friendcommented),
                                                                                    comment.getString(
                                                                                            SdisplayName)));
                                                                    values.put(Notifications.CLEARED, 0);
                                                                } else {
                                                                    values.put(Notifications.NOTIFICATION,
                                                                            String.format(getString(
                                                                                    R.string.friendcommented),
                                                                                    comment.getString(
                                                                                            SdisplayName)
                                                                                            + " and others"));
                                                                }
                                                                getContentResolver().update(
                                                                        Notifications.getContentUri(
                                                                                SonetNotifications.this),
                                                                        values, Notifications._ID + "=?",
                                                                        new String[] { Long
                                                                                .toString(notificationId) });
                                                            }
                                                        }
                                                    }
                                                } catch (JSONException e) {
                                                    Log.e(TAG, service + ":" + e.toString());
                                                }
                                            }
                                            currentNotifications.moveToNext();
                                        }
                                        // check the latest feed
                                        if ((response = SonetHttpClient
                                                .httpResponse(httpClient,
                                                        sonetOAuth.getSignedRequest(
                                                                new HttpGet(String.format(MYSPACE_HISTORY,
                                                                        MYSPACE_BASE_URL))))) != null) {
                                            try {
                                                JSONArray jarr = new JSONObject(response).getJSONArray(Sentry);
                                                // if there are updates, clear the cache
                                                int d2 = jarr.length();
                                                if (d2 > 0) {
                                                    for (int d = 0; d < d2; d++) {
                                                        JSONObject o = jarr.getJSONObject(d);
                                                        String sid = o.getString(SstatusId);
                                                        // if already notified, ignore
                                                        if (!notificationSids.contains(sid)) {
                                                            if (o.has(Sauthor) && o.has(SrecentComments)) {
                                                                JSONObject f = o.getJSONObject(Sauthor);
                                                                if (f.has(SdisplayName) && f.has(Sid)) {
                                                                    String notification = null;
                                                                    String esid = f.getString(Sid);
                                                                    String friend = f.getString(SdisplayName);
                                                                    JSONArray comments = o
                                                                            .getJSONArray(SrecentComments);
                                                                    int commentCount = comments.length();
                                                                    // notifications
                                                                    if ((sid != null) && (commentCount > 0)) {
                                                                        // default hasCommented to whether or not these comments are for the own user's status
                                                                        boolean hasCommented = notification != null
                                                                                || esid.equals(accountEsid);
                                                                        for (int c2 = 0; c2 < commentCount; c2++) {
                                                                            JSONObject c3 = comments
                                                                                    .getJSONObject(c2);
                                                                            if (c3.has(Sauthor)) {
                                                                                JSONObject c4 = c3
                                                                                        .getJSONObject(Sauthor);
                                                                                if (c4.getString(Sid)
                                                                                        .equals(accountEsid)) {
                                                                                    if (!hasCommented) {
                                                                                        // the user has commented on this thread, notify any updates
                                                                                        hasCommented = true;
                                                                                    }
                                                                                    // clear any notifications, as the user is already aware
                                                                                    if (notification != null) {
                                                                                        notification = null;
                                                                                    }
                                                                                } else if (hasCommented) {
                                                                                    // don't notify about user's own comments
                                                                                    // send the parent comment sid
                                                                                    notification = String
                                                                                            .format(getString(
                                                                                                    R.string.friendcommented),
                                                                                                    c4.getString(
                                                                                                            SdisplayName));
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                    if (notification != null) {
                                                                        // new notification
                                                                        addNotification(sid, esid, friend,
                                                                                o.getString(Sstatus),
                                                                                parseDate(o.getString(
                                                                                        "moodStatusLastUpdated"),
                                                                                        MYSPACE_DATE_FORMAT),
                                                                                accountId, notification);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            } catch (JSONException e) {
                                                Log.e(TAG, service + ":" + e.toString());
                                            }
                                        }
                                        break;
                                    case FOURSQUARE:
                                        // loop over notifications
                                        while (!currentNotifications.isAfterLast()) {
                                            long notificationId = currentNotifications.getLong(0);
                                            String sid = mSonetCrypto
                                                    .Decrypt(currentNotifications.getString(1));
                                            long updated = currentNotifications.getLong(2);
                                            boolean cleared = currentNotifications.getInt(3) == 1;
                                            // store sids, to avoid duplicates when requesting the latest feed
                                            if (!notificationSids.contains(sid)) {
                                                notificationSids.add(sid);
                                            }
                                            // get comments for current notifications
                                            if ((response = SonetHttpClient.httpResponse(httpClient,
                                                    new HttpGet(String.format(FOURSQUARE_GET_CHECKIN,
                                                            FOURSQUARE_BASE_URL, sid, token)))) != null) {
                                                // check for a newer post, if it's the user's own, then set CLEARED=0
                                                try {
                                                    JSONArray comments = new JSONObject(response)
                                                            .getJSONObject(Sresponse).getJSONObject(Scheckin)
                                                            .getJSONObject(Scomments).getJSONArray(Sitems);
                                                    int i2 = comments.length();
                                                    if (i2 > 0) {
                                                        for (int i = 0; i < i2; i++) {
                                                            JSONObject comment = comments.getJSONObject(i);
                                                            long created_time = comment.getLong(ScreatedAt)
                                                                    * 1000;
                                                            if (created_time > updated) {
                                                                // new comment
                                                                ContentValues values = new ContentValues();
                                                                values.put(Notifications.UPDATED, created_time);
                                                                JSONObject user = comment.getJSONObject(Suser);
                                                                if (accountEsid.equals(user.getString(Sid))) {
                                                                    // user's own comment, clear the notification
                                                                    values.put(Notifications.CLEARED, 1);
                                                                } else if (cleared) {
                                                                    values.put(Notifications.NOTIFICATION,
                                                                            String.format(getString(
                                                                                    R.string.friendcommented),
                                                                                    user.getString(SfirstName)
                                                                                            + " "
                                                                                            + user.getString(
                                                                                                    SlastName)));
                                                                    values.put(Notifications.CLEARED, 0);
                                                                } else {
                                                                    values.put(Notifications.NOTIFICATION,
                                                                            String.format(getString(
                                                                                    R.string.friendcommented),
                                                                                    user.getString(SfirstName)
                                                                                            + " "
                                                                                            + user.getString(
                                                                                                    SlastName)
                                                                                            + " and others"));
                                                                }
                                                                getContentResolver().update(
                                                                        Notifications.getContentUri(
                                                                                SonetNotifications.this),
                                                                        values, Notifications._ID + "=?",
                                                                        new String[] { Long
                                                                                .toString(notificationId) });
                                                            }
                                                        }
                                                    }
                                                } catch (JSONException e) {
                                                    Log.e(TAG, service + ":" + e.toString());
                                                }
                                            }
                                            currentNotifications.moveToNext();
                                        }
                                        // check the latest feed
                                        if ((response = SonetHttpClient.httpResponse(httpClient,
                                                new HttpGet(String.format(FOURSQUARE_CHECKINS,
                                                        FOURSQUARE_BASE_URL, token)))) != null) {
                                            try {
                                                JSONArray jarr = new JSONObject(response)
                                                        .getJSONObject(Sresponse).getJSONArray(Srecent);
                                                // if there are updates, clear the cache
                                                int d2 = jarr.length();
                                                if (d2 > 0) {
                                                    for (int d = 0; d < d2; d++) {
                                                        JSONObject o = jarr.getJSONObject(d);
                                                        String sid = o.getString(Sid);
                                                        // if already notified, ignore
                                                        if (!notificationSids.contains(sid)) {
                                                            if (o.has(Suser) && o.has(Scomments)) {
                                                                JSONObject f = o.getJSONObject(Suser);
                                                                if (f.has(SfirstName) && f.has(SlastName)
                                                                        && f.has(Sid)) {
                                                                    String notification = null;
                                                                    String esid = f.getString(Sid);
                                                                    String friend = f.getString(SfirstName)
                                                                            + " " + f.getString(SlastName);
                                                                    JSONArray comments = o
                                                                            .getJSONArray(Scomments);
                                                                    int commentCount = comments.length();
                                                                    // notifications
                                                                    if (commentCount > 0) {
                                                                        // default hasCommented to whether or not these comments are for the own user's status
                                                                        boolean hasCommented = notification != null
                                                                                || esid.equals(accountEsid);
                                                                        for (int c2 = 0; c2 < commentCount; c2++) {
                                                                            JSONObject c3 = comments
                                                                                    .getJSONObject(c2);
                                                                            if (c3.has(Suser)) {
                                                                                JSONObject c4 = c3
                                                                                        .getJSONObject(Suser);
                                                                                if (c4.getString(Sid)
                                                                                        .equals(accountEsid)) {
                                                                                    if (!hasCommented) {
                                                                                        // the user has commented on this thread, notify any updates
                                                                                        hasCommented = true;
                                                                                    }
                                                                                    // clear any notifications, as the user is already aware
                                                                                    if (notification != null) {
                                                                                        notification = null;
                                                                                    }
                                                                                } else if (hasCommented) {
                                                                                    // don't notify about user's own comments
                                                                                    // send the parent comment sid
                                                                                    notification = String
                                                                                            .format(getString(
                                                                                                    R.string.friendcommented),
                                                                                                    c4.getString(
                                                                                                            SfirstName)
                                                                                                            + " "
                                                                                                            + c4.getString(
                                                                                                                    SlastName));
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                    if (notification != null) {
                                                                        String message = "";
                                                                        if (o.has(Sshout)) {
                                                                            message = o.getString(Sshout)
                                                                                    + "\n";
                                                                        }
                                                                        if (o.has(Svenue)) {
                                                                            JSONObject venue = o
                                                                                    .getJSONObject(Svenue);
                                                                            if (venue.has(Sname)) {
                                                                                message += "@" + venue
                                                                                        .getString(Sname);
                                                                            }
                                                                        }
                                                                        // new notification
                                                                        addNotification(sid, esid, friend,
                                                                                message,
                                                                                o.getLong(ScreatedAt) * 1000,
                                                                                accountId, notification);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            } catch (JSONException e) {
                                                Log.e(TAG, service + ":" + e.toString());
                                            }
                                        }
                                        break;
                                    case LINKEDIN:
                                        sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY,
                                                BuildConfig.LINKEDIN_SECRET, token, secret);
                                        // loop over notifications
                                        while (!currentNotifications.isAfterLast()) {
                                            long notificationId = currentNotifications.getLong(0);
                                            String sid = mSonetCrypto
                                                    .Decrypt(currentNotifications.getString(1));
                                            long updated = currentNotifications.getLong(2);
                                            boolean cleared = currentNotifications.getInt(3) == 1;
                                            // store sids, to avoid duplicates when requesting the latest feed
                                            if (!notificationSids.contains(sid)) {
                                                notificationSids.add(sid);
                                            }
                                            // get comments for current notifications
                                            HttpGet httpGet = new HttpGet(String
                                                    .format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, sid));
                                            for (String[] header : LINKEDIN_HEADERS)
                                                httpGet.setHeader(header[0], header[1]);
                                            if ((response = SonetHttpClient.httpResponse(httpClient,
                                                    sonetOAuth.getSignedRequest(httpGet))) != null) {
                                                // check for a newer post, if it's the user's own, then set CLEARED=0
                                                try {
                                                    JSONObject jsonResponse = new JSONObject(response);
                                                    if (jsonResponse.has(S_total)
                                                            && (jsonResponse.getInt(S_total) != 0)) {
                                                        JSONArray comments = jsonResponse.getJSONArray(Svalues);
                                                        int i2 = comments.length();
                                                        if (i2 > 0) {
                                                            for (int i = 0; i < i2; i++) {
                                                                JSONObject comment = comments.getJSONObject(i);
                                                                long created_time = comment.getLong(Stimestamp);
                                                                if (created_time > updated) {
                                                                    // new comment
                                                                    ContentValues values = new ContentValues();
                                                                    values.put(Notifications.UPDATED,
                                                                            created_time);
                                                                    JSONObject person = comment
                                                                            .getJSONObject(Sperson);
                                                                    if (accountEsid
                                                                            .equals(person.getString(Sid))) {
                                                                        // user's own comment, clear the notification
                                                                        values.put(Notifications.CLEARED, 1);
                                                                    } else if (cleared) {
                                                                        values.put(Notifications.NOTIFICATION,
                                                                                String.format(getString(
                                                                                        R.string.friendcommented),
                                                                                        person.getString(
                                                                                                SfirstName)
                                                                                                + " "
                                                                                                + person.getString(
                                                                                                        SlastName)));
                                                                        values.put(Notifications.CLEARED, 0);
                                                                    } else {
                                                                        values.put(Notifications.NOTIFICATION,
                                                                                String.format(getString(
                                                                                        R.string.friendcommented),
                                                                                        person.getString(
                                                                                                SfirstName)
                                                                                                + " "
                                                                                                + person.getString(
                                                                                                        SlastName)
                                                                                                + " and others"));
                                                                    }
                                                                    getContentResolver().update(
                                                                            Notifications.getContentUri(
                                                                                    SonetNotifications.this),
                                                                            values, Notifications._ID + "=?",
                                                                            new String[] { Long.toString(
                                                                                    notificationId) });
                                                                }
                                                            }
                                                        }
                                                    }
                                                } catch (JSONException e) {
                                                    Log.e(TAG, service + ":" + e.toString());
                                                }
                                            }
                                            currentNotifications.moveToNext();
                                        }
                                        // check the latest feed
                                        HttpGet httpGet = new HttpGet(
                                                String.format(LINKEDIN_UPDATES, LINKEDIN_BASE_URL));
                                        for (String[] header : LINKEDIN_HEADERS) {
                                            httpGet.setHeader(header[0], header[1]);
                                        }
                                        if ((response = SonetHttpClient.httpResponse(httpClient,
                                                sonetOAuth.getSignedRequest(httpGet))) != null) {
                                            try {
                                                JSONArray jarr = new JSONObject(response).getJSONArray(Svalues);
                                                // if there are updates, clear the cache
                                                int d2 = jarr.length();
                                                if (d2 > 0) {
                                                    for (int d = 0; d < d2; d++) {
                                                        JSONObject o = jarr.getJSONObject(d);
                                                        String sid = o.getString(SupdateKey);
                                                        // if already notified, ignore
                                                        if (!notificationSids.contains(sid)) {
                                                            String updateType = o.getString(SupdateType);
                                                            JSONObject updateContent = o
                                                                    .getJSONObject(SupdateContent);
                                                            if (LinkedIn_UpdateTypes.contains(updateType)
                                                                    && updateContent.has(Sperson)) {
                                                                JSONObject f = updateContent
                                                                        .getJSONObject(Sperson);
                                                                if (f.has(SfirstName) && f.has(SlastName)
                                                                        && f.has(Sid)
                                                                        && o.has(SupdateComments)) {
                                                                    JSONObject updateComments = o
                                                                            .getJSONObject(SupdateComments);
                                                                    if (updateComments.has(Svalues)) {
                                                                        String notification = null;
                                                                        String esid = f.getString(Sid);
                                                                        JSONArray comments = updateComments
                                                                                .getJSONArray(Svalues);
                                                                        int commentCount = comments.length();
                                                                        // notifications
                                                                        if (commentCount > 0) {
                                                                            // default hasCommented to whether or not these comments are for the own user's status
                                                                            boolean hasCommented = notification != null
                                                                                    || esid.equals(accountEsid);
                                                                            for (int c2 = 0; c2 < commentCount; c2++) {
                                                                                JSONObject c3 = comments
                                                                                        .getJSONObject(c2);
                                                                                if (c3.has(Sperson)) {
                                                                                    JSONObject c4 = c3
                                                                                            .getJSONObject(
                                                                                                    Sperson);
                                                                                    if (c4.getString(Sid)
                                                                                            .equals(accountEsid)) {
                                                                                        if (!hasCommented) {
                                                                                            // the user has commented on this thread, notify any updates
                                                                                            hasCommented = true;
                                                                                        }
                                                                                        // clear any notifications, as the user is already aware
                                                                                        if (notification != null) {
                                                                                            notification = null;
                                                                                        }
                                                                                    } else if (hasCommented) {
                                                                                        // don't notify about user's own comments
                                                                                        // send the parent comment sid
                                                                                        notification = String
                                                                                                .format(getString(
                                                                                                        R.string.friendcommented),
                                                                                                        c4.getString(
                                                                                                                SfirstName)
                                                                                                                + " "
                                                                                                                + c4.getString(
                                                                                                                        SlastName));
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                        if (notification != null) {
                                                                            String update = LinkedIn_UpdateTypes
                                                                                    .getMessage(updateType);
                                                                            if (LinkedIn_UpdateTypes.APPS.name()
                                                                                    .equals(updateType)) {
                                                                                if (f.has(SpersonActivities)) {
                                                                                    JSONObject personActivities = f
                                                                                            .getJSONObject(
                                                                                                    SpersonActivities);
                                                                                    if (personActivities
                                                                                            .has(Svalues)) {
                                                                                        JSONArray updates = personActivities
                                                                                                .getJSONArray(
                                                                                                        Svalues);
                                                                                        for (int u = 0, u2 = updates
                                                                                                .length(); u < u2; u++) {
                                                                                            update += updates
                                                                                                    .getJSONObject(
                                                                                                            u)
                                                                                                    .getString(
                                                                                                            Sbody);
                                                                                            if (u < (updates
                                                                                                    .length()
                                                                                                    - 1))
                                                                                                update += ", ";
                                                                                        }
                                                                                    }
                                                                                }
                                                                            } else if (LinkedIn_UpdateTypes.CONN
                                                                                    .name()
                                                                                    .equals(updateType)) {
                                                                                if (f.has(Sconnections)) {
                                                                                    JSONObject connections = f
                                                                                            .getJSONObject(
                                                                                                    Sconnections);
                                                                                    if (connections
                                                                                            .has(Svalues)) {
                                                                                        JSONArray updates = connections
                                                                                                .getJSONArray(
                                                                                                        Svalues);
                                                                                        for (int u = 0, u2 = updates
                                                                                                .length(); u < u2; u++) {
                                                                                            update += updates
                                                                                                    .getJSONObject(
                                                                                                            u)
                                                                                                    .getString(
                                                                                                            SfirstName)
                                                                                                    + " "
                                                                                                    + updates
                                                                                                            .getJSONObject(
                                                                                                                    u)
                                                                                                            .getString(
                                                                                                                    SlastName);
                                                                                            if (u < (updates
                                                                                                    .length()
                                                                                                    - 1))
                                                                                                update += ", ";
                                                                                        }
                                                                                    }
                                                                                }
                                                                            } else if (LinkedIn_UpdateTypes.JOBP
                                                                                    .name()
                                                                                    .equals(updateType)) {
                                                                                if (updateContent.has(Sjob)
                                                                                        && updateContent
                                                                                                .getJSONObject(
                                                                                                        Sjob)
                                                                                                .has(Sposition)
                                                                                        && updateContent
                                                                                                .getJSONObject(
                                                                                                        Sjob)
                                                                                                .getJSONObject(
                                                                                                        Sposition)
                                                                                                .has(Stitle))
                                                                                    update += updateContent
                                                                                            .getJSONObject(Sjob)
                                                                                            .getJSONObject(
                                                                                                    Sposition)
                                                                                            .getString(Stitle);
                                                                            } else if (LinkedIn_UpdateTypes.JGRP
                                                                                    .name()
                                                                                    .equals(updateType)) {
                                                                                if (f.has(SmemberGroups)) {
                                                                                    JSONObject memberGroups = f
                                                                                            .getJSONObject(
                                                                                                    SmemberGroups);
                                                                                    if (memberGroups
                                                                                            .has(Svalues)) {
                                                                                        JSONArray updates = memberGroups
                                                                                                .getJSONArray(
                                                                                                        Svalues);
                                                                                        for (int u = 0, u2 = updates
                                                                                                .length(); u < u2; u++) {
                                                                                            update += updates
                                                                                                    .getJSONObject(
                                                                                                            u)
                                                                                                    .getString(
                                                                                                            Sname);
                                                                                            if (u < (updates
                                                                                                    .length()
                                                                                                    - 1))
                                                                                                update += ", ";
                                                                                        }
                                                                                    }
                                                                                }
                                                                            } else if (LinkedIn_UpdateTypes.PREC
                                                                                    .name()
                                                                                    .equals(updateType)) {
                                                                                if (f.has(
                                                                                        SrecommendationsGiven)) {
                                                                                    JSONObject recommendationsGiven = f
                                                                                            .getJSONObject(
                                                                                                    SrecommendationsGiven);
                                                                                    if (recommendationsGiven
                                                                                            .has(Svalues)) {
                                                                                        JSONArray updates = recommendationsGiven
                                                                                                .getJSONArray(
                                                                                                        Svalues);
                                                                                        for (int u = 0, u2 = updates
                                                                                                .length(); u < u2; u++) {
                                                                                            JSONObject recommendation = updates
                                                                                                    .getJSONObject(
                                                                                                            u);
                                                                                            JSONObject recommendee = recommendation
                                                                                                    .getJSONObject(
                                                                                                            Srecommendee);
                                                                                            if (recommendee.has(
                                                                                                    SfirstName))
                                                                                                update += recommendee
                                                                                                        .getString(
                                                                                                                SfirstName);
                                                                                            if (recommendee.has(
                                                                                                    SlastName))
                                                                                                update += recommendee
                                                                                                        .getString(
                                                                                                                SlastName);
                                                                                            if (recommendation
                                                                                                    .has(SrecommendationSnippet))
                                                                                                update += ":"
                                                                                                        + recommendation
                                                                                                                .getString(
                                                                                                                        SrecommendationSnippet);
                                                                                            if (u < (updates
                                                                                                    .length()
                                                                                                    - 1))
                                                                                                update += ", ";
                                                                                        }
                                                                                    }
                                                                                }
                                                                            } else if (LinkedIn_UpdateTypes.SHAR
                                                                                    .name().equals(updateType)
                                                                                    && f.has(ScurrentShare)) {
                                                                                JSONObject currentShare = f
                                                                                        .getJSONObject(
                                                                                                ScurrentShare);
                                                                                if (currentShare.has(Scomment))
                                                                                    update = currentShare
                                                                                            .getString(
                                                                                                    Scomment);
                                                                            }
                                                                            // new notification
                                                                            addNotification(sid, esid,
                                                                                    f.getString(SfirstName)
                                                                                            + " "
                                                                                            + f.getString(
                                                                                                    SlastName),
                                                                                    update,
                                                                                    o.getLong(Stimestamp),
                                                                                    accountId, notification);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            } catch (JSONException e) {
                                                Log.e(TAG, service + ":" + e.toString());
                                            }
                                        }
                                        break;
                                    case GOOGLEPLUS:
                                        // get new access token, need different request here
                                        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", token));
                                        httpParams.add(new BasicNameValuePair("grant_type", "refresh_token"));
                                        try {
                                            httpPost.setEntity(new UrlEncodedFormEntity(httpParams));
                                            if ((response = SonetHttpClient.httpResponse(httpClient,
                                                    httpPost)) != null) {
                                                JSONObject j = new JSONObject(response);
                                                if (j.has(Saccess_token)) {
                                                    String access_token = j.getString(Saccess_token);
                                                    while (!currentNotifications.isAfterLast()) {
                                                        long notificationId = currentNotifications.getLong(0);
                                                        String sid = mSonetCrypto
                                                                .Decrypt(currentNotifications.getString(1));
                                                        long updated = currentNotifications.getLong(2);
                                                        boolean cleared = currentNotifications.getInt(3) == 1;
                                                        // store sids, to avoid duplicates when requesting the latest feed
                                                        if (!notificationSids.contains(sid)) {
                                                            notificationSids.add(sid);
                                                        }
                                                        // get comments for current notifications
                                                        if ((response = SonetHttpClient.httpResponse(httpClient,
                                                                new HttpGet(String.format(GOOGLEPLUS_ACTIVITY,
                                                                        GOOGLEPLUS_BASE_URL, sid,
                                                                        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: notifications
                                                                        }
                                                                    }
                                                                }
                                                            } catch (JSONException e) {
                                                                Log.e(TAG, service + ":" + e.toString());
                                                            }
                                                        }
                                                        currentNotifications.moveToNext();
                                                    }
                                                    // get new feed
                                                    if ((response = SonetHttpClient.httpResponse(httpClient,
                                                            new HttpGet(String.format(GOOGLEPLUS_ACTIVITIES,
                                                                    GOOGLEPLUS_BASE_URL, "me", "public", 20,
                                                                    access_token)))) != null) {
                                                        JSONObject r = new JSONObject(response);
                                                        if (r.has(Sitems)) {
                                                            JSONArray items = r.getJSONArray(Sitems);
                                                            for (int i1 = 0, i2 = items
                                                                    .length(); i1 < i2; i1++) {
                                                                JSONObject item = items.getJSONObject(i1);
                                                                if (item.has(Sactor) && item.has(Sobject)) {
                                                                    JSONObject actor = item
                                                                            .getJSONObject(Sactor);
                                                                    JSONObject object = item
                                                                            .getJSONObject(Sobject);
                                                                    if (item.has(Sid) && actor.has(Sid)
                                                                            && actor.has(SdisplayName)
                                                                            && item.has(Spublished)
                                                                            && object.has(Sreplies)
                                                                            && object.has(SoriginalContent)) {
                                                                        String sid = item.getString(Sid);
                                                                        String esid = actor.getString(Sid);
                                                                        String friend = actor
                                                                                .getString(SdisplayName);
                                                                        String originalContent = object
                                                                                .getString(SoriginalContent);
                                                                        if ((originalContent == null)
                                                                                || (originalContent
                                                                                        .length() == 0)) {
                                                                            originalContent = object
                                                                                    .getString(Scontent);
                                                                        }
                                                                        String photo = null;
                                                                        if (actor.has(Simage)) {
                                                                            JSONObject image = actor
                                                                                    .getJSONObject(Simage);
                                                                            if (image.has(Surl)) {
                                                                                photo = image.getString(Surl);
                                                                            }
                                                                        }
                                                                        long date = parseDate(
                                                                                item.getString(Spublished),
                                                                                GOOGLEPLUS_DATE_FORMAT);
                                                                        int commentCount = 0;
                                                                        JSONObject replies = object
                                                                                .getJSONObject(Sreplies);
                                                                        String notification = null;
                                                                        if (replies.has(StotalItems)) {
                                                                            Log.d(TAG, Sreplies + ":"
                                                                                    + replies.toString());
                                                                            commentCount = replies
                                                                                    .getInt(StotalItems);
                                                                        }
                                                                        if (notification != null) {
                                                                            // new notification
                                                                            addNotification(sid, esid, friend,
                                                                                    originalContent, date,
                                                                                    accountId, notification);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        } catch (UnsupportedEncodingException e) {
                                            Log.e(TAG, e.toString());
                                        } catch (JSONException e) {
                                            Log.e(TAG, e.toString());
                                        }
                                        break;
                                    }
                                }
                                currentNotifications.close();
                            }
                            // remove old notifications
                            getContentResolver().delete(Notifications.getContentUri(SonetNotifications.this),
                                    Notifications.CLEARED + "=1 and " + Notifications.ACCOUNT + "=? and "
                                            + Notifications.CREATED + "<?",
                                    new String[] { Long.toString(accountId),
                                            Long.toString(System.currentTimeMillis() - 86400000) });
                        }
                        account.close();
                        widgets.moveToNext();
                    }
                } else {
                    publishProgress("No notifications have been set up on any accounts.");
                }
                widgets.close();
                return false;
            } else if (arg0[0] == R.id.menu_notifications_clear_all) {
                // clear all notifications
                ContentValues values = new ContentValues();
                values.put(Notifications.CLEARED, 1);
                SonetNotifications.this.getContentResolver()
                        .update(Notifications.getContentUri(SonetNotifications.this), values, null, null);
                return true;
            }
            return false;
        }

        @Override
        protected void onProgressUpdate(String... messages) {
            (Toast.makeText(SonetNotifications.this, messages[0], Toast.LENGTH_LONG)).show();
        }

        @Override
        protected void onPostExecute(Boolean finish) {
            if (loadingDialog.isShowing()) {
                loadingDialog.dismiss();
            }
            if (finish) {
                SonetNotifications.this.finish();
            }
        }

        private void addNotification(String sid, String esid, String friend, String message, long created,
                long accountId, String notification) {
            ContentValues values = new ContentValues();
            values.put(Notifications.SID, sid);
            values.put(Notifications.ESID, esid);
            values.put(Notifications.FRIEND, friend);
            values.put(Notifications.MESSAGE, message);
            values.put(Notifications.CREATED, created);
            values.put(Notifications.ACCOUNT, accountId);
            values.put(Notifications.NOTIFICATION, notification);
            values.put(Notifications.CLEARED, 0);
            values.put(Notifications.UPDATED, created);
            getContentResolver().insert(Notifications.getContentUri(SonetNotifications.this), values);
        }

        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(item.getItemId());
    return true;
    //      return super.onOptionsItemSelected(item);
}

From source file:com.projectgoth.mywebrtcdemo.WebSocketRTCClient.java

@Override
public void onWebSocketMessage(final String msg) {
    if (wsClient.getState() != WebSocketConnectionState.REGISTERED) {
        Log.e(TAG, "Got WebSocket message in non registered state.");
        return;/*from   www. j  a  v a 2 s  .  c  o  m*/
    }
    try {
        JSONObject json = new JSONObject(msg);
        String msgText = json.getString("msg");
        String errorText = json.optString("error");
        if (msgText.length() > 0) {
            json = new JSONObject(msgText);
            String type = json.optString("type");
            if (type.equals("candidate")) {
                IceCandidate candidate = new IceCandidate(json.getString("id"), json.getInt("label"),
                        json.getString("candidate"));
                events.onRemoteIceCandidate(candidate);
            } else if (type.equals("answer")) {
                if (initiator) {
                    SessionDescription sdp = new SessionDescription(
                            SessionDescription.Type.fromCanonicalForm(type), json.getString("sdp"));
                    events.onRemoteDescription(sdp);
                } else {
                    reportError("Received answer for call initiator: " + msg);
                }
            } else if (type.equals("offer")) {
                if (!initiator) {
                    SessionDescription sdp = new SessionDescription(
                            SessionDescription.Type.fromCanonicalForm(type), json.getString("sdp"));
                    events.onRemoteDescription(sdp);
                } else {
                    reportError("Received offer for call receiver: " + msg);
                }
            } else if (type.equals("bye")) {
                events.onChannelClose();
            } else {
                reportError("Unexpected WebSocket message: " + msg);
            }
        } else {
            if (errorText != null && errorText.length() > 0) {
                reportError("WebSocket error message: " + errorText);
            } else {
                reportError("Unexpected WebSocket message: " + msg);
            }
        }
    } catch (JSONException e) {
        reportError("WebSocket message JSON parsing error: " + e.toString());
    }
}

From source file:com.projectgoth.mywebrtcdemo.WebSocketRTCClient.java

private void sendPostMessage(final MessageType messageType, final String url, final String message) {
    String logInfo = url;/*  ww  w.ja  v  a2s.  c  o m*/
    if (message != null) {
        logInfo += ". Message: " + message;
    }
    Log.d(TAG, "C->GAE: " + logInfo);
    AsyncHttpURLConnection httpConnection = new AsyncHttpURLConnection("POST", url, message,
            new AsyncHttpEvents() {
                @Override
                public void onHttpError(String errorMessage) {
                    reportError("GAE POST error: " + errorMessage);
                }

                @Override
                public void onHttpComplete(String response) {
                    if (messageType == MessageType.MESSAGE) {
                        try {
                            JSONObject roomJson = new JSONObject(response);
                            String result = roomJson.getString("result");
                            if (!result.equals("SUCCESS")) {
                                reportError("GAE POST error: " + result);
                            }
                        } catch (JSONException e) {
                            reportError("GAE POST JSON error: " + e.toString());
                        }
                    }
                }
            });
    httpConnection.send();
}

From source file:com.piusvelte.sonet.SonetComments.java

private void loadComments() {
    mComments.clear();/*from w  ww  . j  ava  2  s  . com*/
    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:com.ibm.mobilefirstplatform.clientsdk.cordovaplugins.push.CDVMFPPush.java

private void registerNotificationsCallback(final CallbackContext callbackContext) {
    pushLogger.debug("In registerNotificationsCallback");

    notificationCallback = callbackContext;

    if (!ignoreIncomingNotifications) {

        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                notificationListener = new MFPPushNotificationListener() {
                    @Override//from w w w.j av  a  2 s  .  c  o  m
                    public void onReceive(final MFPSimplePushNotification message) {
                        try {
                            pushLogger.debug("Push notification received: " + message.toString());

                            JSONObject notification = new JSONObject();

                            notification.put("message", message.getAlert());
                            notification.put("payload", message.getPayload());

                            PluginResult result = new PluginResult(PluginResult.Status.OK, notification);
                            result.setKeepCallback(true);
                            notificationCallback.sendPluginResult(result);
                        } catch (JSONException e) {
                            PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.toString());
                            result.setKeepCallback(true);
                            notificationCallback.sendPluginResult(result);
                        }
                    }
                };

                MFPPush.getInstance().listen(notificationListener);
            }
        });

    } else {
        pushLogger.warn(
                "Notification handling is currently off. Turn it back on by calling setIgnoreIncomingNotifications(true)");
        callbackContext.error(
                "Error: Called registerNotificationsCallback() after IgnoreIncomingNotifications was set");
    }
}

From source file:org.openmrs.mobile.listeners.visit.EndVisitByUUIDListener.java

@Override
public void onResponse(final JSONObject response) {
    mLogger.d(response.toString());//w w  w  . j  a  v  a2s  .  c  o  m
    try {
        Visit visit = visitDAO.getVisitsByID(mVisitID);
        visit.setStopDate(DateUtils.convertTime(response.getString(VisitsManager.STOP_DATE_TIME)));
        visitDAO.updateVisit(visit, mVisitID, mPatientID);
        mCaller.moveToPatientDashboard();
    } catch (JSONException e) {
        mLogger.d(e.toString());
    }
}

From source file:curt.android.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException, InterruptedException {

    String contents = HttpHelper.downloadViaHttp("https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn,
            HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;/*from   w w w . java 2 s. c o m*/
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>();
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e.toString());
    }

    Collection<String> newTexts = new ArrayList<String>();

    if (title != null && title.length() > 0) {
        newTexts.add(title);
    }

    if (authors != null && !authors.isEmpty()) {
        boolean first = true;
        StringBuilder authorsText = new StringBuilder();
        for (String author : authors) {
            if (first) {
                first = false;
            } else {
                authorsText.append(", ");
            }
            authorsText.append(author);
        }
        newTexts.add(authorsText.toString());
    }

    if (pages != null && pages.length() > 0) {
        newTexts.add(pages + "pp.");
    }

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}

From source file:com.piusvelte.sonet.core.StatusDialog.java

@Override
public void onClick(final DialogInterface dialog, int which) {
    switch (which) {
    case COMMENT:
        if (mAppWidgetId != -1) {
            if (mService == GOOGLEPLUS)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://plus.google.com")));
            else if (mService == PINTEREST) {
                if (mSid != null)
                    startActivity(new Intent(Intent.ACTION_VIEW)
                            .setData(Uri.parse(String.format(PINTEREST_PIN, mSid))));
                else
                    startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            } else
                startActivity(Sonet.getPackageIntent(this, SonetComments.class).setData(mData));
        } else//from   ww  w  . j  a va2s  .c  o m
            (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
        dialog.cancel();
        finish();
        break;
    case POST:
        if (mAppWidgetId != -1) {
            if (mService == GOOGLEPLUS)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://plus.google.com")));
            else if (mService == PINTEREST)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            else
                startActivity(Sonet.getPackageIntent(this, SonetCreatePost.class).setData(Uri
                        .withAppendedPath(Accounts.getContentUri(StatusDialog.this), Long.toString(mAccount))));
            dialog.cancel();
            finish();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // no account, dialog to select one
                        // don't limit accounts to the widget
                        Cursor c = StatusDialog.this.getContentResolver().query(
                                Accounts.getContentUri(StatusDialog.this),
                                new String[] { Accounts._ID, ACCOUNTS_QUERY }, null, null, null);
                        if (c.moveToFirst()) {
                            int iid = c.getColumnIndex(Accounts._ID),
                                    iusername = c.getColumnIndex(Accounts.USERNAME), i = 0;
                            final long[] accountIndexes = new long[c.getCount()];
                            final String[] accounts = new String[c.getCount()];
                            while (!c.isAfterLast()) {
                                long id = c.getLong(iid);
                                accountIndexes[i] = id;
                                accounts[i++] = c.getString(iusername);
                                c.moveToNext();
                            }
                            arg0.cancel();
                            mDialog = (new AlertDialog.Builder(StatusDialog.this)).setTitle(R.string.accounts)
                                    .setSingleChoiceItems(accounts, -1, new OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface arg0, int which) {
                                            startActivity(Sonet
                                                    .getPackageIntent(StatusDialog.this, SonetCreatePost.class)
                                                    .setData(Uri.withAppendedPath(
                                                            Accounts.getContentUri(StatusDialog.this),
                                                            Long.toString(accountIndexes[which]))));
                                            arg0.cancel();
                                        }
                                    }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                                        @Override
                                        public void onCancel(DialogInterface arg0) {
                                            dialog.cancel();
                                        }
                                    }).create();
                            mDialog.show();
                        } else {
                            (Toast.makeText(StatusDialog.this, getString(R.string.error_status),
                                    Toast.LENGTH_LONG)).show();
                            dialog.cancel();
                        }
                        c.close();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
                dialog.cancel();
                finish();
            }
        }
        break;
    case SETTINGS:
        if (mAppWidgetId != -1) {
            startActivity(Sonet.getPackageIntent(this, ManageAccounts.class)
                    .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId));
            dialog.cancel();
            finish();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        startActivity(Sonet.getPackageIntent(StatusDialog.this, ManageAccounts.class)
                                .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetIds[arg1]));
                        arg0.cancel();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
                dialog.cancel();
                finish();
            }
        }
        break;
    case NOTIFICATIONS:
        startActivity(Sonet.getPackageIntent(this, SonetNotifications.class));
        dialog.cancel();
        finish();
        break;
    case REFRESH:
        if (mAppWidgetId != -1) {
            (Toast.makeText(getApplicationContext(), getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
            startService(Sonet.getPackageIntent(this, SonetService.class).setAction(ACTION_REFRESH)
                    .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { mAppWidgetId }));
            dialog.cancel();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        (Toast.makeText(StatusDialog.this.getApplicationContext(),
                                getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
                        startService(Sonet.getPackageIntent(StatusDialog.this, SonetService.class)
                                .setAction(ACTION_REFRESH).putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
                                        new int[] { mAppWidgetIds[arg1] }));
                        arg0.cancel();
                        finish();
                    }
                }).setPositiveButton(R.string.refreshallwidgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int which) {
                        // refresh all
                        (Toast.makeText(StatusDialog.this.getApplicationContext(),
                                getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
                        startService(Sonet.getPackageIntent(StatusDialog.this, SonetService.class)
                                .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, mAppWidgetIds));
                        arg0.cancel();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                dialog.cancel();
                finish();
            }
        }
        break;
    case PROFILE:
        Cursor account;
        final AsyncTask<String, Void, String> asyncTask;
        // get the resources
        switch (mService) {
        case TWITTER:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET, arg0[0], arg0[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(
                                        new HttpGet(String.format(TWITTER_USER, TWITTER_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject user = new JSONObject(response);
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri
                                        .parse(String.format(TWITTER_PROFILE, user.getString("screen_name")))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                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();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case FACEBOOK:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                new HttpGet(String.format(FACEBOOK_USER, FACEBOOK_BASE_URL, mEsid,
                                        Saccess_token, arg0[0])));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW)
                                        .setData(Uri.parse((new JSONObject(response)).getString("link"))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                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();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))));
            }
            account.close();
            break;
        case MYSPACE:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(MYSPACE_KEY, MYSPACE_SECRET, arg0[0], arg0[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(
                                        new HttpGet(String.format(MYSPACE_USER, MYSPACE_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW)
                                        .setData(Uri.parse((new JSONObject(response)).getJSONObject("person")
                                                .getString("profileUrl"))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                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();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case FOURSQUARE:
            startActivity(new Intent(Intent.ACTION_VIEW)
                    .setData(Uri.parse(String.format(FOURSQUARE_URL_PROFILE, mEsid))));
            finish();
            break;
        case LINKEDIN:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, arg0[0], arg0[1]);
                        HttpGet httpGet = new HttpGet(String.format(LINKEDIN_URL_USER, mEsid));
                        for (String[] header : LINKEDIN_HEADERS)
                            httpGet.setHeader(header[0], header[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(httpGet));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(
                                        (new JSONObject(response)).getJSONObject("siteStandardProfileRequest")
                                                .getString("url").replaceAll("\\\\", ""))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                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();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case IDENTICA:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET, arg0[0], arg0[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(
                                        new HttpGet(String.format(IDENTICA_USER, IDENTICA_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject user = new JSONObject(response);
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(
                                        String.format(IDENTICA_PROFILE, user.getString("screen_name")))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                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();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case GOOGLEPLUS:
            startActivity(new Intent(Intent.ACTION_VIEW)
                    .setData(Uri.parse(String.format(GOOGLEPLUS_PROFILE, mEsid))));
            finish();
            break;
        case PINTEREST:
            if (mEsid != null)
                startActivity(new Intent(Intent.ACTION_VIEW)
                        .setData(Uri.parse(String.format(PINTEREST_PROFILE, mEsid))));
            else
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            finish();
            break;
        case CHATTER:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        // need to get an instance
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                new HttpPost(String.format(CHATTER_URL_ACCESS, CHATTER_KEY, arg0[0])));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject jobj = new JSONObject(response);
                                if (jobj.has("instance_url")) {
                                    startActivity(new Intent(Intent.ACTION_VIEW)
                                            .setData(Uri.parse(jobj.getString("instance_url") + "/" + mEsid)));
                                }
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                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();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))));
            }
            account.close();
            break;
        }
        break;
    default:
        if ((itemsData != null) && (which < itemsData.length) && (itemsData[which] != null))
            // open link
            startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(itemsData[which])));
        else
            (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
        finish();
        break;
    }
}

From source file:com.inbeacon.cordova.CordovaInbeaconManager.java

private void attachUser(final JSONObject kwargs, final CallbackContext callbackContext) {
    // kwargs keys can be:
    // name, email, customerid, address, gender, zip, city, country,  birth, phone_mobile,
    // phone_home, phone_work, social_facebook_id, social_twitter_id, social_linkedin_id
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            HashMap<String, String> user = new HashMap<String, String>();
            for (Iterator<String> iter = kwargs.keys(); iter.hasNext();) {
                String key = iter.next();
                try {
                    user.put(key, kwargs.getString(key));
                } catch (JSONException e) {
                    callbackContext.error("Invalid user info: " + e.toString());
                }//ww  w  . j  av  a 2s  . com
            }

            InbeaconManager.getSharedInstance().attachUser(user);
            callbackContext.success();
        }
    });
}