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:com.remobile.file.LocalFilesystem.java

@Override
public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, String path, JSONObject options,
        boolean directory)
        throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
    boolean create = false;
    boolean exclusive = false;

    if (options != null) {
        create = options.optBoolean("create");
        if (create) {
            exclusive = options.optBoolean("exclusive");
        }//w w  w .  j a  va  2  s.  c om
    }

    // Check for a ":" character in the file to line up with BB and iOS
    if (path.contains(":")) {
        throw new EncodingException("This path has an invalid \":\" in it.");
    }

    LocalFilesystemURL requestedURL;

    // Check whether the supplied path is absolute or relative
    if (directory && !path.endsWith("/")) {
        path += "/";
    }
    if (path.startsWith("/")) {
        requestedURL = localUrlforFullPath(normalizePath(path));
    } else {
        requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
    }

    File fp = new File(this.filesystemPathForURL(requestedURL));

    if (create) {
        if (exclusive && fp.exists()) {
            throw new FileExistsException("create/exclusive fails");
        }
        if (directory) {
            fp.mkdir();
        } else {
            fp.createNewFile();
        }
        if (!fp.exists()) {
            throw new FileExistsException("create fails");
        }
    } else {
        if (!fp.exists()) {
            throw new FileNotFoundException("path does not exist");
        }
        if (directory) {
            if (fp.isFile()) {
                throw new TypeMismatchException("path doesn't exist or is file");
            }
        } else {
            if (fp.isDirectory()) {
                throw new TypeMismatchException("path doesn't exist or is directory");
            }
        }
    }

    // Return the directory
    return makeEntryForURL(requestedURL);
}

From source file:org.eclipse.orion.server.core.tasks.TaskInfo.java

/**
 * Returns a task object based on its JSON representation. Returns
 * null if the given string is not a valid JSON task representation.
 * This function does not set <code>canBeCanceled</code>. The caller
 * must find out himself if the task can be canceled and set this flag.
 * @throws CorruptedTaskException /*w  w  w  .ja  v a  2  s  .co  m*/
 */
public static TaskInfo fromJSON(TaskDescription description, String taskString) throws CorruptedTaskException {
    TaskInfo info;
    try {
        JSONObject json = new JSONObject(taskString);
        info = new TaskInfo(description.getUserId(), description.getTaskId(), description.isKeep());
        if (json.has(KEY_EXPIRES))
            info.expires = new Date(json.getLong(KEY_EXPIRES));

        if (json.has(KEY_TIMESTAMP))
            info.timestamp = new Date(json.getLong(KEY_TIMESTAMP));

        info.lengthComputable = json.optBoolean(KEY_LENGTH_COMPUTABLE);
        if (json.has(KEY_LOADED))
            info.loaded = json.optInt(KEY_LOADED);
        if (json.has(KEY_TOTAL))
            info.total = json.getInt(KEY_TOTAL);

        if (json.has(KEY_TYPE))
            info.status = TaskStatus.fromString(json.optString(KEY_TYPE));

        if (json.has(KEY_RESULT))
            info.result = ServerStatus.fromJSON(json.optString(KEY_RESULT));
        if (json.has(KEY_LOCATION_ONLY)) {
            info.locationOnly = json.optBoolean(KEY_LOCATION_ONLY);
        }

        return info;
    } catch (JSONException e) {
        throw new CorruptedTaskException(taskString, e);
    }
}

From source file:com.futureplatforms.kirin.extensions.localnotifications.LocalNotificationsBackend.java

