Example usage for org.json JSONObject optBoolean

List of usage examples for org.json JSONObject optBoolean

Introduction

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

Prototype

public boolean optBoolean(String key) 

Source Link

Document

Get an optional boolean associated with a key.

Usage

From source file:fi.harism.lucidchat.api.ChatConnection.java

/**
 * Handle server event messages.//from   w  ww . j  ava2  s  . c o  m
 */
private void handleEvent(String message) {
    try {
        // We receive always JSON messages.
        JSONObject json = new JSONObject(message);
        // Get event type from JSON.
        String event = json.optString("event");

        // Handle session_created event.
        if (event.equals("session_created")) {

            // Here we expect that server sends user_auth only when new
            // session is created. In case where old session was continues
            // user_auth ought not to be present.
            if (!json.has("user_auth")) {
                // Notify server about connection.
                mObserver.onServerMessage(new Message(Message.TYPE_LOG,
                        "Session resumed userId=" + mUserId + " sessionId=" + mSessionId));
                mObserver.onConnect(mUserId, mUserAuth, mSessionId);
            } else {
                // New session was created.
                mUserId = json.getString("user_id");
                mUserAuth = json.getString("user_auth");
                mSessionId = json.getString("session_id");
                mObserver.onServerMessage(new Message(Message.TYPE_LOG,
                        "Session created userId=" + mUserId + " sessionId=" + mSessionId));
                mObserver.onConnect(mUserId, mUserAuth, mSessionId);
                // If autojoin is enabled send join message.
                if (mAutojoin) {
                    sendJoinChannel(NINCHAT_LOUNGE);
                }
            }
        }

        // Handle user_updated and user_found events.
        if (event.equals("user_updated") || event.equals("user_found")) {
            String userId = json.getString("user_id");
            // If update was sent for ourself.
            if (userId.equals(mUserId)) {
                // We do nothing on updates sent to self at the moment.
            } else {
                // Notify observer about user updated event.
                JSONObject userAttrs = json.getJSONObject("user_attrs");
                String name = userAttrs.optString("name");
                String realName = userAttrs.optString("realname");
                boolean connected = userAttrs.optBoolean("connected");
                mObserver.onUserUpdated(new User(userId, name, realName, connected));
            }
        }

        // Handle channel_updated event.
        if (event.equals("channel_updated")) {
            String channelId = json.getString("channel_id");
            JSONObject channelAttrs = json.getJSONObject("channel_attrs");
            String name = channelAttrs.optString("name");
            String topic = channelAttrs.optString("topic");
            mObserver.onChannelUpdated(new Channel(channelId, name, topic));
        }

        // Handle search_results event.
        if (event.equals("search_results")) {
            mObserver.onServerMessage(new Message(Message.TYPE_LOG, "Search results event"));
            Vector<Channel> channelList = new Vector<Channel>();
            // Parse channels from search results.
            JSONObject channels = json.optJSONObject("channels");
            if (channels != null) {
                JSONArray names = channels.names();
                for (int i = 0; i < names.length(); ++i) {
                    String channelId = names.getString(i);
                    JSONObject channelAttrs = channels.getJSONObject(channelId).getJSONObject("channel_attrs");
                    String name = channelAttrs.optString("name");
                    String topic = channelAttrs.optString("topic");
                    channelList.add(new Channel(channelId, name, topic));
                }
            }
            // Parse users from search results.
            Vector<User> userList = new Vector<User>();
            JSONObject users = json.optJSONObject("users");
            if (users != null) {
                JSONArray names = users.names();
                for (int i = 0; i < names.length(); ++i) {
                    String userId = names.getString(i);
                    if (!userId.equals(mUserId)) {
                        JSONObject user = users.getJSONObject(userId);
                        String name = user.optString("name");
                        String realName = user.optString("realname");
                        boolean connected = user.optBoolean("connected");
                        userList.add(new User(userId, name, realName, connected));
                    }
                }
            }
            mObserver.onSearchResults(channelList, userList);
        }

        // Handle channel_joined event.
        if (event.equals("channel_joined")) {
            mObserver.onServerMessage(new Message(Message.TYPE_LOG, "Channel joined event"));

            String channelId = json.getString("channel_id");
            Vector<User> userList = new Vector<User>();
            JSONObject channelMembers = json.getJSONObject("channel_members");
            JSONArray names = channelMembers.names();
            for (int i = 0; i < names.length(); ++i) {
                String userId = names.getString(i);
                JSONObject userAttrs = channelMembers.getJSONObject(userId).getJSONObject("user_attrs");
                if (!userId.equals(mUserId)) {
                    String name = userAttrs.optString("name");
                    String realName = userAttrs.optString("realname");
                    boolean connected = userAttrs.optBoolean("connected");
                    userList.add(new User(userId, name, realName, connected));
                }
            }

            JSONObject channelAttrs = json.getJSONObject("channel_attrs");
            String name = channelAttrs.getString("name");
            String topic = channelAttrs.getString("topic");

            mObserver.onChannelJoined(new Channel(channelId, name, topic), userList);
        }

        // Message receiving happens with 2 callbacks. First
        // message_received is sent from server and then an empty JSON with
        // message only.
        if (event.equals("message_received")) {
            // Check message_type. We handle only text messages.
            if (json.optString("message_type").equals("ninchat.com/text")) {
                mMessage = json;
            }
            if (json.optString("message_type").equals("ninchat.com/info")) {
                mMessage = json;
            }
        }
        // Second part of text message receiving.
        if (mMessage != null && mMessage.optString("message_type").equals("ninchat.com/text")
                && json.has("text")) {
            // Message time is in seconds after epoch.
            long messageTime = mMessage.getLong("message_time") * 1000;
            String messageUserName = mMessage.getString("message_user_name");
            String channelId = mMessage.optString("channel_id");
            String userId = mMessage.optString("user_id");
            String text = json.getString("text");
            mMessage = null;

            // If channel_id exists notify observer about channel message.
            if (channelId.length() > 0) {
                mObserver.onChannelMessage(channelId,
                        new Message(Message.TYPE_CONVERSATION, messageTime, messageUserName, text));
            }
            // If user_id exists notify observer about private message.
            if (userId.length() > 0) {
                User user = new User(userId, messageUserName, "", true);
                mObserver.onUserMessage(user,
                        new Message(Message.TYPE_CONVERSATION, messageTime, messageUserName, text));
            }
        }
        if (mMessage != null && mMessage.optString("message_type").equals("ninchat.com/info")
                && json.has("info")) {
            String info = json.getString("info");
            if (info.equals("join")) {
                String channelId = mMessage.getString("channel_id");
                String userId = json.getString("user_id");
                String userName = json.getString("user_name");
                mObserver.onInfoJoin(channelId, userId, userName);
            }
            if (info.equals("part")) {
                String channelId = mMessage.getString("channel_id");
                String userId = json.getString("user_id");
                String userName = json.getString("user_name");
                mObserver.onInfoPart(channelId, userId, userName);
            }

            mMessage = null;
        }

        // Handle channel_parted event.
        if (event.equals("channel_parted")) {
            String channelId = json.getString("channel_id");
            mObserver.onChannelParted(channelId);
        }

        // Handle channel_member_joined.
        if (event.equals("channel_member_joined")) {
            String channelId = json.getString("channel_id");
            String userId = json.getString("user_id");
            JSONObject userAttrs = json.getJSONObject("user_attrs");
            String name = userAttrs.getString("name");
            String realname = userAttrs.optString("realname");
            boolean connected = userAttrs.optBoolean("connected");
            mObserver.onUserJoin(channelId, new User(userId, name, realname, connected));
        }

        // Handle channel_member_parted.
        if (event.equals("channel_member_parted")) {
            String channelId = json.getString("channel_id");
            String userId = json.getString("user_id");
            mObserver.onUserPart(channelId, userId);
        }

        // Handle second phase of delete_user.
        if (event.equals("user_deleted")) {
            mWSC.disconnect();
        }

    } catch (JSONException ex) {
        ex.printStackTrace();
    }
}

