Example usage for org.json JSONObject optLong

List of usage examples for org.json JSONObject optLong

Introduction

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

Prototype

public long optLong(String key) 

Source Link

Document

Get an optional long value associated with a key, or zero if there is no such key or if the value is not a number.

Usage

From source file:com.jelly.music.player.GMusicHelpers.WebClientSongsSchema.java

@Override
public WebClientSongsSchema fromJsonObject(JSONObject jsonObject) {

    if (jsonObject != null) {
        mTotalTracks = jsonObject.optInt("totalTracks");
        mSubjectToCuration = jsonObject.optBoolean("subjectToCuration");
        mName = jsonObject.optString("name", null);
        mTotalDiscs = jsonObject.optInt("totalDiscs");
        mTitleNorm = jsonObject.optString("titleNorm", null);
        mAlbumNorm = jsonObject.optString("albumNorm", null);
        mTrack = jsonObject.optInt("track");
        mAlbumArtUrl = jsonObject.optString("albumArtUrl", null);
        mUrl = jsonObject.optString("url", null);
        mCreationDate = jsonObject.optLong("creationDate");
        mAlbumArtistNorm = jsonObject.optString("albumArtistNorm", null);
        mArtistNorm = jsonObject.optString("artistNorm", null);
        mLastPlayed = jsonObject.optLong("lastPlayed");
        mMatchedId = jsonObject.optString("matchedId", null);
        mType = jsonObject.optInt("type");
        mDisc = jsonObject.optInt("disc");
        mGenre = jsonObject.optString("genre", null);
        mBeatsPerMinute = jsonObject.optInt("beatsPerMinute");
        mAlbum = jsonObject.optString("album", null);
        mId = jsonObject.optString("id", null);
        mComposer = jsonObject.optString("composer", null);
        mTitle = jsonObject.optString("title", null);
        mAlbumArtist = jsonObject.optString("albumArtist", null);
        mYear = jsonObject.optInt("year");
        mArtist = jsonObject.optString("artist", null);
        mDurationMillis = jsonObject.optLong("durationMillis");
        mIsDeleted = jsonObject.optBoolean("deleted");
        mPlayCount = jsonObject.optInt("playCount");
        mRating = jsonObject.optString("rating", null);
        mComment = jsonObject.optString("comment", null);
        mPlaylistEntryId = jsonObject.optString("playlistEntryId");
    }/*ww  w . jav  a 2  s . c  o  m*/

    //This method returns itself to support chaining.
    return this;
}

From source file:org.catnut.metadata.Comment.java

@Override
public ContentValues convert(JSONObject data) {
    ContentValues values = new ContentValues();
    values.put(BaseColumns._ID, data.optLong(Constants.ID));
    values.put(created_at, data.optString(created_at));
    values.put(columnText, data.optString(text));
    values.put(source, data.optString(source));
    JSONObject user = data.optJSONObject(User.SINGLE);
    if (user != null) {
        values.put(uid, user.optLong(Constants.ID));
    }//  w w  w.  j a  va2s  . com
    values.put(status, data.optString(status));
    values.put(reply_comment, data.optString(reply_comment));
    return values;
}

From source file:com.parking.billing.Security.java

/**
 * Verifies that the data was signed with the given signature, and returns
 * the list of verified purchases. The data is in JSON format and contains
 * a nonce (number used once) that we generated and that was signed
 * (as part of the whole data string) with a private key. The data also
 * contains the {@link PurchaseState} and product ID of the purchase.
 * In the general case, there can be an array of purchase transactions
 * because there may be delays in processing the purchase on the backend
 * and then several purchases can be batched together.
 * @param signedData the signed JSON string (signed, not encrypted)
 * @param signature the signature for the data, signed with the private key
 *//*from  w  w w  .  j  a  v a  2s  . c  om*/
