Java Code Examples for org.json.JSONObject#optLong()

The following examples show how to use org.json.JSONObject#optLong() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: QoSServerResult.java    From open-rmbt with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param json
 */
@SuppressWarnings("unchecked")
public QoSServerResult(JSONObject json) {
	try {
		testType = QoSTestResultEnum.valueOf(json.optString(JSON_KEY_TESTTYPE).toUpperCase(Locale.US));
		testDescription = json.optString(JSON_KEY_TEST_DESCRIPTION);
		testSummary = json.optString(JSON_KEY_TEST_SUMMARY);
		successCount = Integer.valueOf(json.optString(JSON_KEY_SUCCESS_COUNT));
		failureCount = Integer.valueOf(json.optString(JSON_KEY_FAILURE_COUNT));
		onFailureBehaviour = json.optString(JSON_KEY_ON_FAILURE_BEHAVIOUR, DEFAULT_ON_FAILURE_BEHAVIOUR);
		uid = json.optLong(JSON_KEY_UID);
		JSONObject resultObj = json.optJSONObject(JSON_KEY_RESULT_MAP);
	
		if (resultObj != null) {
			Iterator<String> keys = resultObj.keys();
			while (keys.hasNext()) {
				String key = keys.next();
				resultMap.put(key, resultObj.optString(key));
			}
		}
	}
	catch (Throwable t) {
		testType = null;
		resultMap = null;
	}
}
 
Example 2
Source File: JournalQueryService.java    From symphonyx with Apache License 2.0 6 votes vote down vote up
/**
 * Section generated today?
 *
 * @return {@code true} if section generated, returns {@code false} otherwise
 */
public synchronized boolean hasSectionToday() {
    try {
        final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING).
                setCurrentPageNum(1).setPageSize(1);

        query.setFilter(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.EQUAL,
                Article.ARTICLE_TYPE_C_JOURNAL_SECTION));

        final JSONObject result = articleRepository.get(query);
        final List<JSONObject> journals = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));

        if (journals.isEmpty()) {
            return false;
        }

        final JSONObject maybeToday = journals.get(0);
        final long created = maybeToday.optLong(Article.ARTICLE_CREATE_TIME);

        return DateUtils.isSameDay(new Date(created), new Date());
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Check section generated failed", e);

        return false;
    }
}
 
Example 3
Source File: GooglePlayInAppService.java    From atomic-plugins-inapps with Mozilla Public License 2.0 5 votes vote down vote up
public static GPInAppPurchase from(String purchaseData, String signature) throws JSONException {

            JSONObject jo = new JSONObject(purchaseData);
            GPInAppPurchase purchase = new GPInAppPurchase();
            purchase.signature = signature;
            purchase.purchaseData = purchaseData;
            purchase.productId = jo.getString("productId");
            purchase.transactionId = jo.getString("orderId");
            purchase.quantity = 1;
            purchase.purchaseState = jo.getInt("purchaseState");
            purchase.purchaseToken = jo.getString("purchaseToken");
            purchase.developerPayload = jo.optString("developerPayload");
            purchase.purchaseDate = new Date(jo.optLong("purchaseTime"));
            return purchase;
        }
 
Example 4
Source File: AccountResponse.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public void from(JSONObject obj) {
	if (obj != null) {
		this.result = obj.optString("result");
		JSONObject account = obj.optJSONObject("account");
		if (account != null) {
			this.address = account.optString("address");
			this.parent = account.optString("parent");
			this.inception = account.optString("inception");
			this.tx_hash = account.optString("tx_hash");
			this.initial_balance = account.optDouble("initial_balance");
			this.ledger_index = account.optLong("ledger_index");
		}
	}
}
 
Example 5
Source File: VKApiMessage.java    From cordova-social-vk with Apache License 2.0 5 votes vote down vote up
/**
 * Fills a Message instance from JSONObject.
 */