From source file:com.chaosinmotion.securechat.network.SCNetwork.java

private synchronized void sendRequest(final Request request) {
    callQueue.add(request);//ww w .  j a  v  a2  s . c o  m

    // If not in background, spin the spinner
    if (request.caller instanceof WaitSpinner) {
        ((WaitSpinner) request.caller).startWaitSpinner();
        request.waitFlag = true;
    }

    request.taskFuture = ThreadPool.get().enqueueAsync(new Runnable() {
        @Override
        public void run() {
            try {
                HttpURLConnection conn = requestWith(request);

                conn.connect();
                Map<String, List<String>> headers = conn.getHeaderFields();
                List<String> clist = headers.get("Set-Cookie");
                if (clist != null) {
                    for (String cookie : clist) {
                        cookies.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
                    }
                }

                InputStream is = conn.getInputStream();
                JSONObject d = parseResult(is);
                conn.disconnect();

                final Response response = new Response();
                response.serverCode = conn.getResponseCode();
                if (d != null) {
                    response.success = d.optBoolean("success");
                    response.error = d.optInt("error");
                    response.errorMessage = d.optString("message");
                    response.exceptionStack = d.optJSONArray("exception");
                    response.data = d.optJSONObject("data");
                }

                ThreadPool.get().enqueueMain(new Runnable() {
                    @Override
                    public void run() {
                        if (request.waitFlag && ((request.caller instanceof WaitSpinner))) {
                            ((WaitSpinner) request.caller).stopWaitSpinner();
                            request.waitFlag = false;
                        }
                        callQueue.remove(request);
                        handleResponse(response, request);
                    }
                });
            } catch (Exception ex) {
                /*
                 *  This happens if there is a connection error.
                 */
                ThreadPool.get().enqueueMain(new Runnable() {
                    @Override
                    public void run() {
                        if (request.waitFlag && ((request.caller instanceof WaitSpinner))) {
                            ((WaitSpinner) request.caller).stopWaitSpinner();
                            request.waitFlag = false;
                        }
                        callQueue.remove(request);
                        handleIOError(request);
                    }
                });
            }
        }
    });
}

