Example usage for org.json JSONObject getInt

List of usage examples for org.json JSONObject getInt

Introduction

In this page you can find the example usage for org.json JSONObject getInt.

Prototype

public int getInt(String key) throws JSONException 

Source Link

Document

Get the int value associated with a key.

Usage

From source file:qurandwnld.SyncDbHelper.java

public static ServerResponse sendMySelectionsToServer(String username, String password) throws Exception {
    String urlParameters = String.format("username=%s&password=%s&xmlData=%s",
            URLEncoder.encode(username, "UTF-8"), URLEncoder.encode(password, "UTF-8"),
            URLEncoder.encode(getSendXml(), "UTF-8"));
    byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
    int postDataLength = postData.length;
    String request = "http://localhost:55622/Server/SubmitUserSelections";
    URL url = new URL(request);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);//w  w w  . j a v  a2  s  . c o m
    conn.setInstanceFollowRedirects(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("charset", "utf-8");
    conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
    conn.setUseCaches(false);
    try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
        wr.write(postData);
    }
    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    StringBuilder json = new StringBuilder();
    for (int c = in.read(); c != -1; c = in.read())
        json.append((char) c);
    JSONObject obj = new JSONObject(json.toString());
    ServerResponse res = new ServerResponse();
    res.code = obj.getInt("Code");
    res.message = obj.getString("Message");
    return res;
}

From source file:org.mozilla.gecko.gfx.RectUtils.java