@SuppressWarnings("deprecation")
public Notification createNotification(Bundle settings, JSONObject obj) {

    // notifications[i] = api.normalizeAPI({
    // 'string': {
    // mandatory: ['title', 'body'],
    // defaults: {'icon':'icon'}
    // },/*from  ww  w.j av  a2  s  . co  m*/
    //
    // 'number': {
    // mandatory: ['id', 'timeMillisSince1970'],
    // // the number of ms after which we start prioritising more recent
    // things above you.
    // defaults: {'epsilon': 1000 * 60 * 24 * 365}
    // },
    //
    // 'boolean': {
    // defaults: {
    // 'vibrate': false,
    // 'sound': false
    // }
    // }

    int icon = settings.getInt("notification_icon", -1);
    if (icon == -1) {
        Log.e(C.TAG, "Need a notification_icon resource in the meta-data of LocalNotificationsAlarmReceiver");
        return null;
    }

    Notification n = new Notification();
    n.icon = icon;
    n.flags = Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
    long alarmTime = obj.optLong("timeMillisSince1970");
    long displayTime = obj.optLong("displayTimestamp", alarmTime);
    n.when = displayTime;
    n.tickerText = obj.optString("body");
    n.setLatestEventInfo(mContext, obj.optString("title"), obj.optString("body"), null);

    if (obj.optBoolean("vibrate")) {
        n.defaults |= Notification.DEFAULT_VIBRATE;
    }
    if (obj.optBoolean("sound")) {
        n.defaults |= Notification.DEFAULT_SOUND;
    }

    String uriString = settings.getString("content_uri_prefix");
    if (uriString == null) {
        Log.e(C.TAG, "Need a content_uri_prefix in the meta-data of LocalNotificationsAlarmReceiver");
        return null;
    }

    if (uriString.contains("%d")) {
        uriString = String.format(uriString, obj.optInt("id"));
    }
    Uri uri = Uri.parse(uriString);

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.setData(uri);
    n.contentIntent = PendingIntent.getActivity(mContext, 23, intent, PendingIntent.FLAG_ONE_SHOT);
    return n;
}

From source file:com.remobile.file.AssetFilesystem.java

@Override
public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, String path, JSONObject options,
        boolean directory)
        throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
    if (options != null && options.optBoolean("create")) {
        throw new UnsupportedOperationException("Assets are read-only");
    }/*w  ww.  j av  a 2  s .  c  o  m*/

    // Check whether the supplied path is absolute or relative
    if (directory && !path.endsWith("/")) {
        path += "/";
    }

    LocalFilesystemURL requestedURL;
    if (path.startsWith("/")) {
        requestedURL = localUrlforFullPath(normalizePath(path));
    } else {
        requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
    }

    // Throws a FileNotFoundException if it doesn't exist.
    getFileMetadataForLocalURL(requestedURL);

    boolean isDir = isDirectory(requestedURL.path);
    if (directory && !isDir) {
        throw new TypeMismatchException("path doesn't exist or is file");
    } else if (!directory && isDir) {
        throw new TypeMismatchException("path doesn't exist or is directory");
    }

    // Return the directory
    return makeEntryForURL(requestedURL);
}

From source file:com.fuse.billing.android.Purchase.java

public Purchase(String jsonPurchaseInfo) throws JSONException {
    mOriginalJson = jsonPurchaseInfo;// w ww. j  a v a2  s.  co  m
    JSONObject o = new JSONObject(mOriginalJson);
    mOrderId = o.optString("orderId");
    mPackageName = o.optString("packageName");
    mSku = o.optString("productId");
    mPurchaseTime = o.optLong("purchaseTime");
    mPurchaseState = o.optInt("purchaseState");
    mDeveloperPayload = o.optString("developerPayload");
    mToken = o.optString("token", o.optString("purchaseToken"));
    mIsAutoRenewing = o.optBoolean("autoRenewing");
    mSignature = o.optString("signature");
    mItemType = o.optString("itemType");
}

From source file:org.official.json.Cookie.java

/**
 * Convert a JSONObject into a cookie specification string. The JSONObject
 * must contain "name" and "value" members.
 * If the JSONObject contains "expires", "domain", "path", or "secure"
 * members, they will be appended to the cookie specification string.
 * All other members are ignored.//from  w w  w .  java 2s . c  o m
 * @param jo A JSONObject
 * @return A cookie specification string
 * @throws JSONException
 */
public static String toString(JSONObject jo) throws JSONException {
    StringBuilder sb = new StringBuilder();

    sb.append(escape(jo.getString("name")));
    sb.append("=");
    sb.append(escape(jo.getString("value")));
    if (jo.has("expires")) {
        sb.append(";expires=");
        sb.append(jo.getString("expires"));
    }
    if (jo.has("domain")) {
        sb.append(";domain=");
        sb.append(escape(jo.getString("domain")));
    }
    if (jo.has("path")) {
        sb.append(";path=");
        sb.append(escape(jo.getString("path")));
    }
    if (jo.optBoolean("secure")) {
        sb.append(";secure");
    }
    return sb.toString();
}

From source file:com.example.SmartBoard.MQTTHandler.java