From source file:com.samsung.richnotification.RichNotificationHelper.java

private static SrnRemoteInputAction getRemoteInputAction(Context mContext, JSONObject action)
        throws JSONException {
    SrnRemoteInputAction inputAction = null;
    String actionLabel = action.optString("actionLabel");
    if (actionLabel == null || actionLabel.isEmpty())
        return null;

    inputAction = new SrnRemoteInputAction(actionLabel);

    int inputType = action.optInt("type");
    switch (inputType) {
    case ACTION_TYPE_INPUT_KEYBOARD:
        KeyboardInputMode kbInput = InputModeFactory.createKeyboardInputMode();
        String prefillString = action.optString("body");
        int charLimit = action.optInt("charLimit", 0);
        if (charLimit > 0 && charLimit <= prefillString.length()) {
            kbInput.setCharacterLimit(charLimit);
            kbInput.setPrefillString(prefillString.substring(0, charLimit));
        } else if (charLimit > 0 && charLimit > prefillString.length()) {
            kbInput.setCharacterLimit(charLimit);
            kbInput.setPrefillString(prefillString);
        } else {// w  ww .j  ava 2s .  com
            kbInput.setPrefillString(prefillString);
        }
        int keyboardType = action.optInt("keyboardType", KEYBOARD_NORMAL);
        kbInput.setKeyboardType(getKeyboardType(keyboardType));
        inputAction.setRequestedInputMode(kbInput);
        break;
    case ACTION_TYPE_INPUT_SINGLE_SELECT:
    case ACTION_TYPE_INPUT_MULTI_SELECT:
        SingleSelectInputMode single = InputModeFactory.createSingleSelectInputMode();
        MultiSelectInputMode multi = InputModeFactory.createMultiSelectInputMode();
        JSONArray choices = action.optJSONArray("choices");
        Log.d(TAG, "Choices: " + choices);
        if (choices == null || choices.length() == 0)
            return null;

        for (int index = 0; index < choices.length(); index++) {
            JSONObject choice = choices.optJSONObject(index);
            Log.d(TAG, "Choice: " + choice);
            if (choice == null)
                continue;

            String choiceLabel = choice.optString("choiceLabel", null);
            String choiceID = choice.optString("choiceID", null);
            if (choiceLabel == null || choiceID == null)
                continue;

            Bitmap chIco = getIconBitmap(mContext, "file://" + choice.optString("choiceIcon"));
            Log.d(TAG, "chIco for '" + choiceLabel + "'' : " + chIco);
            SrnImageAsset choiceImg = new SrnImageAsset(mContext, choiceLabel, chIco);

            boolean selected = choice.optBoolean("selected");
            if (inputType == ACTION_TYPE_INPUT_SINGLE_SELECT) {
                single.addChoice(choiceLabel, choiceID, choiceImg);
                inputAction.setRequestedInputMode(single);
            } else {
                multi.addChoice(choiceLabel, choiceID, choiceImg, selected);
                inputAction.setRequestedInputMode(multi);
            }
        }

        break;
    default:
        Log.d(TAG, "Invalid input type. Hence, ignoring.");
        return null;
    }
    return inputAction;
}