public VKApiMessage parse(JSONObject source) throws JSONException {
    id = source.optInt("id");
    user_id = source.optInt("user_id");
    date = source.optLong("date");
    read_state = ParseUtils.parseBoolean(source, "read_state");
    out = ParseUtils.parseBoolean(source, "out");
    title = source.optString("title");
    body = source.optString("body");
    attachments .fill(source.optJSONArray("attachments"));
    fwd_messages = new VKList<VKApiMessage>(source.optJSONArray("fwd_messages"), VKApiMessage.class);
    emoji = ParseUtils.parseBoolean(source, "emoji");
    deleted = ParseUtils.parseBoolean(source, "deleted");
    return this;
}
 
Example 6
Source File: MarketComponent.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public void from(JSONObject obj) {
	if (obj != null) {
		this.base.copyFrom(obj.opt("base"));
		this.counter.copyFrom(obj.opt("counter"));
		this.rate = obj.optDouble("rate");
		this.count = obj.optLong("count");
		this.amount = obj.optDouble("amount");
		this.convertedAmount = obj.optDouble("convertedAmount");
	}
}
 
Example 7
Source File: ActivityQueryService.java    From symphonyx with Apache License 2.0 5 votes vote down vote up
/**
 * Does checkin today?
 *
 * @param userId the specified user id
 * @return {@code true} if checkin succeeded, returns {@code false} otherwise
 */
public synchronized boolean isCheckedinToday(final String userId) {
    final Calendar calendar = Calendar.getInstance();
    final int hour = calendar.get(Calendar.HOUR_OF_DAY);
    if (hour < Symphonys.getInt("activityDailyCheckinTimeMin")
            || hour > Symphonys.getInt("activityDailyCheckinTimeMax")) {
        return true;
    }

    final Date now = new Date();

    JSONObject user = userCache.getUser(userId);

    try {
        if (null == user) {
            user = userRepository.get(userId);
        }
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Checks checkin failed", e);

        return true;
    }

    final List<JSONObject> records = pointtransferQueryService.getLatestPointtransfers(userId,
            Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_CHECKIN, 1);
    if (records.isEmpty()) {
        return false;
    }

    final JSONObject maybeToday = records.get(0);
    final long time = maybeToday.optLong(Pointtransfer.TIME);

    return DateUtils.isSameDay(now, new Date(time));
}
 
Example 8
Source File: KanboardActivity.java    From Kandroid with GNU General Public License v3.0 5 votes vote down vote up
public KanboardActivity(JSONObject json) {
    Title = json.optString("event_title");
    Content = json.optString("event_content");
    Creator = json.optString("author");
    CreatorUserName = json.optString("author_username");
    CreatorId = json.optInt("creator_id");
    Id = json.optInt("id");
    ProjectId = json.optInt("project_id");
    TaskId = json.optInt("task_id");
    DateCreation = new Date(json.optLong("date_creation") * 1000);
}
 
Example 9
Source File: Purchase.java    From Slide with GNU General Public License v3.0 5 votes vote down vote up
public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
    mItemType = itemType;
    mOriginalJson = jsonPurchaseInfo;
    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"));
    mSignature = signature;
}
 
Example 10
Source File: Capture.java    From cordova-android-chromeview with Apache License 2.0 5 votes vote down vote up
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    this.callbackContext = callbackContext;
    this.limit = 1;
    this.duration = 0;
    this.results = new JSONArray();

    JSONObject options = args.optJSONObject(0);
    if (options != null) {
        limit = options.optLong("limit", 1);
        duration = options.optInt("duration", 0);
    }

    if (action.equals("getFormatData")) {
        JSONObject obj = getFormatData(args.getString(0), args.getString(1));
        callbackContext.success(obj);
        return true;
    }
    else if (action.equals("captureAudio")) {
        this.captureAudio();
    }
    else if (action.equals("captureImage")) {
        this.captureImage();
    }
    else if (action.equals("captureVideo")) {
        this.captureVideo(duration);
    }
    else {
        return false;
    }

    return true;
}
 