public static Rect create(JSONObject json) {
    try {//from  ww w.  j  ava 2s.co m
        int x = json.getInt("x");
        int y = json.getInt("y");
        int width = json.getInt("width");
        int height = json.getInt("height");
        return new Rect(x, y, x + width, y + height);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.polychrom.cordova.ActionBarPlugin.java

private boolean buildMenu(Menu menu, JSONArray definition, String menu_var) {
    // Sadly MenuItem.setIcon and SubMenu.setIcon have conficting return types (for chaining), thus this can't be done w/ generics :(
    class GetMenuItemIconTask extends AsyncTask<String, Void, Drawable> {
        public final MenuItem item;
        public Exception exception = null;

        GetMenuItemIconTask(MenuItem item) {
            this.item = item;
        }//from   www . j  a va 2  s.co  m

        @Override
        protected Drawable doInBackground(String... uris) {
            return getDrawableForURI(uris[0]);
        }

        @Override
        protected void onPostExecute(Drawable icon) {
            if (icon != null) {
                item.setIcon(icon);
            }
        }
    }
    ;

    class GetSubMenuIconTask extends AsyncTask<String, Void, Drawable> {
        public final SubMenu item;
        public Exception exception = null;

        GetSubMenuIconTask(SubMenu item) {
            this.item = item;
        }

        @Override
        protected Drawable doInBackground(String... uris) {
            return getDrawableForURI(uris[0]);
        }

        @Override
        protected void onPostExecute(Drawable icon) {
            if (icon != null) {
                item.setIcon(icon);
            }
        }
    }
    ;

    try {
        for (int i = 0; i < definition.length(); ++i) {
            final JSONObject item_def = definition.getJSONObject(i);
            final String text = item_def.isNull("text") ? "" : item_def.getString("text");

            if (!item_def.has("items")) {
                MenuItem item = menu.add(0, i, i, text);
                item.setTitleCondensed(text);
                if (item_def.isNull("icon") == false) {
                    GetMenuItemIconTask task = new GetMenuItemIconTask(item);

                    synchronized (task) {
                        task.execute(item_def.getString("icon"));
                    }
                }

                // Default to MenuItem.SHOW_AS_ACTION_IF_ROOM, otherwise take user defined value.
                item.setShowAsAction(item_def.has("show") ? item_def.getInt("show")
                        : MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

                menu_callbacks.put(item,
                        "var item = " + menu_var + "[" + i + "]; if(item.click) item.click();");
            } else {
                SubMenu submenu = menu.addSubMenu(0, i, i, text);
                if (item_def.isNull("icon") == false) {
                    GetSubMenuIconTask task = new GetSubMenuIconTask(submenu);

                    synchronized (task) {
                        task.execute(item_def.getString("icon"));
                    }
                }

                // Set submenu header
                if (item_def.has("header")) {
                    JSONObject header = item_def.getJSONObject("header");

                    if (header.has("title")) {
                        submenu.setHeaderTitle(header.getString("title"));
                    }

                    if (header.has("icon")) {
                        submenu.setHeaderIcon(getDrawableForURI(header.getString("icon")));
                    }
                }

                // Build sub-menu
                buildMenu(submenu, item_def.getJSONArray("items"), menu_var + "[" + i + "].items");
            }
        }
    } catch (JSONException e) {
        return false;
    }

    return true;
}

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  w w  w  .ja  va  2 s.co 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:org.nuxeo.box.api.test.exception.BoxExceptionTest.java

@Test
public void itCanReturnJSONBoxException() throws Exception {
    // Get wrong folder id
    ClientResponse response = service.path("folders/blabla").get(ClientResponse.class);
    // Checking response consistency
    assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
    JSONObject finalResult = getJSONFromResponse(response);
    assertEquals(404, finalResult.getInt("status"));
    assertEquals("No such document: blabla", finalResult.getString("code"));

    // Get wrong endpoint
    response = service.path("folder").get(ClientResponse.class);
    // Checking response consistency
    assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
    finalResult = getJSONFromResponse(response);
    assertEquals(500, finalResult.getInt("status"));
    assertEquals("Type not found: repo", finalResult.getString("code"));

    // Posting with wrong property 'i' instead of 'id'
    response = service.path("folders").post(ClientResponse.class,
            "{\"name\":\"New Folder\", \"parent\": {\"i\": " + "\"blabla\"}}");
    // Checking response consistency
    assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
    finalResult = getJSONFromResponse(response);
    assertEquals(500, finalResult.getInt("status"));
    assertEquals("Failed to get document null", finalResult.getString("message"));
}

From source file:com.grarak.kerneladiutor.database.tools.profiles.ImportProfile.java

public ImportProfile(String path) {
    String json = Utils.readFile(path);
    if (json != null && !json.isEmpty()) {
        try {//from  w  ww .  j  av  a  2s  . c o  m
            JSONObject main = new JSONObject(json);
            mVersion = main.getInt("version");
            JSONObject profile = main.getJSONObject("profile");

            mCommands = profile.getJSONArray("commands");
            for (int i = 0; i < mCommands.length(); i++) {
                JSONObject command = mCommands.getJSONObject(i);
                if (!command.has("path") || !command.has("command")) {
                    mCommands = null;
                    break;
                }
            }
        } catch (JSONException ignored) {
        }
    }
}

From source file:asynctasks.LoadTaskTicketDataAsync.java

@Override
protected void onPostExecute(JSONObject json) {
    pDialog.cancel();/*from   w w  w  . j a v  a2  s. c  o  m*/
    ArrayList<HashMap<String, String>> cachedTempTickets = new ArrayList<HashMap<String, String>>();
    CachedData.getCachedTask().clear();
    int success, errorCode;
    try {
        success = json.getInt("success");
        if (success == 1) {
            JSONArray jsonList = json.getJSONArray("tickets");

            for (int i = 0; i < jsonList.length(); i++) {
                JSONObject o = jsonList.getJSONObject(i);

                HashMap<String, String> map = new HashMap<String, String>();
                map.put("t_id", o.getString("t_id"));
                map.put("t_name", o.getString("t_name"));
                map.put("t_serial", o.getString("t_serial"));
                map.put("t_datein", o.getString("t_datein"));
                map.put("t_dateout", o.getString("t_dateout"));
                map.put("t_license", o.getString("t_license"));
                map.put("t_vtype", o.getString("t_vtype"));
                map.put("t_vcolor", o.getString("t_vcolor"));
                map.put("t_vmodel", o.getString("t_vmodel"));
                map.put("t_parklocation", o.getString("t_parklocation"));
                map.put("t_keylocation", o.getString("t_keylocation"));
                map.put("t_staffemailentered", o.getString("t_staffemailentered"));
                map.put("t_useridpickup", o.getString("t_useridpickup"));
                map.put("t_active", o.getString("t_active"));
                map.put("tk_id", o.getString("tk_id"));

                cachedTempTickets.add(map);
            }

            CachedData.setCachedTask(cachedTempTickets);

            Task resultFrag = (Task) fm.findFragmentByTag("Task");

            if (resultFrag != null) {
                resultFrag.refreshData(CachedData.getCachedTask());
            }

        } else {
            Toast.makeText(context, "fuck, no work", Toast.LENGTH_SHORT).show();
        }

    } catch (JSONException e) {

        Task resultFrag = (Task) fm.findFragmentByTag("Task");
        if (resultFrag != null) {
            resultFrag.refreshData(CachedData.getCachedTask());
        }

        e.printStackTrace();
    }
}

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

private void loadComments() {
    mComments.clear();/*from   w ww  . j a  v  a 2  s  . co m*/
    setListAdapter(new SimpleAdapter(SonetComments.this, mComments, R.layout.comment,
            new String[] { Entities.FRIEND, Statuses.MESSAGE, Statuses.CREATEDTEXT, getString(R.string.like) },
            new int[] { R.id.friend, R.id.message, R.id.created, R.id.like }));
    mMessage.setEnabled(false);
    mMessage.setText(R.string.loading);
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() {
        @Override
        protected String doInBackground(Void... none) {
            // load the status itself
            if (mData != null) {
                SonetCrypto sonetCrypto = SonetCrypto.getInstance(getApplicationContext());
                UriMatcher um = new UriMatcher(UriMatcher.NO_MATCH);
                String authority = Sonet.getAuthority(SonetComments.this);
                um.addURI(authority, SonetProvider.VIEW_STATUSES_STYLES + "/*", SonetProvider.STATUSES_STYLES);
                um.addURI(authority, SonetProvider.TABLE_NOTIFICATIONS + "/*", SonetProvider.NOTIFICATIONS);
                Cursor status;
                switch (um.match(mData)) {
                case SonetProvider.STATUSES_STYLES:
                    status = getContentResolver().query(Statuses_styles.getContentUri(SonetComments.this),
                            new String[] { Statuses_styles.ACCOUNT, Statuses_styles.SID, Statuses_styles.ESID,
                                    Statuses_styles.WIDGET, Statuses_styles.SERVICE, Statuses_styles.FRIEND,
                                    Statuses_styles.MESSAGE, Statuses_styles.CREATED },
                            Statuses_styles._ID + "=?", new String[] { mData.getLastPathSegment() }, null);
                    if (status.moveToFirst()) {
                        mService = status.getInt(4);
                        mServiceName = getResources().getStringArray(R.array.service_entries)[mService];
                        mAccount = status.getLong(0);
                        mSid = sonetCrypto.Decrypt(status.getString(1));
                        mEsid = sonetCrypto.Decrypt(status.getString(2));
                        Cursor widget = getContentResolver().query(
                                Widgets_settings.getContentUri(SonetComments.this),
                                new String[] { Widgets.TIME24HR },
                                Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                new String[] { Integer.toString(status.getInt(3)), Long.toString(mAccount) },
                                null);
                        if (widget.moveToFirst()) {
                            mTime24hr = widget.getInt(0) == 1;
                        } else {
                            Cursor b = getContentResolver().query(
                                    Widgets_settings.getContentUri(SonetComments.this),
                                    new String[] { Widgets.TIME24HR },
                                    Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                    new String[] { Integer.toString(status.getInt(3)),
                                            Long.toString(Sonet.INVALID_ACCOUNT_ID) },
                                    null);
                            if (b.moveToFirst()) {
                                mTime24hr = b.getInt(0) == 1;
                            } else {
                                Cursor c = getContentResolver()
                                        .query(Widgets_settings.getContentUri(SonetComments.this),
                                                new String[] { Widgets.TIME24HR },
                                                Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                                new String[] {
                                                        Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID),
                                                        Long.toString(Sonet.INVALID_ACCOUNT_ID) },
                                                null);
                                if (c.moveToFirst()) {
                                    mTime24hr = c.getInt(0) == 1;
                                } else {
                                    mTime24hr = false;
                                }
                                c.close();
                            }
                            b.close();
                        }
                        widget.close();
                        HashMap<String, String> commentMap = new HashMap<String, String>();
                        commentMap.put(Statuses.SID, mSid);
                        commentMap.put(Entities.FRIEND, status.getString(5));
                        commentMap.put(Statuses.MESSAGE, status.getString(6));
                        commentMap.put(Statuses.CREATEDTEXT,
                                Sonet.getCreatedText(status.getLong(7), mTime24hr));
                        commentMap.put(getString(R.string.like),
                                mService == TWITTER ? getString(R.string.retweet)
                                        : mService == IDENTICA ? getString(R.string.repeat) : "");
                        mComments.add(commentMap);
                        // load the session
                        Cursor account = getContentResolver().query(Accounts.getContentUri(SonetComments.this),
                                new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SID },
                                Accounts._ID + "=?", new String[] { Long.toString(mAccount) }, null);
                        if (account.moveToFirst()) {
                            mToken = sonetCrypto.Decrypt(account.getString(0));
                            mSecret = sonetCrypto.Decrypt(account.getString(1));
                            mAccountSid = sonetCrypto.Decrypt(account.getString(2));
                        }
                        account.close();
                    }
                    status.close();
                    break;
                case SonetProvider.NOTIFICATIONS:
                    Cursor notification = getContentResolver().query(
                            Notifications.getContentUri(SonetComments.this),
                            new String[] { Notifications.ACCOUNT, Notifications.SID, Notifications.ESID,
                                    Notifications.FRIEND, Notifications.MESSAGE, Notifications.CREATED },
                            Notifications._ID + "=?", new String[] { mData.getLastPathSegment() }, null);
                    if (notification.moveToFirst()) {
                        // clear notification
                        ContentValues values = new ContentValues();
                        values.put(Notifications.CLEARED, 1);
                        getContentResolver().update(Notifications.getContentUri(SonetComments.this), values,
                                Notifications._ID + "=?", new String[] { mData.getLastPathSegment() });
                        mAccount = notification.getLong(0);
                        mSid = sonetCrypto.Decrypt(notification.getString(1));
                        mEsid = sonetCrypto.Decrypt(notification.getString(2));
                        mTime24hr = false;
                        // load the session
                        Cursor account = getContentResolver().query(Accounts.getContentUri(SonetComments.this),
                                new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SID,
                                        Accounts.SERVICE },
                                Accounts._ID + "=?", new String[] { Long.toString(mAccount) }, null);
                        if (account.moveToFirst()) {
                            mToken = sonetCrypto.Decrypt(account.getString(0));
                            mSecret = sonetCrypto.Decrypt(account.getString(1));
                            mAccountSid = sonetCrypto.Decrypt(account.getString(2));
                            mService = account.getInt(3);
                        }
                        account.close();
                        HashMap<String, String> commentMap = new HashMap<String, String>();
                        commentMap.put(Statuses.SID, mSid);
                        commentMap.put(Entities.FRIEND, notification.getString(3));
                        commentMap.put(Statuses.MESSAGE, notification.getString(4));
                        commentMap.put(Statuses.CREATEDTEXT,
                                Sonet.getCreatedText(notification.getLong(5), mTime24hr));
                        commentMap.put(getString(R.string.like),
                                mService == TWITTER ? getString(R.string.retweet) : getString(R.string.repeat));
                        mComments.add(commentMap);
                        mServiceName = getResources().getStringArray(R.array.service_entries)[mService];
                    }
                    notification.close();
                    break;
                default:
                    mComments.clear();
                    HashMap<String, String> commentMap = new HashMap<String, String>();
                    commentMap.put(Statuses.SID, "");
                    commentMap.put(Entities.FRIEND, "");
                    commentMap.put(Statuses.MESSAGE, "error, status not found");
                    commentMap.put(Statuses.CREATEDTEXT, "");
                    commentMap.put(getString(R.string.like), "");
                    mComments.add(commentMap);
                }
                String response = null;
                HttpGet httpGet;
                SonetOAuth sonetOAuth;
                boolean liked = false;
                String screen_name = "";
                switch (mService) {
                case TWITTER:
                    sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET, mToken,
                            mSecret);
                    if ((response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(
                            new HttpGet(String.format(TWITTER_USER, TWITTER_BASE_URL, mEsid))))) != null) {
                        try {
                            JSONObject user = new JSONObject(response);
                            screen_name = "@" + user.getString(Sscreen_name) + " ";
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                    publishProgress(screen_name);
                    response = SonetHttpClient.httpResponse(mHttpClient,
                            sonetOAuth.getSignedRequest(new HttpGet(String.format(TWITTER_MENTIONS,
                                    TWITTER_BASE_URL, String.format(TWITTER_SINCE_ID, mSid)))));
                    break;
                case FACEBOOK:
                    if ((response = SonetHttpClient.httpResponse(mHttpClient,
                            new HttpGet(String.format(FACEBOOK_LIKES, FACEBOOK_BASE_URL, mSid, Saccess_token,
                                    mToken)))) != null) {
                        try {
                            JSONArray likes = new JSONObject(response).getJSONArray(Sdata);
                            for (int i = 0, i2 = likes.length(); i < i2; i++) {
                                JSONObject like = likes.getJSONObject(i);
                                if (like.getString(Sid).equals(mAccountSid)) {
                                    liked = true;
                                    break;
                                }
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                    publishProgress(getString(liked ? R.string.unlike : R.string.like));
                    response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(
                            String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid, Saccess_token, mToken)));
                    break;
                case MYSPACE:
                    sonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY, BuildConfig.MYSPACE_SECRET, mToken,
                            mSecret);
                    response = SonetHttpClient.httpResponse(mHttpClient,
                            sonetOAuth.getSignedRequest(new HttpGet(String
                                    .format(MYSPACE_URL_STATUSMOODCOMMENTS, MYSPACE_BASE_URL, mEsid, mSid))));
                    break;
                case LINKEDIN:
                    sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY, BuildConfig.LINKEDIN_SECRET, mToken,
                            mSecret);
                    httpGet = new HttpGet(String.format(LINKEDIN_UPDATE, LINKEDIN_BASE_URL, mSid));
                    for (String[] header : LINKEDIN_HEADERS)
                        httpGet.setHeader(header[0], header[1]);
                    if ((response = SonetHttpClient.httpResponse(mHttpClient,
                            sonetOAuth.getSignedRequest(httpGet))) != null) {
                        try {
                            JSONObject data = new JSONObject(response);
                            if (data.has("isCommentable") && !data.getBoolean("isCommentable")) {
                                publishProgress(getString(R.string.uncommentable));
                            }
                            if (data.has("isLikable")) {
                                publishProgress(getString(
                                        data.has("isLiked") && data.getBoolean("isLiked") ? R.string.unlike
                                                : R.string.like));
                            } else {
                                publishProgress(getString(R.string.unlikable));
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                    } else {
                        publishProgress(getString(R.string.unlikable));
                    }
                    httpGet = new HttpGet(String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid));
                    for (String[] header : LINKEDIN_HEADERS)
                        httpGet.setHeader(header[0], header[1]);
                    response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpGet));
                    break;
                case FOURSQUARE:
                    response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(
                            String.format(FOURSQUARE_GET_CHECKIN, FOURSQUARE_BASE_URL, mSid, mToken)));
                    break;
                case IDENTICA:
                    sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY, BuildConfig.IDENTICA_SECRET, mToken,
                            mSecret);
                    if ((response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(
                            new HttpGet(String.format(IDENTICA_USER, IDENTICA_BASE_URL, mEsid))))) != null) {
                        try {
                            JSONObject user = new JSONObject(response);
                            screen_name = "@" + user.getString(Sscreen_name) + " ";
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                    publishProgress(screen_name);
                    response = SonetHttpClient.httpResponse(mHttpClient,
                            sonetOAuth.getSignedRequest(new HttpGet(String.format(IDENTICA_MENTIONS,
                                    IDENTICA_BASE_URL, String.format(IDENTICA_SINCE_ID, mSid)))));
                    break;
                case GOOGLEPLUS:
                    //TODO:
                    // get plussed status
                    break;
                case CHATTER:
                    // Chatter requires loading an instance
                    if ((mChatterInstance == null) || (mChatterToken == null)) {
                        if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpPost(
                                String.format(CHATTER_URL_ACCESS, BuildConfig.CHATTER_KEY, mToken)))) != null) {
                            try {
                                JSONObject jobj = new JSONObject(response);
                                if (jobj.has("instance_url") && jobj.has(Saccess_token)) {
                                    mChatterInstance = jobj.getString("instance_url");
                                    mChatterToken = jobj.getString(Saccess_token);
                                }
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                    }
                    if ((mChatterInstance != null) && (mChatterToken != null)) {
                        httpGet = new HttpGet(String.format(CHATTER_URL_LIKES, mChatterInstance, mSid));
                        httpGet.setHeader("Authorization", "OAuth " + mChatterToken);
                        if ((response = SonetHttpClient.httpResponse(mHttpClient, httpGet)) != null) {
                            try {
                                JSONObject jobj = new JSONObject(response);
                                if (jobj.getInt(Stotal) > 0) {
                                    JSONArray likes = jobj.getJSONArray("likes");
                                    for (int i = 0, i2 = likes.length(); i < i2; i++) {
                                        JSONObject like = likes.getJSONObject(i);
                                        if (like.getJSONObject(Suser).getString(Sid).equals(mAccountSid)) {
                                            mChatterLikeId = like.getString(Sid);
                                            liked = true;
                                            break;
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        publishProgress(getString(liked ? R.string.unlike : R.string.like));
                        httpGet = new HttpGet(String.format(CHATTER_URL_COMMENTS, mChatterInstance, mSid));
                        httpGet.setHeader("Authorization", "OAuth " + mChatterToken);
                        response = SonetHttpClient.httpResponse(mHttpClient, httpGet);
                    } else {
                        response = null;
                    }
                    break;
                }
                return response;
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... params) {
            mMessage.setText("");
            if (params != null) {
                if ((mService == TWITTER) || (mService == IDENTICA)) {
                    mMessage.append(params[0]);
                } else {
                    if (mService == LINKEDIN) {
                        if (params[0].equals(getString(R.string.uncommentable))) {
                            mSend.setEnabled(false);
                            mMessage.setEnabled(false);
                            mMessage.setText(R.string.uncommentable);
                        } else {
                            setCommentStatus(0, params[0]);
                        }
                    } else {
                        setCommentStatus(0, params[0]);
                    }
                }
            }
            mMessage.setEnabled(true);
        }

        @Override
        protected void onPostExecute(String response) {
            if (response != null) {
                int i2;
                try {
                    JSONArray comments;
                    mSimpleDateFormat = null;
                    switch (mService) {
                    case TWITTER:
                        comments = new JSONArray(response);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject comment = comments.getJSONObject(i);
                                if (comment.getString(Sin_reply_to_status_id) == mSid) {
                                    HashMap<String, String> commentMap = new HashMap<String, String>();
                                    commentMap.put(Statuses.SID, comment.getString(Sid));
                                    commentMap.put(Entities.FRIEND,
                                            comment.getJSONObject(Suser).getString(Sname));
                                    commentMap.put(Statuses.MESSAGE, comment.getString(Stext));
                                    commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(
                                            parseDate(comment.getString(Screated_at), TWITTER_DATE_FORMAT),
                                            mTime24hr));
                                    commentMap.put(getString(R.string.like), getString(R.string.retweet));
                                    mComments.add(commentMap);
                                }
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case FACEBOOK:
                        comments = new JSONObject(response).getJSONArray(Sdata);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject comment = comments.getJSONObject(i);
                                HashMap<String, String> commentMap = new HashMap<String, String>();
                                commentMap.put(Statuses.SID, comment.getString(Sid));
                                commentMap.put(Entities.FRIEND, comment.getJSONObject(Sfrom).getString(Sname));
                                commentMap.put(Statuses.MESSAGE, comment.getString(Smessage));
                                commentMap.put(Statuses.CREATEDTEXT,
                                        Sonet.getCreatedText(comment.getLong(Screated_time) * 1000, mTime24hr));
                                commentMap.put(getString(R.string.like),
                                        getString(comment.has(Suser_likes) && comment.getBoolean(Suser_likes)
                                                ? R.string.unlike
                                                : R.string.like));
                                mComments.add(commentMap);
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case MYSPACE:
                        comments = new JSONObject(response).getJSONArray(Sentry);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject entry = comments.getJSONObject(i);
                                HashMap<String, String> commentMap = new HashMap<String, String>();
                                commentMap.put(Statuses.SID, entry.getString(ScommentId));
                                commentMap.put(Entities.FRIEND,
                                        entry.getJSONObject(Sauthor).getString(SdisplayName));
                                commentMap.put(Statuses.MESSAGE, entry.getString(Sbody));
                                commentMap.put(Statuses.CREATEDTEXT,
                                        Sonet.getCreatedText(
                                                parseDate(entry.getString(SpostedDate), MYSPACE_DATE_FORMAT),
                                                mTime24hr));
                                commentMap.put(getString(R.string.like), "");
                                mComments.add(commentMap);
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case LINKEDIN:
                        JSONObject jsonResponse = new JSONObject(response);
                        if (jsonResponse.has(S_total) && (jsonResponse.getInt(S_total) != 0)) {
                            comments = jsonResponse.getJSONArray(Svalues);
                            if ((i2 = comments.length()) > 0) {
                                for (int i = 0; i < i2; i++) {
                                    JSONObject comment = comments.getJSONObject(i);
                                    JSONObject person = comment.getJSONObject(Sperson);
                                    HashMap<String, String> commentMap = new HashMap<String, String>();
                                    commentMap.put(Statuses.SID, comment.getString(Sid));
                                    commentMap.put(Entities.FRIEND,
                                            person.getString(SfirstName) + " " + person.getString(SlastName));
                                    commentMap.put(Statuses.MESSAGE, comment.getString(Scomment));
                                    commentMap.put(Statuses.CREATEDTEXT,
                                            Sonet.getCreatedText(comment.getLong(Stimestamp), mTime24hr));
                                    commentMap.put(getString(R.string.like), "");
                                    mComments.add(commentMap);
                                }
                            } else {
                                noComments();
                            }
                        }
                        break;
                    case FOURSQUARE:
                        comments = new JSONObject(response).getJSONObject(Sresponse).getJSONObject(Scheckin)
                                .getJSONObject(Scomments).getJSONArray(Sitems);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject comment = comments.getJSONObject(i);
                                JSONObject user = comment.getJSONObject(Suser);
                                HashMap<String, String> commentMap = new HashMap<String, String>();
                                commentMap.put(Statuses.SID, comment.getString(Sid));
                                commentMap.put(Entities.FRIEND,
                                        user.getString(SfirstName) + " " + user.getString(SlastName));
                                commentMap.put(Statuses.MESSAGE, comment.getString(Stext));
                                commentMap.put(Statuses.CREATEDTEXT,
                                        Sonet.getCreatedText(comment.getLong(ScreatedAt) * 1000, mTime24hr));
                                commentMap.put(getString(R.string.like), "");
                                mComments.add(commentMap);
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case IDENTICA:
                        comments = new JSONArray(response);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject comment = comments.getJSONObject(i);
                                if (comment.getString(Sin_reply_to_status_id) == mSid) {
                                    HashMap<String, String> commentMap = new HashMap<String, String>();
                                    commentMap.put(Statuses.SID, comment.getString(Sid));
                                    commentMap.put(Entities.FRIEND,
                                            comment.getJSONObject(Suser).getString(Sname));
                                    commentMap.put(Statuses.MESSAGE, comment.getString(Stext));
                                    commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(
                                            parseDate(comment.getString(Screated_at), TWITTER_DATE_FORMAT),
                                            mTime24hr));
                                    commentMap.put(getString(R.string.like), getString(R.string.repeat));
                                    mComments.add(commentMap);
                                }
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case GOOGLEPLUS:
                        //TODO: load comments
                        HttpPost httpPost = new HttpPost(GOOGLE_ACCESS);
                        List<NameValuePair> httpParams = new ArrayList<NameValuePair>();
                        httpParams.add(new BasicNameValuePair("client_id", BuildConfig.GOOGLECLIENT_ID));
                        httpParams
                                .add(new BasicNameValuePair("client_secret", BuildConfig.GOOGLECLIENT_SECRET));
                        httpParams.add(new BasicNameValuePair("refresh_token", mToken));
                        httpParams.add(new BasicNameValuePair("grant_type", "refresh_token"));
                        try {
                            httpPost.setEntity(new UrlEncodedFormEntity(httpParams));
                            if ((response = SonetHttpClient.httpResponse(mHttpClient, httpPost)) != null) {
                                JSONObject j = new JSONObject(response);
                                if (j.has(Saccess_token)) {
                                    String access_token = j.getString(Saccess_token);
                                    if ((response = SonetHttpClient.httpResponse(mHttpClient,
                                            new HttpGet(String.format(GOOGLEPLUS_ACTIVITY, GOOGLEPLUS_BASE_URL,
                                                    mSid, access_token)))) != null) {
                                        // check for a newer post, if it's the user's own, then set CLEARED=0
                                        try {
                                            JSONObject item = new JSONObject(response);
                                            if (item.has(Sobject)) {
                                                JSONObject object = item.getJSONObject(Sobject);
                                                if (object.has(Sreplies)) {
                                                    int commentCount = 0;
                                                    JSONObject replies = object.getJSONObject(Sreplies);
                                                    if (replies.has(StotalItems)) {
                                                        //TODO: load comments
                                                        commentCount = replies.getInt(StotalItems);
                                                    }
                                                }
                                            }
                                        } catch (JSONException e) {
                                            Log.e(TAG, e.toString());
                                        }
                                    }
                                }
                            }
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case CHATTER:
                        JSONObject chats = new JSONObject(response);
                        if (chats.getInt(Stotal) > 0) {
                            comments = chats.getJSONArray(Scomments);
                            if ((i2 = comments.length()) > 0) {
                                for (int i = 0; i < i2; i++) {
                                    JSONObject comment = comments.getJSONObject(i);
                                    HashMap<String, String> commentMap = new HashMap<String, String>();
                                    commentMap.put(Statuses.SID, comment.getString(Sid));
                                    commentMap.put(Entities.FRIEND,
                                            comment.getJSONObject(Suser).getString(Sname));
                                    commentMap.put(Statuses.MESSAGE,
                                            comment.getJSONObject(Sbody).getString(Stext));
                                    commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(
                                            parseDate(comment.getString(ScreatedDate), CHATTER_DATE_FORMAT),
                                            mTime24hr));
                                    commentMap.put(getString(R.string.like), "");
                                    mComments.add(commentMap);
                                }
                            } else {
                                noComments();
                            }
                        } else {
                            noComments();
                        }
                        break;
                    }
                } catch (JSONException e) {
                    Log.e(TAG, e.toString());
                }
            } else {
                noComments();
            }
            setListAdapter(new SimpleAdapter(SonetComments.this, mComments, R.layout.comment,
                    new String[] { Entities.FRIEND, Statuses.MESSAGE, Statuses.CREATEDTEXT,
                            getString(R.string.like) },
                    new int[] { R.id.friend, R.id.message, R.id.created, R.id.like }));
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
        }

        private void noComments() {
            HashMap<String, String> commentMap = new HashMap<String, String>();
            commentMap.put(Statuses.SID, "");
            commentMap.put(Entities.FRIEND, "");
            commentMap.put(Statuses.MESSAGE, getString(R.string.no_comments));
            commentMap.put(Statuses.CREATEDTEXT, "");
            commentMap.put(getString(R.string.like), "");
            mComments.add(commentMap);
        }

        private long parseDate(String date, String format) {
            if (date != null) {
                // hack for the literal 'Z'
                if (date.substring(date.length() - 1).equals("Z")) {
                    date = date.substring(0, date.length() - 2) + "+0000";
                }
                Date created = null;
                if (format != null) {
                    if (mSimpleDateFormat == null) {
                        mSimpleDateFormat = new SimpleDateFormat(format, Locale.ENGLISH);
                        // all dates should be GMT/UTC
                        mSimpleDateFormat.setTimeZone(sTimeZone);
                    }
                    try {
                        created = mSimpleDateFormat.parse(date);
                        return created.getTime();
                    } catch (ParseException e) {
                        Log.e(TAG, e.toString());
                    }
                } else {
                    // attempt to parse RSS date
                    if (mSimpleDateFormat != null) {
                        try {
                            created = mSimpleDateFormat.parse(date);
                            return created.getTime();
                        } catch (ParseException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                    for (String rfc822 : sRFC822) {
                        mSimpleDateFormat = new SimpleDateFormat(rfc822, Locale.ENGLISH);
                        mSimpleDateFormat.setTimeZone(sTimeZone);
                        try {
                            if ((created = mSimpleDateFormat.parse(date)) != null) {
                                return created.getTime();
                            }
                        } catch (ParseException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                }
            }
            return System.currentTimeMillis();
        }
    };
    loadingDialog.setMessage(getString(R.string.loading));
    loadingDialog.setCancelable(true);
    loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            if (!asyncTask.isCancelled())
                asyncTask.cancel(true);
        }
    });
    loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    loadingDialog.show();
    asyncTask.execute();
}

From source file:com.jvoid.products.controller.JVoidProductController.java

@RequestMapping(value = "productattributevalue/delete", method = RequestMethod.GET)
public @ResponseBody String deleteProductAttributeValue(
        @RequestParam(required = false, value = "callback") String callback,
        @RequestParam(required = false, value = "params") JSONObject jsonParams, HttpServletResponse response) {

    JSONObject jparams = jsonParams;
    int productAttributeValueId = 0;
    try {//w w  w.  j ava 2s .c  o m
        productAttributeValueId = jparams.getInt("id");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JSONObject jsonObject = new JSONObject();
    if (productAttributeValueId > 0) {
        int status = this.productsMasterService.deleteProductAttributeValue(productAttributeValueId);
        if (status == 1) {
            try {
                jsonObject.put("status", 1);
                jsonObject.put("message", "ProductAttributeValue deleted successfully.");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            try {
                jsonObject.put("status", 0);
                jsonObject.put("message", "Failed to delete ProductAttributeValue.");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } else {
        try {
            jsonObject.put("status", 0);
            jsonObject.put("message", "Failed to delete ProductAttributeValue.");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return jsonObject.toString();
}

From source file:com.jvoid.products.controller.JVoidProductController.java

@RequestMapping(value = "attributevalue/delete", method = RequestMethod.GET)
public @ResponseBody String deleteAttributeValue(
        @RequestParam(required = false, value = "callback") String callback,
        @RequestParam(required = false, value = "params") JSONObject jsonParams, HttpServletResponse response) {

    JSONObject jparams = jsonParams;
    int attributeValueId = 0;
    try {/*from   ww  w.java2s  .  c om*/
        attributeValueId = jparams.getInt("id");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JSONObject jsonObject = new JSONObject();
    if (attributeValueId > 0) {
        this.productsMasterService.deleteAttributeValue(attributeValueId);
        try {
            jsonObject.put("status", 1);
            jsonObject.put("message", "AttributeValue deleted successfully.");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        try {
            jsonObject.put("status", 0);
            jsonObject.put("message", "Failed to delete AttributeValue.");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return jsonObject.toString();
}