From source file:me.tassoevan.cordova.ForegroundService.java

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private Notification makeNotification() {
    JSONObject settings = BackgroundPlugin.settings;
    Context context = getApplicationContext();
    String pkgName = context.getPackageName();
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(pkgName);

    Notification.Builder notification = new Notification.Builder(context)
            .setContentTitle(settings.optString("title", "")).setContentText(settings.optString("text", ""))
            .setTicker(settings.optString("ticker", "")).setOngoing(true).setSmallIcon(getIconResId());

    if (intent != null && settings.optBoolean("resume")) {
        PendingIntent contentIntent = PendingIntent.getActivity(context, NOTIFICATION_ID, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        notification.setContentIntent(contentIntent);
    }//from www .ja va2 s . c om

    if (Build.VERSION.SDK_INT < 16) {
        return notification.getNotification();
    } else {
        return notification.build();
    }
}

From source file:com.basetechnology.s0.agentserver.field.BooleanField.java

public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) {
    String type = fieldJson.optString("type");
    if (type == null || !(type.equals("option") || type.equals("boolean")))
        return null;
    String name = fieldJson.has("name") ? fieldJson.optString("name") : null;
    String label = fieldJson.has("label") ? fieldJson.optString("label") : null;
    String description = fieldJson.has("description") ? fieldJson.optString("description") : null;
    boolean defaultValue = fieldJson.has("default_value") ? fieldJson.optBoolean("default_value") : true;
    String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null;
    return new BooleanField(symbolTable, name, label, description, defaultValue, compute);
}

From source file:com.melniqw.instagramsdk.Media.java

public static Media fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    Media media = new Media();
    media.id = o.optString("id");
    media.type = o.optString("type");
    media.createdTime = o.optString("created_time");
    media.attribution = o.optString("attribution");
    media.image = Image.fromJSON(o.optJSONObject("images"));
    if (media.type.equals("video"))
        media.video = Video.fromJSON(o.optJSONObject("videos"));
    media.link = o.optString("link");
    media.filter = o.optString("filter");
    media.userHasLiked = o.optBoolean("user_has_liked");
    media.user = User.fromJSON(o.optJSONObject("user"));
    JSONArray tagsJSONArray = o.optJSONArray("tags");
    ArrayList<String> tags = new ArrayList<>();
    for (int j = 0; j < tagsJSONArray.length(); j++) {
        tags.add(tagsJSONArray.optString(j));
    }// ww  w . j a  v a2 s.c o m
    media.tags.addAll(tags);
    JSONArray likesJSONArray = o.optJSONObject("likes").optJSONArray("data");
    ArrayList<Like> likes = new ArrayList<>();
    for (int j = 0; j < likesJSONArray.length(); j++) {
        JSONObject likeJSON = (JSONObject) likesJSONArray.get(j);
        likes.add(Like.fromJSON(likeJSON));
    }
    media.likes.addAll(likes);
    JSONArray commentJSONArray = o.optJSONObject("comments").optJSONArray("data");
    ArrayList<Comment> comments = new ArrayList<>();
    for (int j = 0; j < commentJSONArray.length(); j++) {
        JSONObject commentJSON = (JSONObject) commentJSONArray.get(j);
        comments.add(Comment.fromJSON(commentJSON));
    }
    media.comments.addAll(comments);
    JSONArray usersInPhotoJSON = o.optJSONArray("users_in_photo");
    ArrayList<UserInPhoto> usersInPhotos = new ArrayList<>();
    for (int j = 0; j < usersInPhotoJSON.length(); j++) {
        JSONObject userInPhotoJSON = (JSONObject) usersInPhotoJSON.get(j);
        usersInPhotos.add(UserInPhoto.fromJSON(userInPhotoJSON));
    }
    media.usersInPhoto.addAll(usersInPhotos);
    JSONObject locationJSON = o.optJSONObject("location");
    if (locationJSON != null) {
        media.location = Location.fromJSON(locationJSON);
    }
    JSONObject captionJSON = o.optJSONObject("caption");
    if (captionJSON != null) {
        media.caption = Comment.fromJSON(captionJSON);
    }
    return media;
}

From source file:org.catnut.support.TransientUser.java