public void messageArrived(String topic, MqttMessage message) {
    MyActivity drawingActivity = (MyActivity) drawingContext;
    JSONObject recvMessage = null;

    if (message.toString().compareTo("") == 0) {
        //user went offline
        String[] topicStruct = topic.split("/");
        // System.out.println("user to be removed: "+topicStruct[2]);

        if (topicStruct[2].compareTo("users") == 0) {
            usersListHistory.remove(new OnlineStateMessage(null, topicStruct[3]));
            usersAdapter.notifyDataSetChanged();

        } else if (topicStruct[2].compareTo("objects") == 0) {
            drawingActivity.drawer.removeObject(topicStruct[3]);
        }//from  ww  w  .j a  va2 s.c  o  m
        return;
    }

    try {
        recvMessage = new JSONObject(message.toString());
    } catch (JSONException j) {
        j.printStackTrace();
    }

    if (recvMessage.optString("status").compareTo("online") == 0) {

        OnlineStateMessage newUser = new OnlineStateMessage(recvMessage.optString("selfie"),
                recvMessage.optString("userId"));
        // System.out.println("user added: "+ recvMessage.optString("userId"));
        usersListHistory.add(newUser);
        usersAdapter.notifyDataSetChanged();
        return;

    }

    String clientId = recvMessage.optString("clientId");

    if (clientId.compareTo(client.getClientId()) != 0) {

        switch (type.valueOf(recvMessage.optString("type"))) {

        case Point:
            drawingActivity.drawer.drawPoint((float) recvMessage.optDouble("mX"),
                    (float) recvMessage.optDouble("mY"), recvMessage.optInt("drawActionFlag"),
                    recvMessage.optInt("color"), recvMessage.optString("mode"), recvMessage.optInt("brushSize"),
                    recvMessage.optString("clientId"));
            break;
        case Eraser:
            float eSize = (float) recvMessage.optDouble("size");
            drawingActivity.drawer.updateEraseSize(eSize);
            break;
        case Pencil: //shares topic with Eraser
            float size = (float) recvMessage.optDouble("size");
            drawingActivity.drawer.updateBrushSize(size);
            break;

        case ColorChange:
            drawingActivity.drawer.updateColor(recvMessage.optInt("code"));
            break;

        case ClearScreen:
            drawingActivity.drawer.updateClearScreen();
            break;
        case Chat:
            Vibrator v = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(new long[] { 3, 100 }, -1);

            String[] nameMessage = recvMessage.optString("message").split(":");
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
                    .setLargeIcon(stringToBitmap(recvMessage.optString("selfie")))
                    .setSmallIcon(R.drawable.smart2).setContentTitle(nameMessage[0])
                    .setContentText(nameMessage[1]).setTicker("New Message Arrived").setAutoCancel(true)
                    .setNumber(++numMessages);

            NotificationManager mNotificationManager = (NotificationManager) ctx
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            // mId allows you to update the notification later on.
            mNotificationManager.notify(1000, mBuilder.build());

            ChatMessageWithSelfie mChatMessage = new ChatMessageWithSelfie(recvMessage.optBoolean("direction"),
                    recvMessage.optString("message"), recvMessage.optString("selfie"),
                    recvMessage.optString("imageSent"), null);
            sessionHistory.add(mChatMessage);
            Chat.chatAdapter.add(mChatMessage);
            break;

        case Image:
            Vibrator v2 = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v2.vibrate(new long[] { 3, 100 }, -1);
            Toast.makeText(ctx, recvMessage.optString("username") + " has sent you a message!",
                    Toast.LENGTH_SHORT).show();
            ChatMessageWithSelfie mChatImageMessage = new ChatMessageWithSelfie(
                    recvMessage.optBoolean("direction"), null, recvMessage.optString("selfie"),
                    recvMessage.optString("image"), null);
            sessionHistory.add(mChatImageMessage);
            Chat.chatAdapter.add(mChatImageMessage);
            break;
        case Rectangle:
            drawingActivity.drawer.onDrawReceivedRectangle(recvMessage);
            break;
        case Circle:
            drawingActivity.drawer.onDrawReceivedCircle(recvMessage);
            break;
        case Line:
            drawingActivity.drawer.onDrawReceivedLine(recvMessage);
            break;
        case Text:
            drawingActivity.drawer.onDrawReceivedText(recvMessage);
            break;
        default:
            //ignore the message
        }
    }
}

From source file:com.ammobyte.radioreddit.api.GetSongInfo.java