public static ArrayList<VerifiedPurchase> verifyPurchase(String signedData, String signature) {
    if (signedData == null) {
        Log.e(TAG, "data is null");
        return null;
    }
    if (BillingConstants.DEBUG) {
        Log.i(TAG, "signedData: " + signedData);
    }

    boolean verified = false;

    if (!TextUtils.isEmpty(signature)) {
        /**
         * Compute your public key (that you got from the Android Market publisher site).
         *
         * Instead of just storing the entire literal string here embedded in the
         * program,  construct the key at runtime from pieces or
         * use bit manipulation (for example, XOR with some other string) to hide
         * the actual key.  The key itself is not secret information, but we don't
         * want to make it easy for an adversary to replace the public key with one
         * of their own and then fake messages from the server.
         *
         * Generally, encryption keys / passwords should only be kept in memory
         * long enough to perform the operation they need to perform.
         */
        //Chintan's Key
        String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuRIrk/6nAPzZo5HKe261/ZMfoe63mtY5QUlc0A0/77RTicrS9Nk1VjtVniRpHmjasQOGsQrBpBGJUYp0ixsjJpgfjLv7OvpF8Hp/ucth2T/Bm7kl/odRDT3urAp3snvqZEzfOg1wtDU7DAnDW1zNSqVNCVczXRnNrEmGxEjamKkTTQwz37ui7AhjKXCXAJY4n5ANj1oymnjGN5FHfzcMb07wR/ucz39ZX+Raf6qBsbnYkmuDH6pJ/4ZI9+vjbgWzXCx07DefQW4dtNMQZlVlKgKnJUkafePUYJVIO4sRgeWL1e5b8dbIYMO7gB9oopyfVhZifi+pDGr5+YAxi6D3PwIDAQAB";
        //Mandar's Key:
        //String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj7zgTswMi1ePyAK7rCnCOkpmviHZzoSn2cxtyQ5ZQRFifNGkKq3Gli3VbeIeeJR8GHzlfOPUSgtMrd17WtGJoo29rsw6UuXov+imQutGKZglcM/cIrlIdZCsse3dGYyDcKFhEHrC/nPdwlYxgIGBaZKAcbbhitkdgYaVHQvGFTagCytxDq9NDJAY7exSKKm2HimfjlcBZjhHeImZ+cRCPux+9uoBQ4mTRYjrXfcpi/OPKTKsq2AHXf/y60qsZJlgGl3tBgRQo6lOEr7UbbHKESTKvOQ4t3J1wjNz8Z3+T0PZHb5JkeTsdAE7cG7jmz2HmMxfdXcT5mBTTDei6DPDGwIDAQAB";
        PublicKey key = Security.generatePublicKey(base64EncodedPublicKey);
        verified = Security.verify(key, signedData, signature);
        if (!verified) {
            Log.w(TAG, "signature does not match data.");
            return null;
        }
    }

    JSONObject jObject;
    JSONArray jTransactionsArray = null;
    int numTransactions = 0;
    long nonce = 0L;
    try {
        jObject = new JSONObject(signedData);

        // The nonce might be null if the user backed out of the buy page.
        nonce = jObject.optLong("nonce");
        jTransactionsArray = jObject.optJSONArray("orders");
        if (jTransactionsArray != null) {
            numTransactions = jTransactionsArray.length();
        }
    } catch (JSONException e) {
        return null;
    }

    if (!Security.isNonceKnown(nonce)) {
        Log.w(TAG, "Nonce not found: " + nonce);
        return null;
    }

    ArrayList<VerifiedPurchase> purchases = new ArrayList<VerifiedPurchase>();
    try {
        for (int i = 0; i < numTransactions; i++) {
            JSONObject jElement = jTransactionsArray.getJSONObject(i);
            int response = jElement.getInt("purchaseState");
            PurchaseState purchaseState = PurchaseState.valueOf(response);
            String productId = jElement.getString("productId");
            String packageName = jElement.getString("packageName");
            long purchaseTime = jElement.getLong("purchaseTime");
            String orderId = jElement.optString("orderId", "");
            String notifyId = null;
            if (jElement.has("notificationId")) {
                notifyId = jElement.getString("notificationId");
            }
            String developerPayload = jElement.optString("developerPayload", null);

            // If the purchase state is PURCHASED, then we require a
            // verified nonce.

            /**
             *   mandarm - We are ok with no signature for our test code! 
             */
            //TODO - Take care for signed purchases.

            if (purchaseState == PurchaseState.PURCHASED && !verified) {
                continue;
            }

            purchases.add(new VerifiedPurchase(purchaseState, notifyId, productId, orderId, purchaseTime,
                    developerPayload));
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSON exception: ", e);
        return null;
    }
    removeNonce(nonce);
    return purchases;
}

From source file:de.luhmer.owncloudnewsreader.reader.owncloud.InsertFeedIntoDatabase.java

private static Feed parseFeed(JSONObject e) {
    String faviconLink = e.optString("faviconLink");
    if (faviconLink != null)
        if (faviconLink.equals("null") || faviconLink.trim().equals(""))
            faviconLink = null;//from   www  .  j a v  a  2 s.  c  om

    Feed feed = new Feed();
    feed.setId(e.optLong("id"));
    feed.setFeedTitle(e.optString("title"));
    feed.setFolderId(e.optLong("folderId"));
    feed.setFaviconUrl(faviconLink);

    return feed;
}

From source file:com.github.jberkel.pay.me.model.Purchase.java

/**
 * @param itemType the item type for this purchase, cannot be null.
 * @param jsonPurchaseInfo the JSON representation of this purchase
 * @param signature the signature/*w w w  .  ja  v a 2  s  .  co m*/
 * @throws JSONException if the purchase cannot be parsed or is invalid.
 */
public Purchase(ItemType itemType, String jsonPurchaseInfo, String signature) throws JSONException {
    if (itemType == null)
        throw new IllegalArgumentException("itemType cannot be null");
    mItemType = itemType;
    final JSONObject json = new JSONObject(jsonPurchaseInfo);

    mOrderId = json.optString(ORDER_ID);
    mPackageName = json.optString(PACKAGE_NAME);
    mSku = json.optString(PRODUCT_ID);
    mPurchaseTime = json.optLong(PURCHASE_TIME);
    mPurchaseState = json.optInt(PURCHASE_STATE);
    mDeveloperPayload = json.optString(DEVELOPER_PAYLOAD);
    mToken = json.optString(TOKEN, json.optString(PURCHASE_TOKEN));

    mOriginalJson = jsonPurchaseInfo;
    mSignature = signature;
    mState = State.fromCode(mPurchaseState);

    if (TextUtils.isEmpty(mSku)) {
        throw new JSONException("SKU is empty");
    }
}

From source file:ezturner.limitvolume.billing.SkuDetails.java

public SkuDetails(String itemType, String jsonSkuDetails) throws JSONException {
    mItemType = itemType;/*from w w w. j  a v  a2 s .c  o m*/
    mJson = jsonSkuDetails;
    JSONObject o = new JSONObject(mJson);
    mSku = o.optString("productId");
    mType = o.optString("type");
    mPrice = o.optString("price");
    mPriceAmountMicros = o.optLong("price_amount_micros");
    mPriceCurrencyCode = o.optString("price_currency_code");
    mTitle = o.optString("title");
    mDescription = o.optString("description");
}

From source file:com.vk.sdkweb.api.model.VKApiPhoto.java

/**
 * Fills a Photo instance from JSONObject.
 *//*  w  w w  .  j a  v a 2  s.c  o  m*/
public VKApiPhoto parse(JSONObject from) {
    album_id = from.optInt("album_id");
    date = from.optLong("date");
    height = from.optInt("height");
    width = from.optInt("width");
    owner_id = from.optInt("owner_id");
    id = from.optInt("id");
    text = from.optString("text");
    access_key = from.optString("access_key");

    photo_75 = from.optString("photo_75");
    photo_130 = from.optString("photo_130");
    photo_604 = from.optString("photo_604");
    photo_807 = from.optString("photo_807");
    photo_1280 = from.optString("photo_1280");
    photo_2560 = from.optString("photo_2560");

    JSONObject likes = from.optJSONObject("likes");
    this.likes = ParseUtils.parseInt(likes, "count");
    this.user_likes = ParseUtils.parseBoolean(likes, "user_likes");
    comments = parseInt(from.optJSONObject("comments"), "count");
    tags = parseInt(from.optJSONObject("tags"), "count");
    can_comment = parseBoolean(from, "can_comment");

    src.setOriginalDimension(width, height);
    JSONArray photo_sizes = from.optJSONArray("sizes");
    if (photo_sizes != null) {
        src.fill(photo_sizes);
    } else {
        if (!TextUtils.isEmpty(photo_75)) {
            src.add(VKApiPhotoSize.create(photo_75, VKApiPhotoSize.S, width, height));
        }
        if (!TextUtils.isEmpty(photo_130)) {
            src.add(VKApiPhotoSize.create(photo_130, VKApiPhotoSize.M, width, height));
        }
        if (!TextUtils.isEmpty(photo_604)) {
            src.add(VKApiPhotoSize.create(photo_604, VKApiPhotoSize.X, width, height));
        }
        if (!TextUtils.isEmpty(photo_807)) {
            src.add(VKApiPhotoSize.create(photo_807, VKApiPhotoSize.Y, width, height));
        }
        if (!TextUtils.isEmpty(photo_1280)) {
            src.add(VKApiPhotoSize.create(photo_1280, VKApiPhotoSize.Z, width, height));
        }
        if (!TextUtils.isEmpty(photo_2560)) {
            src.add(VKApiPhotoSize.create(photo_2560, VKApiPhotoSize.W, width, height));
        }
        src.sort();
    }
    return this;
}

From source file:com.vk.sdkweb.api.model.VKApiPost.java

/**
 * Fills a Post instance from JSONObject.
 *//*from  ww  w.  java  2 s .  c  o m*/
public VKApiPost parse(JSONObject source) throws JSONException {
    id = source.optInt("id");
    to_id = source.optInt("to_id");
    from_id = source.optInt("from_id");
    date = source.optLong("date");
    text = source.optString("text");
    reply_owner_id = source.optInt("reply_owner_id");
    reply_post_id = source.optInt("reply_post_id");
    friends_only = ParseUtils.parseBoolean(source, "friends_only");
    JSONObject comments = source.optJSONObject("comments");
    if (comments != null) {
        comments_count = comments.optInt("count");
        can_post_comment = ParseUtils.parseBoolean(comments, "can_post");
    }
    JSONObject likes = source.optJSONObject("likes");
    if (likes != null) {
        likes_count = likes.optInt("count");
        user_likes = ParseUtils.parseBoolean(likes, "user_likes");
        can_like = ParseUtils.parseBoolean(likes, "can_like");
        can_publish = ParseUtils.parseBoolean(likes, "can_publish");
    }
    JSONObject reposts = source.optJSONObject("reposts");
    if (reposts != null) {
        reposts_count = reposts.optInt("count");
        user_reposted = ParseUtils.parseBoolean(reposts, "user_reposted");
    }
    post_type = source.optString("post_type");
    attachments.fill(source.optJSONArray("attachments"));
    JSONObject geo = source.optJSONObject("geo");
    if (geo != null) {
        this.geo = new VKApiPlace().parse(geo);
    }
    signer_id = source.optInt("signer_id");
    copy_history = new VKList<VKApiPost>(source.optJSONArray("copy_history"), VKApiPost.class);
    return this;
}

From source file:jfabrix101.billing.BillingSecurity.java

/**
 * Verifies that the data was signed with the given signature, and returns
 * the list of verified purchases. The data is in JSON format and contains
 * a nonce (number used once) that we generated and that was signed
 * (as part of the whole data string) with a private key. The data also
 * contains the {@link PurchaseState} and product ID of the purchase.
 * In the general case, there can be an array of purchase transactions
 * because there may be delays in processing the purchase on the backend
 * and then several purchases can be batched together.
 * @param signedData the signed JSON string (signed, not encrypted)
 * @param signature the signature for the data, signed with the private key
 *//*  w ww. jav  a 2s  . c om*/
public static ArrayList<VerifiedPurchase> verifyPurchase(Context context, String signedData, String signature) {
    if (signedData == null) {
        Log.e(TAG, "data is null");
        return null;
    }
    if (BillingConsts.DEBUG) {
        Log.i(TAG, "signedData: " + signedData);
    }
    boolean verified = false;
    if (!TextUtils.isEmpty(signature)) {
        /**
         * Compute your public key (that you got from the Android Market publisher site).
         *
         * Instead of just storing the entire literal string here embedded in the
         * program,  construct the key at runtime from pieces or
         * use bit manipulation (for example, XOR with some other string) to hide
         * the actual key.  The key itself is not secret information, but we don't
         * want to make it easy for an adversary to replace the public key with one
         * of their own and then fake messages from the server.
         *
         * Generally, encryption keys / passwords should only be kept in memory
         * long enough to perform the operation they need to perform.
         */

        SharedPreferences pref = context.getSharedPreferences("billingPK", 0);
        AESObfuscator obfuscator = AESObfuscator.getDefaultObfuscator(context);
        String publicKey = "";
        try {
            publicKey = obfuscator.unobfuscate(pref.getString("pk", ""));
        } catch (Exception e) {
            Log.e(TAG, "Error getting publicc key from repository");
            return null;
        }
        PublicKey key = BillingSecurity.generatePublicKey(publicKey);
        verified = BillingSecurity.verify(key, signedData, signature);
        if (!verified) {
            Log.w(TAG, "signature does not match data.");
            return null;
        }
    }

    JSONObject jObject;
    JSONArray jTransactionsArray = null;
    int numTransactions = 0;
    long nonce = 0L;
    try {
        jObject = new JSONObject(signedData);

        // The nonce might be null if the user backed out of the buy page.
        nonce = jObject.optLong("nonce");
        jTransactionsArray = jObject.optJSONArray("orders");
        if (jTransactionsArray != null) {
            numTransactions = jTransactionsArray.length();
        }
    } catch (JSONException e) {
        return null;
    }

    if (!BillingSecurity.isNonceKnown(nonce)) {
        Log.w(TAG, "Nonce not found: " + nonce);
        return null;
    }

    ArrayList<VerifiedPurchase> purchases = new ArrayList<VerifiedPurchase>();
    try {
        for (int i = 0; i < numTransactions; i++) {
            JSONObject jElement = jTransactionsArray.getJSONObject(i);
            int response = jElement.getInt("purchaseState");
            PurchaseState purchaseState = PurchaseState.valueOf(response);
            String productId = jElement.getString("productId");
            //String packageName = jElement.getString("packageName");
            long purchaseTime = jElement.getLong("purchaseTime");
            String orderId = jElement.optString("orderId", "");
            String notifyId = null;
            if (jElement.has("notificationId")) {
                notifyId = jElement.getString("notificationId");
            }
            String developerPayload = jElement.optString("developerPayload", null);

            // If the purchase state is PURCHASED, then we require a verified nonce.
            if (purchaseState == PurchaseState.PURCHASED && !verified) {
                continue;
            }
            purchases.add(new VerifiedPurchase(purchaseState, notifyId, productId, orderId, purchaseTime,
                    developerPayload));
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSON exception: ", e);
        return null;
    }
    removeNonce(nonce);
    return purchases;
}

From source file:mc.inappbilling.Purchase.java

public Purchase(String json, String signature) throws JSONException {
    this.json = json;
    JSONObject o = new JSONObject(json);
    this.orderId = o.optString("orderId");
    this.packageName = o.optString("packageName");
    this.sku = o.optString("productId");
    this.purchaseTime = o.optLong("purchaseTime");
    this.purchaseState = o.optInt("purchaseState");
    this.developerPayload = o.optString("developerPayload");
    this.token = o.optString("token", o.optString("purchaseToken"));
    this.signature = signature;
}