Example 11
Source File: ConfigPresenter.java    From AppOpsX with MIT License 5 votes vote down vote up
private RestoreModel readModel(File file) {
  try {
    RestoreModel model = new RestoreModel();
    model.path = file.getAbsolutePath();
    model.fileName = file.getName();
    model.fileSize = file.length();

    String s = BFileUtils.read2String(file);
    JSONObject jsonObject = new JSONObject(s);
    model.createTime = jsonObject.optLong("time");
    model.version = jsonObject.optInt("v");
    model.size = jsonObject.optInt("size");
    JSONArray jsonArray = jsonObject.optJSONArray("opbacks");
    if (jsonArray != null && jsonArray.length() > 0) {
      int len = jsonArray.length();
      List<PreAppInfo> preAppInfos = new ArrayList<>(len);
      for (int i = 0; i < len; i++) {
        JSONObject jo = jsonArray.optJSONObject(i);
        if (jo != null) {
          String pkg = jo.optString("pkg");
          String ops = jo.optString("ops");
          if (!TextUtils.isEmpty(pkg) && !TextUtils.isEmpty(ops)) {
            preAppInfos.add(new PreAppInfo(pkg, ops));
          }
        }
      }
      model.preAppInfos = preAppInfos;

      return model;
    }
  } catch (Exception e) {
    if (file != null) {
      file.delete();
    }
  }
  return null;
}
 
Example 12
Source File: Purchase.java    From lantern with Apache License 2.0 5 votes vote down vote up
public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
    mItemType = itemType;
    mOriginalJson = jsonPurchaseInfo;
    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"));
    mSignature = signature;
}
 
Example 13
Source File: ActivityQueryService.java    From symphonyx with Apache License 2.0 5 votes vote down vote up
/**
 * Did collect 1A0001 today?
 *
 * @param userId the specified user id
 * @return {@code true} if collected, returns {@code false} otherwise
 */
public synchronized boolean isCollected1A0001Today(final String userId) {
    final Date now = new Date();

    final List<JSONObject> records = pointtransferQueryService.getLatestPointtransfers(userId,
            Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_1A0001_COLLECT, 1);
    if (records.isEmpty()) {
        return false;
    }

    final JSONObject maybeToday = records.get(0);
    final long time = maybeToday.optLong(Pointtransfer.TIME);

    return DateUtils.isSameDay(now, new Date(time));
}
 
Example 14
Source File: RouteHistoryModel.java    From BmapLite with GNU General Public License v3.0 5 votes vote down vote up
public void fromJSON(JSONObject object) {
    this.nameStart = object.optString("nameStart");
    this.nameEnd = object.optString("nameEnd");
    this.latStart = object.optDouble("latStart", 0);
    this.lngStart = object.optDouble("lngStart", 0);
    this.latEnd = object.optDouble("latEnd", 0);
    this.lngEnd = object.optDouble("lngEnd", 0);
    this.time = object.optLong("time", 0);
}
 
Example 15
Source File: Purchase.java    From AndroidInAppPurchase with Apache License 2.0 5 votes vote down vote up
public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
    mItemType = itemType;
    mOriginalJson = jsonPurchaseInfo;
    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"));
    mSignature = signature;
}
 
Example 16
Source File: ValidatedLedger.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public void from(JSONObject validated_ledger) {
	if (validated_ledger != null) {
		this.base_fee_xrp = validated_ledger.optLong("base_fee_xrp");
		this.reserve_base_xrp = validated_ledger.optInt("reserve_base_xrp");
		this.age = validated_ledger.optInt("age");
		this.hash = validated_ledger.optString("hash");
		this.reserve_inc_xrp = validated_ledger.optInt("reserve_inc_xrp");
		this.seq = validated_ledger.optInt("seq");
	}
}
 
Example 17
Source File: StarredCardsManager.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 4 votes vote down vote up
private StarredCard(JSONObject obj) throws JSONException {
    blackCard = new Card(obj.getJSONObject("bc"));
    id = obj.getInt("id");
    whiteCards = new CardsGroup(obj.getJSONArray("wc"));
    addedAt = obj.optLong("addedAt", System.currentTimeMillis());
}
 