public static TransientUser convert(JSONObject jsonObject) {
    TransientUser user = new TransientUser();
    user.id = jsonObject.optLong(Constants.ID);
    user.screenName = jsonObject.optString(User.screen_name);
    user.location = jsonObject.optString(User.location);
    user.description = jsonObject.optString(User.description);
    user.verified = jsonObject.optBoolean(User.verified);
    user.avatarUrl = jsonObject.optString(User.profile_image_url);
    return user;//  w ww.j a  va  2s.com
}

From source file:com.trellmor.berrytube.ChatMessage.java

/**
 * Constructs a <code>ChatMessage</code> from an <code>JSONObject</code>
 * //  w  ww.j a v a  2 s . co  m
 * @param message
 *            <code>JSONObject<code> containing all the required fields to form a chat message
 * @throws JSONException
 */
public ChatMessage(JSONObject message) throws JSONException {
    mNick = message.getString("nick");
    mMsg = message.getString("msg");
    mMulti = message.getInt("multi");
    mType = message.getInt("type");

    // check emote
    if (message.has("emote") && message.get("emote") instanceof String) {
        String emote = message.getString("emote");
        if (emote.compareTo("rcv") == 0)
            this.mEmote = EMOTE_RCV;
        else if (emote.compareTo("sweetiebot") == 0)
            this.mEmote = EMOTE_SWEETIEBOT;
        else if (emote.compareTo("spoiler") == 0)
            this.mEmote = EMOTE_SPOILER;
        else if (emote.compareTo("act") == 0)
            this.mEmote = EMOTE_ACT;
        else if (emote.compareTo("request") == 0)
            this.mEmote = EMOTE_REQUEST;
        else if (emote.compareTo("poll") == 0)
            this.mEmote = EMOTE_POLL;
        else if (emote.compareTo("drink") == 0)
            this.mEmote = EMOTE_DRINK;
    } else
        mEmote = 0;

    JSONObject metadata = message.getJSONObject("metadata");
    mFlair = metadata.optInt("flair");
    mFlaunt = metadata.optBoolean("nameflaunt");

    try {
        this.mTimeStamp = TIMESTAMP_FORMAT.parse(message.getString("timestamp")).getTime();
    } catch (ParseException pe) {
        Log.w(TAG, "Error parsing timestamp string");
        this.mTimeStamp = System.currentTimeMillis();
    }
    this.mHidden = (this.mEmote == EMOTE_SPOILER);
}

From source file:com.ibm.mobilefirst.mobileedge.interpretation.Classification.java

private void executeClassification() {

    if (accelerometerData.size() >= DATA_SIZE && gyroscopeData.size() >= DATA_SIZE) {

        JSONArray accelerometerArray = getNextDataAsJSONArray(accelerometerData);
        JSONArray gyroscopeArray = getNextDataAsJSONArray(gyroscopeData);

        JSONObject params = new JSONObject();

        try {//from w  w  w . j a va2  s.c o  m
            params.put("accelerometer", accelerometerArray);
            params.put("gyroscope", gyroscopeArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JSONObject result = JSEngine.getInstance().executeFunction("detectGesture", params);

        if (result.has("detected") && result.optBoolean("detected")) {
            //notify the detected gesture
            notifyResult(result.optJSONObject("additionalInfo"));
        }
    }
}

From source file:org.mariotaku.twidere.extension.mediauploader.util.ParseUtils.java

public static Bundle jsonToBundle(final String string) {
    final Bundle bundle = new Bundle();
    if (string != null) {
        try {// w  w  w.  j a va  2s. c  o  m
            final JSONObject json = new JSONObject(string);
            final Iterator<?> it = json.keys();
            while (it.hasNext()) {
                final Object key_obj = it.next();
                if (key_obj == null) {
                    continue;
                }
                final String key = key_obj.toString();
                final Object value = json.get(key);
                if (value instanceof Boolean) {
                    bundle.putBoolean(key, json.optBoolean(key));
                } else if (value instanceof Integer) {
                    // Simple workaround for account_id
                    if (shouldPutLong(key)) {
                        bundle.putLong(key, json.optLong(key));
                    } else {
                        bundle.putInt(key, json.optInt(key));
                    }
                } else if (value instanceof Long) {
                    bundle.putLong(key, json.optLong(key));
                } else if (value instanceof String) {
                    bundle.putString(key, json.optString(key));
                } else {
                    Log.w(LOGTAG,
                            "Unknown type " + value.getClass().getSimpleName() + " in arguments key " + key);
                }
            }
        } catch (final JSONException e) {
            e.printStackTrace();
        } catch (final ClassCastException e) {
            e.printStackTrace();
        }
    }
    return bundle;
}