@Override
protected Boolean doInBackground(String... params) {
    final String cookie = params[0]; // This will be null if not logged in

    // Prepare GET with cookie, execute it, parse response as JSON
    JSONObject response = null;/* ww  w .j  a  v a 2s.  c  o  m*/
    try {
        final HttpClient httpClient = new DefaultHttpClient();
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("url", mSong.reddit_url));
        final HttpGet httpGet = new HttpGet(
                "http://www.reddit.com/api/info.json?" + URLEncodedUtils.format(nameValuePairs, "utf-8"));
        if (cookie != null) {
            // Using HttpContext, CookieStore, and friends didn't work
            httpGet.setHeader("Cookie", "reddit_session=" + cookie);
        }
        httpGet.setHeader("User-Agent", RedditApi.USER_AGENT);
        final HttpResponse httpResponse = httpClient.execute(httpGet);
        response = new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
    } catch (UnsupportedEncodingException e) {
        Log.i(RedditApi.TAG, "UnsupportedEncodingException while getting song info", e);
    } catch (ClientProtocolException e) {
        Log.i(RedditApi.TAG, "ClientProtocolException while getting song info", e);
    } catch (IOException e) {
        Log.i(RedditApi.TAG, "IOException while getting song info", e);
    } catch (ParseException e) {
        Log.i(RedditApi.TAG, "ParseException while getting song info", e);
    } catch (JSONException e) {
        Log.i(RedditApi.TAG, "JSONException while getting song info", e);
    }

    // Check for failure
    if (response == null) {
        Log.i(RedditApi.TAG, "Response is null");
        return false;
    }

    // Get the info we want
    final JSONObject data1 = response.optJSONObject("data");
    if (data1 == null) {
        Log.i(RedditApi.TAG, "First data is null");
        return false;
    }
    final String modhash = data1.optString("modhash", "");
    if (modhash.length() > 0) {
        mService.setModhash(modhash);
    }
    final JSONArray children = data1.optJSONArray("children");
    if (children == null) {
        Log.i(RedditApi.TAG, "Children is null");
        return false;
    }
    final JSONObject child = children.optJSONObject(0);
    if (child == null) {
        // This is common if the song hasn't been submitted to reddit yet
        // so we intentionally don't log this case
        return false;
    }
    final String kind = child.optString("kind");
    if (kind == null) {
        Log.i(RedditApi.TAG, "Kind is null");
        return false;
    }
    final JSONObject data2 = child.optJSONObject("data");
    if (data2 == null) {
        Log.i(RedditApi.TAG, "Second data is null");
        return false;
    }
    final String id = data2.optString("id");
    if (id == null) {
        Log.i(RedditApi.TAG, "Id is null");
        return false;
    }
    final int score = data2.optInt("score");
    Boolean likes = null;
    if (!data2.isNull("likes")) {
        likes = data2.optBoolean("likes");
    }
    final boolean saved = data2.optBoolean("saved");

    // Modify song with collected info
    if (kind != null && id != null) {
        mSong.reddit_id = kind + "_" + id;
    } else {
        mSong.reddit_id = null;
    }
    mSong.upvoted = (likes != null && likes == true);
    mSong.downvoted = (likes != null && likes == false);
    mSong.votes = score;
    mSong.saved = saved;

    return true;
}

From source file:edu.umass.cs.gigapaxos.paxospackets.StatePacket.java

public StatePacket(JSONObject json) throws JSONException {
    super(json);//from   w w  w.  j a v  a 2  s.c  o  m
    assert (PaxosPacket.getPaxosPacketType(json) == PaxosPacketType.CHECKPOINT_STATE);
    this.packetType = PaxosPacketType.CHECKPOINT_STATE;
    this.slotNumber = json.getInt(PaxosPacket.Keys.S.toString());
    this.ballot = new Ballot(json.getString(PaxosPacket.NodeIDKeys.B.toString()));
    this.state = json.getString(PaxosPacket.Keys.STATE.toString());
    this.isLargeCheckpoint = json.optBoolean(PaxosPacket.Keys.BIG_CP.toString());
}

From source file:edu.asu.bscs.csiebler.waypointapplication.WaypointServerStub.java

/**
 *
 * @return//from   w w w.j a  v  a 2  s  . c  o m
 */
public boolean saveToFile() {
    boolean result = false;

    try {
        String jsonStr = this.packageWaypointCall("saveToFile", null, null);
        debug("sending: " + jsonStr);
        String resString = server.call(jsonStr);
        debug("got back: " + resString);
        JSONObject res = new JSONObject(resString);
        result = res.optBoolean("result");
    } catch (Exception ex) {
        System.out.println("exception in rpc call to saveToFile: " + ex.getMessage());
    }

    return result;
}