Example 18
Source File: IMMessageManager.java    From imsdk-android with MIT License 4 votes vote down vote up
/**
     * 插入群聊消息
     *
     * @param lastGroupTime
     * @throws JSONException
     * @throws IOException
     */
    public void getMucHistorys(double lastGroupTime) throws JSONException, IOException {
        String jid = IMLogicManager.getInstance().getMyself().getUser();
        String domain = IMLogicManager.getInstance().getMyself().getDomain();
        if (!StringUtils.isEmpty(jid)) {
            String requestUrl = String.format("%s/domain/get_muc_history_v2?server=%s&c=%s&u=%s&k=%s&p=%s&v=%s",
                    QtalkNavicationService.getInstance().getHttpHost(),
                    domain,
                    GlobalConfigManager.getAppName(),
                    IMLogicManager.getInstance().getMyself().getUser(),
                    IMLogicManager.getInstance().getRemoteLoginKey(),
                    GlobalConfigManager.getAppPlatform(),
                    GlobalConfigManager.getAppVersion());

            if (lastGroupTime <= 0) {
                lastGroupTime = System.currentTimeMillis() - 24 * 3600 * 1000;
            }

            JSONObject inputObject = new JSONObject();
//            lastGroupTime = Long.parseLong("1512576000000");
            inputObject.put("T", lastGroupTime);
            inputObject.put("u", jid);
            inputObject.put("U", jid);
            inputObject.put("D", String.format("conference.%s", domain));


            JSONObject response = QtalkHttpService.postJson(requestUrl, inputObject);

//            Logger.i("mu版本数据:", response);
            int num = 0;
            if (response != null && response.has("errcode")) {
                //请求成功 设置为true


                int errCode = response.getInt("errcode");
                if (errCode == 0) {
                    String groupId = null;
                    try {
                        groupRequest = true;
                        //返回里面又很多个data 所以需要循环一下
                        JSONArray data = response.getJSONArray("data");
                        for (int i = 0; i < data.length(); ++i) {
                            //获取其中一个data 的JsonObject
                            JSONObject groupMsgDic = data.getJSONObject(i);
                            //这里获取的是外层的domain
                            String myDomain = groupMsgDic.getString("Domain");
                            //这里是按照群消息id来分配消息的
                            groupId = String.format("%s@conference.%s",
                                    groupMsgDic.getString("ID"),
                                    myDomain);
                            //这里获取了一个时间标记
                            long readMarkT = groupMsgDic.optLong("Time");
                            JSONArray resultList = groupMsgDic.getJSONArray("Msg");
                            if (resultList == null || resultList.length() <= 0)
                                continue;

                            List msgList = null;
                            {


                                String myNickName = getGroupNickNameByGroupId(groupId);
                                String rtxId = IMLogicManager.getInstance().getMyself().getUser();
                                Logger.i("groupId:" + groupId + ";myNickName:" + myNickName);
                                num += resultList.length();
                                IMDatabaseManager.getInstance().bulkInsertGroupHistory(resultList, groupId, myNickName, readMarkT, MessageState.didRead, rtxId);
                                Logger.i("群历史记录同步成功:" + groupId);
//                                groupRequest = true;

                            }

                            updateNotReadCountCacheByJid(groupId);

                        }

                        Logger.i("xml群size:" + num);
                    } catch (Exception e) {
                        Logger.e(e, "getMucHistorys");
                        Logger.i("群历史记录同步失败:" + groupId);
                        groupRequest = false;
                    }

                }
            }
        }
    }
 
Example 19
Source File: ServiceConfig.java    From Connect-SDK-Android-Core with Apache License 2.0 4 votes vote down vote up
public ServiceConfig(JSONObject json) {
    serviceUUID = json.optString(KEY_UUID);
    lastDetected = json.optLong(KEY_LAST_DETECT);
}
 
Example 20
Source File: Container.java    From ambry with Apache License 2.0 4 votes vote down vote up
/**
 * Constructing an {@link Container} object from container metadata.
 * @param metadata The metadata of the container in JSON.
 * @throws JSONException If fails to parse metadata.
 */
private Container(JSONObject metadata, short parentAccountId) throws JSONException {
  if (metadata == null) {
    throw new IllegalArgumentException("metadata cannot be null.");
  }
  this.parentAccountId = parentAccountId;
  short metadataVersion = (short) metadata.getInt(JSON_VERSION_KEY);
  switch (metadataVersion) {
    case JSON_VERSION_1:
      id = (short) metadata.getInt(CONTAINER_ID_KEY);
      name = metadata.getString(CONTAINER_NAME_KEY);
      status = ContainerStatus.valueOf(metadata.getString(STATUS_KEY));
      deleteTriggerTime = CONTAINER_DELETE_TRIGGER_TIME_DEFAULT_VALUE;
      description = metadata.optString(DESCRIPTION_KEY);
      encrypted = ENCRYPTED_DEFAULT_VALUE;
      previouslyEncrypted = PREVIOUSLY_ENCRYPTED_DEFAULT_VALUE;
      cacheable = !metadata.getBoolean(IS_PRIVATE_KEY);
      backupEnabled = BACKUP_ENABLED_DEFAULT_VALUE;
      mediaScanDisabled = MEDIA_SCAN_DISABLED_DEFAULT_VALUE;
      replicationPolicy = null;
      ttlRequired = TTL_REQUIRED_DEFAULT_VALUE;
      securePathRequired = SECURE_PATH_REQUIRED_DEFAULT_VALUE;
      contentTypeWhitelistForFilenamesOnDownload = CONTENT_TYPE_WHITELIST_FOR_FILENAMES_ON_DOWNLOAD_DEFAULT_VALUE;
      break;
    case JSON_VERSION_2:
      id = (short) metadata.getInt(CONTAINER_ID_KEY);
      name = metadata.getString(CONTAINER_NAME_KEY);
      status = ContainerStatus.valueOf(metadata.getString(STATUS_KEY));
      deleteTriggerTime = metadata.optLong(CONTAINER_DELETE_TRIGGER_TIME_KEY, CONTAINER_DELETE_TRIGGER_TIME_DEFAULT_VALUE);
      description = metadata.optString(DESCRIPTION_KEY);
      encrypted = metadata.optBoolean(ENCRYPTED_KEY, ENCRYPTED_DEFAULT_VALUE);
      previouslyEncrypted = metadata.optBoolean(PREVIOUSLY_ENCRYPTED_KEY, PREVIOUSLY_ENCRYPTED_DEFAULT_VALUE);
      cacheable = metadata.optBoolean(CACHEABLE_KEY, CACHEABLE_DEFAULT_VALUE);
      backupEnabled = metadata.optBoolean(BACKUP_ENABLED_KEY, BACKUP_ENABLED_DEFAULT_VALUE);
      mediaScanDisabled = metadata.optBoolean(MEDIA_SCAN_DISABLED_KEY, MEDIA_SCAN_DISABLED_DEFAULT_VALUE);
      replicationPolicy = metadata.optString(REPLICATION_POLICY_KEY, null);
      ttlRequired = metadata.optBoolean(TTL_REQUIRED_KEY, TTL_REQUIRED_DEFAULT_VALUE);
      securePathRequired = metadata.optBoolean(SECURE_PATH_REQUIRED_KEY, SECURE_PATH_REQUIRED_DEFAULT_VALUE);
      JSONArray contentTypeWhitelistForFilenamesOnDownloadJson =
          metadata.optJSONArray(CONTENT_TYPE_WHITELIST_FOR_FILENAMES_ON_DOWNLOAD);
      if (contentTypeWhitelistForFilenamesOnDownloadJson != null) {
        contentTypeWhitelistForFilenamesOnDownload = new HashSet<>();
        contentTypeWhitelistForFilenamesOnDownloadJson.forEach(
            contentType -> contentTypeWhitelistForFilenamesOnDownload.add(contentType.toString()));
      } else {
        contentTypeWhitelistForFilenamesOnDownload = CONTENT_TYPE_WHITELIST_FOR_FILENAMES_ON_DOWNLOAD_DEFAULT_VALUE;
      }
      break;
    default:
      throw new IllegalStateException("Unsupported container json version=" + metadataVersion);
  }
  checkPreconditions(name, status, encrypted, previouslyEncrypted);
}