org.json.JSONObject

Here are the examples of the java api class org.json.JSONObject taken from open source projects.

1. PLAYER#toJson()

Project: BeeFramework_Android
Source File: PLAYER.java
View license
public JSONObject toJson() throws JSONException {
    JSONObject localItemObject = new JSONObject();
    localItemObject.put("id", id);
    localItemObject.put("name", name);
    localItemObject.put("location", location);
    localItemObject.put("followers_count", followers_count);
    localItemObject.put("draftees_conut", draftees_conut);
    localItemObject.put("likes_count", likes_count);
    localItemObject.put("likes_receiced_count", likes_receiced_count);
    localItemObject.put("rebounds_count", rebounds_count);
    localItemObject.put("rebounds_received_count", rebounds_received_count);
    localItemObject.put("url", url);
    localItemObject.put("avatar_url", avatar_url);
    localItemObject.put("username", username);
    localItemObject.put("twitter_screen_name", twitter_screen_name);
    localItemObject.put("website_url", website_url);
    localItemObject.put("drafted_by_player_id", drafted_by_player_id);
    localItemObject.put("shots_count", shots_count);
    localItemObject.put("following_count", following_count);
    localItemObject.put("created_at", created_at);
    return localItemObject;
}

2. UserAccountTest#createTestAccountJSON()

View license
/**
     * Creates a test [email protected] JSONObject} with all [email protected] UserAccount} fields populated
     *
     * @return [email protected] JSONObject}
     */
private JSONObject createTestAccountJSON() throws JSONException {
    final JSONObject object = new JSONObject();
    object.put(UserAccount.AUTH_TOKEN, TEST_AUTH_TOKEN);
    object.put(UserAccount.REFRESH_TOKEN, TEST_REFRESH_TOKEN);
    object.put(UserAccount.LOGIN_SERVER, TEST_LOGIN_URL);
    object.put(UserAccount.ID_URL, TEST_IDENTITY_URL);
    object.put(UserAccount.INSTANCE_SERVER, TEST_INSTANCE_URL);
    object.put(UserAccount.ORG_ID, TEST_ORG_ID);
    object.put(UserAccount.USER_ID, TEST_USER_ID);
    object.put(UserAccount.USERNAME, TEST_USERNAME);
    object.put(UserAccount.CLIENT_ID, TEST_CLIENT_ID);
    object.put(UserAccount.ACCOUNT_NAME, TEST_ACCOUNT_NAME);
    object.put(UserAccount.COMMUNITY_ID, TEST_COMMUNITY_ID);
    object.put(UserAccount.COMMUNITY_URL, TEST_COMMUNITY_URL);
    object.put(UserAccount.FIRST_NAME, TEST_FIRST_NAME);
    object.put(UserAccount.LAST_NAME, TEST_LAST_NAME);
    object.put(UserAccount.DISPLAY_NAME, TEST_DISPLAY_NAME);
    object.put(UserAccount.EMAIL, TEST_EMAIL);
    object.put(UserAccount.PHOTO_URL, TEST_PHOTO_URL);
    object.put(UserAccount.THUMBNAIL_URL, TEST_THUMBNAIL_URL);
    return object;
}

3. SHOT#toJson()

Project: BeeFramework_Android
Source File: SHOT.java
View license
public JSONObject toJson() throws JSONException {
    JSONObject localItemObject = new JSONObject();
    JSONArray itemJSONArray = new JSONArray();
    localItemObject.put("id", id);
    localItemObject.put("title", title);
    localItemObject.put("url", url);
    localItemObject.put("short_url", short_url);
    localItemObject.put("image_url", image_url);
    localItemObject.put("image_teaser_url", image_teaser_url);
    localItemObject.put("width", width);
    localItemObject.put("height", height);
    localItemObject.put("views_count", views_count);
    localItemObject.put("likes_count", likes_count);
    localItemObject.put("comments_count", comments_count);
    localItemObject.put("rebounds_count", rebounds_count);
    localItemObject.put("rebounds_source_id", rebounds_source_id);
    localItemObject.put("created_at", created_at);
    localItemObject.put("player", this.player.toJson());
    return localItemObject;
}

4. HSDeskGear#retrieveTicketProperties()

Project: helpstack-android
Source File: HSDeskGear.java
View license
private JSONObject retrieveTicketProperties(HSUser user, String body, String message) throws JSONException {
    JSONObject messageFields = new JSONObject();
    JSONObject customerLinks = new JSONObject();
    JSONObject customerParameter = new JSONObject();
    JSONObject params = new JSONObject();
    messageFields.put("direction", "in");
    messageFields.put("from", user.getEmail());
    messageFields.put("to", to_help_email);
    messageFields.put("subject", message);
    messageFields.put("body", body);
    customerLinks.put("href", user.getApiHref());
    customerLinks.put("class", "customer");
    customerParameter.put("customer", customerLinks);
    params.put("type", "email");
    params.put("subject", message);
    params.put("_links", customerParameter);
    params.put("message", messageFields);
    return params;
}

5. NetworkQueryControllerTest#generateBasicMockResponse()

View license
// TODO(mengyan): Add testFindAsyncWithCachePolicy to verify command is added to
// ParseKeyValueCache
//endregion
private static JSONObject generateBasicMockResponse() throws JSONException {
    JSONObject objectJSON = new JSONObject();
    String createAtStr = "2015-08-09T22:15:13.460Z";
    objectJSON.put("createdAt", createAtStr);
    objectJSON.put("updatedAt", createAtStr);
    objectJSON.put("objectId", "testObjectId");
    objectJSON.put("sessionToken", "testSessionToken");
    objectJSON.put("key", "value");
    createAtStr = "2015-08-10T22:15:13.460Z";
    JSONObject objectJSONAgain = new JSONObject();
    objectJSONAgain.put("createdAt", createAtStr);
    objectJSONAgain.put("updatedAt", createAtStr);
    objectJSONAgain.put("objectId", "testObjectIdAgain");
    objectJSONAgain.put("sessionToken", "testSessionTokenAgain");
    objectJSONAgain.put("keyAgain", "valueAgain");
    JSONArray objectJSONArray = new JSONArray();
    objectJSONArray.put(objectJSON);
    objectJSONArray.put(objectJSONAgain);
    JSONObject mockResponse = new JSONObject();
    mockResponse.put("results", objectJSONArray);
    return mockResponse;
}

6. InitService#helloWorld()

Project: solo
Source File: InitService.java
View license
/**
     * Publishes the first article "Hello World" and the first comment with the specified locale.
     *
     * @throws Exception exception
     */
private void helloWorld() throws Exception {
    final JSONObject article = new JSONObject();
    article.put(Article.ARTICLE_TITLE, langPropsService.get("helloWorld.title"));
    final String content = langPropsService.get("helloWorld.content");
    article.put(Article.ARTICLE_ABSTRACT, content);
    article.put(Article.ARTICLE_CONTENT, content);
    article.put(Article.ARTICLE_TAGS_REF, "B3log,Solo");
    article.put(Article.ARTICLE_PERMALINK, "/hello-solo");
    article.put(Article.ARTICLE_IS_PUBLISHED, true);
    article.put(Article.ARTICLE_HAD_BEEN_PUBLISHED, true);
    article.put(Article.ARTICLE_SIGN_ID, "1");
    article.put(Article.ARTICLE_COMMENT_COUNT, 1);
    article.put(Article.ARTICLE_VIEW_COUNT, 0);
    final Date date = new Date();
    final JSONObject admin = userRepository.getAdmin();
    final String authorEmail = admin.optString(User.USER_EMAIL);
    article.put(Article.ARTICLE_CREATE_DATE, date);
    article.put(Article.ARTICLE_UPDATE_DATE, date);
    article.put(Article.ARTICLE_PUT_TOP, false);
    article.put(Article.ARTICLE_RANDOM_DOUBLE, Math.random());
    article.put(Article.ARTICLE_AUTHOR_EMAIL, authorEmail);
    article.put(Article.ARTICLE_COMMENTABLE, true);
    article.put(Article.ARTICLE_VIEW_PWD, "");
    article.put(Article.ARTICLE_EDITOR_TYPE, DefaultPreference.DEFAULT_EDITOR_TYPE);
    final String articleId = addHelloWorldArticle(article);
    final JSONObject comment = new JSONObject();
    comment.put(Keys.OBJECT_ID, articleId);
    comment.put(Comment.COMMENT_NAME, "88250");
    comment.put(Comment.COMMENT_EMAIL, "[email protected]");
    comment.put(Comment.COMMENT_URL, "http://88250.b3log.org");
    comment.put(Comment.COMMENT_CONTENT, langPropsService.get("helloWorld.comment.content"));
    comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, "");
    comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, "");
    comment.put(Comment.COMMENT_THUMBNAIL_URL, Thumbnails.GRAVATAR + "59a5e8209c780307dbe9c9ba728073f5??s=60&r=G");
    comment.put(Comment.COMMENT_DATE, date);
    comment.put(Comment.COMMENT_ON_ID, articleId);
    comment.put(Comment.COMMENT_ON_TYPE, Article.ARTICLE);
    final String commentId = Ids.genTimeMillisId();
    comment.put(Keys.OBJECT_ID, commentId);
    final String commentSharpURL = Comments.getCommentSharpURLForArticle(article, commentId);
    comment.put(Comment.COMMENT_SHARP_URL, commentSharpURL);
    commentRepository.add(comment);
    LOGGER.info("Hello World!");
}

7. ArticleMgmtServiceTestCase#addArticle()

View license
/**
     * Add Article.
     *
     * @throws Exception exception
     */
@Test(dependsOnMethods = "init")
public void addArticle() throws Exception {
    final ArticleMgmtService articleMgmtService = getArticleMgmtService();
    final JSONObject requestJSONObject = new JSONObject();
    final JSONObject article = new JSONObject();
    requestJSONObject.put(Article.ARTICLE, article);
    article.put(Article.ARTICLE_AUTHOR_EMAIL, "[email protected]");
    article.put(Article.ARTICLE_TITLE, "article1 title");
    article.put(Article.ARTICLE_ABSTRACT, "article1 abstract");
    article.put(Article.ARTICLE_CONTENT, "article1 content");
    article.put(Article.ARTICLE_TAGS_REF, "tag1, tag2, tag3");
    article.put(Article.ARTICLE_PERMALINK, "article1 permalink");
    article.put(Article.ARTICLE_IS_PUBLISHED, true);
    article.put(Common.POST_TO_COMMUNITY, true);
    article.put(Article.ARTICLE_SIGN_ID, "1");
    article.put(Article.ARTICLE_COMMENTABLE, true);
    article.put(Article.ARTICLE_VIEW_PWD, "");
    final String articleId = articleMgmtService.addArticle(requestJSONObject);
    Assert.assertNotNull(articleId);
}

8. PostTest#loadValidResponseBody()

Project: LiveSDK-for-Android
Source File: PostTest.java
View license
@Override
protected void loadValidResponseBody() throws JSONException {
    JSONObject calendar = new JSONObject();
    calendar.put(JsonKeys.ID, "calendar_id");
    calendar.put(JsonKeys.DESCRIPTION, JSONObject.NULL);
    calendar.put(JsonKeys.NAME, "name");
    calendar.put(JsonKeys.PERMISSIONS, "owner");
    calendar.put(JsonKeys.IS_DEFAULT, false);
    JSONObject from = new JSONObject();
    from.put(JsonKeys.ID, "from_id");
    from.put(JsonKeys.NAME, "from_name");
    calendar.put(JsonKeys.FROM, from);
    calendar.put(JsonKeys.SUBSCRIPTION_LOCATION, JSONObject.NULL);
    calendar.put(JsonKeys.CREATED_TIME, "2011-12-10T02:48:33+0000");
    calendar.put(JsonKeys.UPDATED_TIME, "2011-12-10T02:48:33+0000");
    byte[] bytes = calendar.toString().getBytes();
    this.mockEntity.setInputStream(new ByteArrayInputStream(bytes));
}

9. PutTest#loadValidResponseBody()

Project: LiveSDK-for-Android
Source File: PutTest.java
View license
@Override
protected void loadValidResponseBody() throws JSONException {
    JSONObject calendar = new JSONObject();
    calendar.put(JsonKeys.ID, "calendar_id");
    calendar.put(JsonKeys.DESCRIPTION, JSONObject.NULL);
    calendar.put(JsonKeys.NAME, "name");
    calendar.put(JsonKeys.PERMISSIONS, "owner");
    calendar.put(JsonKeys.IS_DEFAULT, false);
    JSONObject from = new JSONObject();
    from.put(JsonKeys.ID, "from_id");
    from.put(JsonKeys.NAME, "from_name");
    calendar.put(JsonKeys.FROM, from);
    calendar.put(JsonKeys.SUBSCRIPTION_LOCATION, JSONObject.NULL);
    calendar.put(JsonKeys.CREATED_TIME, "2011-12-10T02:48:33+0000");
    calendar.put(JsonKeys.UPDATED_TIME, "2011-12-10T02:48:33+0000");
    byte[] bytes = calendar.toString().getBytes();
    this.mockEntity.setInputStream(new ByteArrayInputStream(bytes));
}

10. ArticleMgmtServiceTestCase#addArticleWithoutPermalink()

View license
/**
     * Add Article without permalink.
     *
     * @throws Exception exception
     */
@Test(dependsOnMethods = "init")
public void addArticleWithoutPermalink() throws Exception {
    final ArticleMgmtService articleMgmtService = getArticleMgmtService();
    final JSONObject requestJSONObject = new JSONObject();
    final JSONObject article = new JSONObject();
    requestJSONObject.put(Article.ARTICLE, article);
    article.put(Article.ARTICLE_AUTHOR_EMAIL, "[email protected]");
    article.put(Article.ARTICLE_TITLE, "article1 title");
    article.put(Article.ARTICLE_ABSTRACT, "article1 abstract");
    article.put(Article.ARTICLE_CONTENT, "article1 content");
    article.put(Article.ARTICLE_TAGS_REF, "tag1, tag2, tag3");
    article.put(Article.ARTICLE_IS_PUBLISHED, true);
    article.put(Common.POST_TO_COMMUNITY, true);
    article.put(Article.ARTICLE_SIGN_ID, "1");
    article.put(Article.ARTICLE_COMMENTABLE, true);
    article.put(Article.ARTICLE_VIEW_PWD, "");
    final String articleId = articleMgmtService.addArticle(requestJSONObject);
    Assert.assertNotNull(articleId);
}

11. TestJsonConfiguration#createFinalJsonObject()

View license
private JSONObject createFinalJsonObject() throws Exception {
    // Construct json object for core_site
    JSONObject core_site = new JSONObject();
    core_site.put("io_file_buffer_size", 65536);
    core_site.put("hadoop_disable_shell", true);
    core_site.put("fs_hdfs_impl", "org.apache.hadoop.hdfs.DistributedAvatarFileSystem");
    // Construct json object for hdfs_site
    JSONObject hdfs_site = new JSONObject();
    hdfs_site.put("fs_ha_retrywrites", true);
    hdfs_site.put("dfs_replication", 3);
    hdfs_site.put("dfs_replication_max", 512);
    hdfs_site.put("dfs_replication_min", 1);
    // Construct the final json object consisting for core-site and hdfs-site
    JSONObject json = new JSONObject();
    json.put("core-site", core_site);
    json.put("hdfs-site", hdfs_site);
    return json;
}

12. CalendarQueryResult#toJson()

View license
public JSONObject toJson() throws JSONException {
    JSONObject json = new JSONObject();
    json.put(KEY_EXECUTED_AT, executedAt.getMillis());
    DateTimeZone zone = executedAt.getZone();
    json.put(KEY_TIME_ZONE_ID, zone.getID());
    json.put(KEY_MILLIS_OFFSET_FROM_UTC_TO_LOCAL, zone.getOffset(executedAt));
    json.put(KEY_STANDARD_MILLIS_OFFSET_FROM_UTC_TO_LOCAL, zone.getStandardOffset(executedAt.getMillis()));
    json.put(KEY_URI, uri != null ? uri.toString() : "");
    json.put(KEY_PROJECTION, arrayOfStingsToJson(projection));
    json.put(KEY_SELECTION, selection != null ? selection : "");
    json.put(KEY_SELECTION_ARGS, arrayOfStingsToJson(selectionArgs));
    json.put(KEY_SORT_ORDER, sortOrder != null ? sortOrder : "");
    JSONArray jsonArray = new JSONArray();
    for (CalendarQueryRow row : rows) {
        jsonArray.put(row.toJson());
    }
    json.put(KEY_ROWS, jsonArray);
    return json;
}

13. PageOffsets#toJSON()

Project: PageTurner
Source File: PageOffsets.java
View license
public String toJSON() throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(Fields.fontFamily.name(), this.fontFamily);
    jsonObject.put(Fields.fontSize.name(), this.fontSize);
    jsonObject.put(Fields.vMargin.name(), this.vMargin);
    jsonObject.put(Fields.hMargin.name(), this.hMargin);
    jsonObject.put(Fields.lineSpacing.name(), this.lineSpacing);
    jsonObject.put(Fields.fullScreen.name(), this.fullScreen);
    jsonObject.put(Fields.allowStyling.name(), this.allowStyling);
    jsonObject.put(Fields.algorithmVersion.name(), this.algorithmVersion);
    jsonObject.put(Fields.offsets.name(), new JSONArray(this.offsets));
    return jsonObject.toString();
}

14. PluginList#getBuildInfoJson()

Project: lumify
Source File: PluginList.java
View license
private JSONObject getBuildInfoJson(BuildInfo buildInfo) {
    JSONObject json = new JSONObject();
    json.put("date", buildInfo.getDate());
    json.put("jvmVendor", buildInfo.getJvmVendor());
    json.put("jvmVersion", buildInfo.getJvmVersion());
    json.put("mavenVersion", buildInfo.getMavenVersion());
    json.put("osArch", buildInfo.getOsArch());
    json.put("osName", buildInfo.getOsName());
    json.put("osVersion", buildInfo.getOsVersion());
    json.put("timestamp", buildInfo.getTimestamp());
    json.put("user", buildInfo.getUser());
    return json;
}

15. BrokerResponseJSON#toJson()

Project: pinot
Source File: BrokerResponseJSON.java
View license
@Override
public JSONObject toJson() throws JSONException {
    JSONObject retJsonObject = new JSONObject();
    retJsonObject.put("totalDocs", _totalDocs);
    retJsonObject.put("timeUsedMs", _timeUsedMs);
    retJsonObject.put("numDocsScanned", _numDocsScanned);
    retJsonObject.put("aggregationResults", new JSONArray(_aggregationResults));
    retJsonObject.put("selectionResults", _selectionResults);
    retJsonObject.put("segmentStatistics", new JSONArray(_segmentStatistics));
    retJsonObject.put("exceptions", new JSONArray(_exceptions));
    JSONObject traceInfo = new JSONObject();
    for (String key : _traceInfo.keySet()) {
        traceInfo.put(key, new JSONArray(_traceInfo.get(key)));
    }
    retJsonObject.put("traceInfo", traceInfo);
    return retJsonObject;
}

16. ClusterTest#addRealtimeTable()

Project: pinot
Source File: ClusterTest.java
View license
protected void addRealtimeTable(String tableName, String timeColumnName, String timeColumnType, int retentionDays, String retentionTimeUnit, String kafkaZkUrl, String kafkaTopic, String schemaName, String serverTenant, String brokerTenant, File avroFile, int realtimeSegmentFlushSize, String sortedColumn, List<String> invertedIndexColumns, String loadMode) throws Exception {
    JSONObject metadata = new JSONObject();
    metadata.put("streamType", "kafka");
    metadata.put(DataSource.STREAM_PREFIX + "." + Kafka.CONSUMER_TYPE, Kafka.ConsumerType.highLevel.toString());
    metadata.put(DataSource.STREAM_PREFIX + "." + Kafka.TOPIC_NAME, kafkaTopic);
    metadata.put(DataSource.STREAM_PREFIX + "." + Kafka.DECODER_CLASS, AvroFileSchemaKafkaAvroMessageDecoder.class.getName());
    metadata.put(DataSource.STREAM_PREFIX + "." + Kafka.ZK_BROKER_URL, kafkaZkUrl);
    metadata.put(DataSource.STREAM_PREFIX + "." + Kafka.HighLevelConsumer.ZK_CONNECTION_STRING, kafkaZkUrl);
    metadata.put(DataSource.Realtime.REALTIME_SEGMENT_FLUSH_SIZE, Integer.toString(realtimeSegmentFlushSize));
    metadata.put(DataSource.STREAM_PREFIX + "." + Kafka.KAFKA_CONSUMER_PROPS_PREFIX + "." + "auto.offset.reset", "smallest");
    JSONObject request = ControllerRequestBuilder.buildCreateRealtimeTableJSON(tableName, serverTenant, brokerTenant, timeColumnName, timeColumnType, retentionTimeUnit, Integer.toString(retentionDays), 1, "BalanceNumSegmentAssignmentStrategy", metadata, schemaName, sortedColumn, invertedIndexColumns, null);
    sendPostRequest(ControllerRequestURLBuilder.baseUrl(CONTROLLER_BASE_API_URL).forTableCreate(), request.toString());
    AvroFileSchemaKafkaAvroMessageDecoder.avroFile = avroFile;
}

17. InitService#initReplyNotificationTemplate()

Project: solo
Source File: InitService.java
View license
/**
     * Initializes reply notification template.
     *
     * @throws Exception exception
     */
private void initReplyNotificationTemplate() throws Exception {
    LOGGER.info("Initializing reply notification template");
    final JSONObject replyNotificationTemplate = new JSONObject(DefaultPreference.DEFAULT_REPLY_NOTIFICATION_TEMPLATE);
    replyNotificationTemplate.put(Keys.OBJECT_ID, "replyNotificationTemplate");
    final JSONObject subjectOpt = new JSONObject();
    subjectOpt.put(Keys.OBJECT_ID, Option.ID_C_REPLY_NOTI_TPL_SUBJECT);
    subjectOpt.put(Option.OPTION_CATEGORY, Option.CATEGORY_C_PREFERENCE);
    subjectOpt.put(Option.OPTION_VALUE, replyNotificationTemplate.optString("subject"));
    optionRepository.add(subjectOpt);
    final JSONObject bodyOpt = new JSONObject();
    bodyOpt.put(Keys.OBJECT_ID, Option.ID_C_REPLY_NOTI_TPL_BODY);
    bodyOpt.put(Option.OPTION_CATEGORY, Option.CATEGORY_C_PREFERENCE);
    bodyOpt.put(Option.OPTION_VALUE, replyNotificationTemplate.optString("body"));
    optionRepository.add(bodyOpt);
    LOGGER.info("Initialized reply notification template");
}

18. PageRepositoryImplTestCase#getMaxOrder()

View license
/**
     * Get Max Order.
     * 
     * @throws Exception exception
     */
@Test(dependsOnMethods = "add")
public void getMaxOrder() throws Exception {
    final PageRepository pageRepository = getPageRepository();
    final JSONObject page = new JSONObject();
    page.put(Page.PAGE_COMMENT_COUNT, 0);
    page.put(Page.PAGE_CONTENT, "page2 content");
    page.put(Page.PAGE_ORDER, 1);
    page.put(Page.PAGE_PERMALINK, "page2 permalink");
    page.put(Page.PAGE_TITLE, "page2 title");
    page.put(Page.PAGE_COMMENTABLE, true);
    page.put(Page.PAGE_TYPE, "page");
    page.put(Page.PAGE_OPEN_TARGET, "_self");
    page.put(Page.PAGE_EDITOR_TYPE, "");
    final Transaction transaction = pageRepository.beginTransaction();
    pageRepository.add(page);
    transaction.commit();
    final int maxOrder = pageRepository.getMaxOrder();
    Assert.assertEquals(maxOrder, 1);
}

19. PageMgmtServiceTestCase#changeOrder()

Project: solo
Source File: PageMgmtServiceTestCase.java
View license
/**
     * Change Order.
     * 
     * @throws Exception exception
     */
@Test(dependsOnMethods = "addPage")
public void changeOrder() throws Exception {
    final PageMgmtService pageMgmtService = getPageMgmtService();
    JSONObject requestJSONObject = new JSONObject();
    final JSONObject page = new JSONObject();
    requestJSONObject.put(Page.PAGE, page);
    page.put(Page.PAGE_CONTENT, "page4 content");
    page.put(Page.PAGE_PERMALINK, "page4 permalink");
    page.put(Page.PAGE_TITLE, "page4 title");
    page.put(Page.PAGE_COMMENTABLE, true);
    page.put(Page.PAGE_TYPE, "page");
    page.put(Page.PAGE_OPEN_TARGET, "_self");
    final String pageId = pageMgmtService.addPage(requestJSONObject);
    Assert.assertNotNull(pageId);
    final int oldOrder = page.getInt(Page.PAGE_ORDER);
    pageMgmtService.changeOrder(pageId, "up");
    final JSONObject result = getPageQueryService().getPage(pageId);
    Assert.assertNotNull(result);
    Assert.assertTrue(oldOrder > result.getJSONObject(Page.PAGE).getInt(Page.PAGE_ORDER));
}

20. UnionPayCardBuilder#buildEnrollment()

View license
public JSONObject buildEnrollment() throws JSONException {
    JSONObject unionPayEnrollment = new JSONObject();
    unionPayEnrollment.put(NUMBER_KEY, mCardnumber);
    unionPayEnrollment.put(EXPIRATION_MONTH_KEY, mExpirationMonth);
    unionPayEnrollment.put(EXPIRATION_YEAR_KEY, mExpirationYear);
    unionPayEnrollment.put(EXPIRATION_DATE_KEY, mExpirationDate);
    unionPayEnrollment.put(MOBILE_COUNTRY_CODE_KEY, mMobileCountryCode);
    unionPayEnrollment.put(MOBILE_PHONE_NUMBER_KEY, mMobilePhoneNumber);
    JSONObject payload = new JSONObject();
    payload.put(UNIONPAY_ENROLLMENT_KEY, unionPayEnrollment);
    return payload;
}

21. ExtensionData#serialize()

Project: dashclock
Source File: ExtensionData.java
View license
/**
     * Serializes the contents of this object to JSON.
     */
public JSONObject serialize() throws JSONException {
    JSONObject data = new JSONObject();
    data.put(KEY_VISIBLE, mVisible);
    data.put(KEY_ICON, mIcon);
    data.put(KEY_ICON_URI, (mIconUri == null ? null : mIconUri.toString()));
    data.put(KEY_STATUS, mStatus);
    data.put(KEY_EXPANDED_TITLE, mExpandedTitle);
    data.put(KEY_EXPANDED_BODY, mExpandedBody);
    data.put(KEY_CLICK_INTENT, (mClickIntent == null) ? null : mClickIntent.toUri(0));
    data.put(KEY_CONTENT_DESCRIPTION, mContentDescription);
    return data;
}

22. TaskTracker#toJson()

Project: gcm
Source File: TaskTracker.java
View license
public JSONObject toJson() throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(TAG, tag);
    jsonObject.put(WINDOW_START_ELAPSED_SECS, windowStartElapsedSecs);
    jsonObject.put(WINDOW_STOP_ELAPSED_SECS, windowStopElapsedSecs);
    jsonObject.put(PERIOD, period);
    jsonObject.put(FLEX, flex);
    jsonObject.put(CREATED_AT_ELAPSED_SECS, createdAtElapsedSecs);
    jsonObject.put(CANCELLED, cancelled);
    jsonObject.put(EXECUTED, executed);
    return jsonObject;
}

23. SystemNotificationRepository#toJSONObject()

View license
public static JSONObject toJSONObject(SystemNotification notification) {
    JSONObject json = new JSONObject();
    json.put("id", notification.getId());
    json.put("type", "system");
    json.put("severity", notification.getSeverity().toString());
    json.put("title", notification.getTitle());
    json.put("message", notification.getMessage());
    if (notification.getActionEvent() != null) {
        JSONObject action = new JSONObject();
        action.put("event", notification.getActionEvent());
        action.putOpt("data", notification.getActionPayload());
        json.put("action", action);
    }
    json.put("startDate", notification.getStartDate().getTime());
    json.put("endDate", notification.getEndDate() == null ? null : notification.getEndDate().getTime());
    json.put("hash", hash(json.toString()));
    return json;
}

24. PluginList#handle()

Project: lumify
Source File: PluginList.java
View license
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, HandlerChain chain) throws Exception {
    JSONObject json = new JSONObject();
    json.put("loadedLibFiles", getLoadedLibFilesJson());
    json.put("graphPropertyWorkers", getGraphPropertyWorkersJson());
    json.put("postMimeTypeWorkers", getPostMimeTypeWorkersJson());
    json.put("userListeners", getUserListenersJson());
    json.put("libLoaders", getLibLoadersJson());
    json.put("fileImportSupportingFileHandlers", getFileImportSupportingFileHandlersJson());
    json.put("termMentionFilters", getTermMentionFiltersJson());
    json.put("webAppPlugins", getWebAppPluginsJson());
    respondWithJson(response, json);
}

25. PluginList#getProjectInfoJson()

Project: lumify
Source File: PluginList.java
View license
private JSONObject getProjectInfoJson(ProjectInfo projectInfo) {
    JSONObject json = new JSONObject();
    json.put("name", projectInfo.getName());
    json.put("artifactId", projectInfo.getArtifactId());
    json.put("buildInfo", getBuildInfoJson(projectInfo.getBuildInfo()));
    json.put("coordinates", projectInfo.getCoordinates());
    json.put("groupId", projectInfo.getGroupId());
    json.put("scmRevision", projectInfo.getScmRevision());
    json.put("source", projectInfo.getSource());
    json.put("version", projectInfo.getVersion());
    return json;
}

26. Artwork#toJson()

Project: muzei
Source File: Artwork.java
View license
/**
     * Serializes this artwork object to a [email protected] JSONObject} representation.
     */
public JSONObject toJson() throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(KEY_COMPONENT_NAME, (mComponentName != null) ? mComponentName.flattenToShortString() : null);
    jsonObject.put(KEY_IMAGE_URI, (mImageUri != null) ? mImageUri.toString() : null);
    jsonObject.put(KEY_TITLE, mTitle);
    jsonObject.put(KEY_BYLINE, mByline);
    jsonObject.put(KEY_ATTRIBUTION, mAttribution);
    jsonObject.put(KEY_TOKEN, mToken);
    jsonObject.put(KEY_VIEW_INTENT, (mViewIntent != null) ? mViewIntent.toUri(Intent.URI_INTENT_SCHEME) : null);
    jsonObject.put(KEY_META_FONT, mMetaFont);
    return jsonObject;
}

27. ControllerRequestBuilder#buildCreateRealtimeTableJSON()

Project: pinot
Source File: ControllerRequestBuilder.java
View license
public static JSONObject buildCreateRealtimeTableJSON(String tableName, String serverTenant, String brokerTenant, String timeColumnName, String timeType, String retentionTimeUnit, String retentionTimeValue, int numReplicas, String segmentAssignmentStrategy, JSONObject streamConfigs, String schemaName, String sortedColumn, List<String> invertedIndexColumns, String loadMode) throws JSONException {
    JSONObject creationRequest = new JSONObject();
    creationRequest.put("tableName", tableName);
    JSONObject segmentsConfig = new JSONObject();
    segmentsConfig.put("retentionTimeUnit", retentionTimeUnit);
    segmentsConfig.put("retentionTimeValue", retentionTimeValue);
    segmentsConfig.put("segmentPushFrequency", "daily");
    segmentsConfig.put("segmentPushType", "APPEND");
    segmentsConfig.put("replication", numReplicas);
    segmentsConfig.put("schemaName", schemaName);
    segmentsConfig.put("timeColumnName", timeColumnName);
    segmentsConfig.put("timeType", timeType);
    segmentsConfig.put("segmentAssignmentStrategy", segmentAssignmentStrategy);
    creationRequest.put("segmentsConfig", segmentsConfig);
    JSONObject tableIndexConfig = new JSONObject();
    tableIndexConfig.put("invertedIndexColumns", invertedIndexColumns);
    if (loadMode != null && loadMode.equals("MMAP")) {
        tableIndexConfig.put("loadMode", "MMAP");
    } else {
        tableIndexConfig.put("loadMode", "HEAP");
    }
    tableIndexConfig.put("lazyLoad", "false");
    tableIndexConfig.put("streamConfigs", streamConfigs);
    JSONArray sortedColumns = new JSONArray();
    if (sortedColumn != null) {
        sortedColumns.put(sortedColumn);
    }
    tableIndexConfig.put("sortedColumn", sortedColumns);
    creationRequest.put("tableIndexConfig", tableIndexConfig);
    JSONObject tenants = new JSONObject();
    tenants.put("broker", brokerTenant);
    tenants.put("server", serverTenant);
    creationRequest.put("tenants", tenants);
    creationRequest.put("tableType", "REALTIME");
    JSONObject metadata = new JSONObject();
    JSONObject customConfigs = new JSONObject();
    customConfigs.put("d2Name", "xlntBetaPinot");
    metadata.put("customConfigs", customConfigs);
    creationRequest.put("metadata", metadata);
    return creationRequest;
}

28. JSONFormatter#asJSON()

Project: redpen
Source File: JSONFormatter.java
View license
/**
     * Render a start and end coordinates as a 'position'
     *
     * @param startLine   the line this position starts
     * @param startOffset the offset within startLine the position starts
     * @param endLine     the line offset denoting the end position
     * @param endOffset   the offset within endLine the position ends
     * @return a JSON representation of this 'position'
     * @throws JSONException when failed to construct JSONObject
     */
protected JSONObject asJSON(int startLine, int startOffset, int endLine, int endOffset) throws JSONException {
    JSONObject position = new JSONObject();
    JSONObject offset = new JSONObject();
    offset.put("line", startLine);
    offset.put("offset", startOffset);
    position.put("start", offset);
    offset = new JSONObject();
    offset.put("line", endLine);
    offset.put("offset", endOffset);
    position.put("end", offset);
    return position;
}

29. BootConfig#asJSON()

View license
/**
     * @return boot config as JSONObject
	 * @throws JSONException
	 */
public JSONObject asJSON() throws JSONException {
    JSONObject config = new JSONObject();
    config.put(REMOTE_ACCESS_CONSUMER_KEY, remoteAccessConsumerKey);
    config.put(OAUTH_REDIRECT_URI, oauthRedirectURI);
    config.put(OAUTH_SCOPES, new JSONArray(Arrays.asList(oauthScopes)));
    config.put(IS_LOCAL, isLocal);
    config.put(START_PAGE, startPage);
    config.put(ERROR_PAGE, errorPage);
    if (pushNotificationClientId != null)
        config.put(PUSH_NOTIFICATION_CLIENT_ID, pushNotificationClientId);
    config.put(SHOULD_AUTHENTICATE, shouldAuthenticate);
    config.put(ATTEMPT_OFFLINE_LOAD, attemptOfflineLoad);
    return config;
}

30. SyncState#createSyncDown()

View license
/**
	 * Create sync state in database for a sync down and return corresponding SyncState
	 * @return
	 * @throws JSONException 
	 */
public static SyncState createSyncDown(SmartStore store, SyncDownTarget target, SyncOptions options, String soupName) throws JSONException {
    JSONObject sync = new JSONObject();
    sync.put(SYNC_TYPE, Type.syncDown);
    sync.put(SYNC_TARGET, target.asJSON());
    sync.put(SYNC_OPTIONS, options.asJSON());
    sync.put(SYNC_SOUP_NAME, soupName);
    sync.put(SYNC_STATUS, Status.NEW.name());
    sync.put(SYNC_PROGRESS, 0);
    sync.put(SYNC_TOTAL_SIZE, -1);
    sync.put(SYNC_MAX_TIME_STAMP, -1);
    sync = store.upsert(SYNCS_SOUP, sync);
    return SyncState.fromJSON(sync);
}

31. SyncState#createSyncUp()

View license
/**
	 * Create sync state in database for a sync up and return corresponding SyncState
	 * @return
	 * @throws JSONException 
	 */
public static SyncState createSyncUp(SmartStore store, SyncUpTarget target, SyncOptions options, String soupName) throws JSONException {
    JSONObject sync = new JSONObject();
    sync.put(SYNC_TYPE, Type.syncUp);
    sync.put(SYNC_TARGET, target.asJSON());
    sync.put(SYNC_SOUP_NAME, soupName);
    sync.put(SYNC_OPTIONS, options.asJSON());
    sync.put(SYNC_STATUS, Status.NEW.name());
    sync.put(SYNC_PROGRESS, 0);
    sync.put(SYNC_TOTAL_SIZE, -1);
    sync.put(SYNC_MAX_TIME_STAMP, -1);
    sync = store.upsert(SYNCS_SOUP, sync);
    return SyncState.fromJSON(sync);
}

32. AbstractSmartStoreTest#testRetrieve()

View license
/**
	 * Testing retrieve: create multiple soup elements and retrieves them back
	 * @throws JSONException 
	 */
public void testRetrieve() throws JSONException {
    JSONObject soupElt1 = new JSONObject("{'key':'ka1', 'value':'va1'}");
    JSONObject soupElt2 = new JSONObject("{'key':'ka2', 'value':'va2'}");
    JSONObject soupElt3 = new JSONObject("{'key':'ka3', 'value':'va3'}");
    JSONObject soupElt1Created = store.create(TEST_SOUP, soupElt1);
    JSONObject soupElt2Created = store.create(TEST_SOUP, soupElt2);
    JSONObject soupElt3Created = store.create(TEST_SOUP, soupElt3);
    JSONObject soupElt1Retrieved = store.retrieve(TEST_SOUP, idOf(soupElt1Created)).getJSONObject(0);
    JSONObject soupElt2Retrieved = store.retrieve(TEST_SOUP, idOf(soupElt2Created)).getJSONObject(0);
    JSONObject soupElt3Retrieved = store.retrieve(TEST_SOUP, idOf(soupElt3Created)).getJSONObject(0);
    JSONTestHelper.assertSameJSON("Retrieve mismatch", soupElt1Created, soupElt1Retrieved);
    JSONTestHelper.assertSameJSON("Retrieve mismatch", soupElt2Created, soupElt2Retrieved);
    JSONTestHelper.assertSameJSON("Retrieve mismatch", soupElt3Created, soupElt3Retrieved);
}

33. InitService#initAdmin()

Project: solo
Source File: InitService.java
View license
/**
     * Initializes administrator with the specified request json object, and then logins it.
     *
     * @param requestJSONObject the specified request json object, for example,      <pre>
     * {
     *     "userName": "",
     *     "userEmail": "",
     *     "userPassowrd": "" // Unhashed
     * }
     * </pre>
     *
     * @throws Exception exception
     */
private void initAdmin(final JSONObject requestJSONObject) throws Exception {
    LOGGER.info("Initializing admin....");
    final JSONObject admin = new JSONObject();
    admin.put(User.USER_NAME, requestJSONObject.getString(User.USER_NAME));
    admin.put(User.USER_EMAIL, requestJSONObject.getString(User.USER_EMAIL));
    admin.put(User.USER_URL, Latkes.getServePath());
    admin.put(User.USER_ROLE, Role.ADMIN_ROLE);
    admin.put(User.USER_PASSWORD, MD5.hash(requestJSONObject.getString(User.USER_PASSWORD)));
    admin.put(UserExt.USER_ARTICLE_COUNT, 0);
    admin.put(UserExt.USER_PUBLISHED_ARTICLE_COUNT, 0);
    admin.put(UserExt.USER_AVATAR, Thumbnails.getGravatarURL(requestJSONObject.getString(User.USER_EMAIL), "128"));
    userRepository.add(admin);
    LOGGER.info("Initialized admin");
}

34. CommentMgmtServiceTestCase#addPage()

View license
/**
     * Adds a page.
     * 
     * @throws Exception exception
     */
private void addPage() throws Exception {
    final PageMgmtService pageMgmtService = getPageMgmtService();
    final JSONObject requestJSONObject = new JSONObject();
    final JSONObject page = new JSONObject();
    requestJSONObject.put(Page.PAGE, page);
    page.put(Page.PAGE_CONTENT, "page1 content");
    page.put(Page.PAGE_PERMALINK, "page1 permalink");
    page.put(Page.PAGE_TITLE, "page1 title");
    page.put(Page.PAGE_COMMENTABLE, true);
    page.put(Page.PAGE_TYPE, "page");
    page.put(Page.PAGE_OPEN_TARGET, "_self");
    final String pageId = pageMgmtService.addPage(requestJSONObject);
    Assert.assertNotNull(pageId);
}

35. OptionMgmtServiceTestCase#update()

Project: solo
Source File: OptionMgmtServiceTestCase.java
View license
/**
     * Update.
     * 
     * @throws Exception exception
     */
@Test
public void update() throws Exception {
    final OptionMgmtService optionMgmtService = getOptionMgmtService();
    JSONObject option = new JSONObject();
    option.put(Keys.OBJECT_ID, Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME);
    option.put(Option.OPTION_CATEGORY, Option.CATEGORY_C_BROADCAST);
    option.put(Option.OPTION_VALUE, 0L);
    // Add
    final String id = optionMgmtService.addOrUpdateOption(option);
    System.out.println(id);
    Assert.assertNotNull(id);
    option = new JSONObject();
    option.put(Keys.OBJECT_ID, Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME);
    option.put(Option.OPTION_CATEGORY, Option.CATEGORY_C_BROADCAST);
    option.put(Option.OPTION_VALUE, 1L);
    // Update
    optionMgmtService.addOrUpdateOption(option);
    final JSONObject opt = getOptionQueryService().getOptionById(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME);
    Assert.assertEquals(opt.getInt(Option.OPTION_VALUE), 1L);
}

36. PageMgmtServiceTestCase#addPage()

Project: solo
Source File: PageMgmtServiceTestCase.java
View license
/**
     * Add Page.
     * 
     * @throws Exception exception
     */
@Test(dependsOnMethods = "init")
public void addPage() throws Exception {
    final PageMgmtService pageMgmtService = getPageMgmtService();
    final JSONObject requestJSONObject = new JSONObject();
    final JSONObject page = new JSONObject();
    requestJSONObject.put(Page.PAGE, page);
    page.put(Page.PAGE_CONTENT, "page1 content");
    page.put(Page.PAGE_PERMALINK, "page1 permalink");
    page.put(Page.PAGE_TITLE, "page1 title");
    page.put(Page.PAGE_COMMENTABLE, true);
    page.put(Page.PAGE_TYPE, "page");
    page.put(Page.PAGE_OPEN_TARGET, "_self");
    final String pageId = pageMgmtService.addPage(requestJSONObject);
    Assert.assertNotNull(pageId);
}

37. PageQueryServiceTestCase#addPage()

Project: solo
Source File: PageQueryServiceTestCase.java
View license
/**
     * Add Page.
     * 
     * @throws Exception exception
     */
@Test(dependsOnMethods = "init")
public void addPage() throws Exception {
    final PageMgmtService pageMgmtService = getPageMgmtService();
    final JSONObject requestJSONObject = new JSONObject();
    final JSONObject page = new JSONObject();
    requestJSONObject.put(Page.PAGE, page);
    page.put(Page.PAGE_CONTENT, "page1 content");
    page.put(Page.PAGE_PERMALINK, "page1 permalink");
    page.put(Page.PAGE_TITLE, "page1 title");
    page.put(Page.PAGE_COMMENTABLE, true);
    page.put(Page.PAGE_TYPE, "page");
    page.put(Page.PAGE_OPEN_TARGET, "_self");
    final String pageId = pageMgmtService.addPage(requestJSONObject);
    Assert.assertNotNull(pageId);
}

38. AlignmentSVGVisualizationUpdate#getNormalLayoutNodeJsonObject()

View license
private JSONObject getNormalLayoutNodeJsonObject(String label, String id, String nodeType, double height, boolean isForcedByUser, JSONArray hNodeIdsCoveredByVertex, String hNodeId, String nodeDomain, boolean isUri) throws JSONException {
    JSONObject nodeObj = new JSONObject();
    nodeObj.put(JsonKeys.label.name(), label);
    nodeObj.put(JsonKeys.id.name(), id);
    nodeObj.put(JsonKeys.nodeType.name(), nodeType);
    nodeObj.put(JsonKeys.height.name(), height);
    nodeObj.put(JsonKeys.isForcedByUser.name(), isForcedByUser);
    nodeObj.put(JsonKeys.hNodesCovered.name(), hNodeIdsCoveredByVertex);
    if (!hNodeId.equals(""))
        nodeObj.put(JsonKeys.hNodeId.name(), hNodeId);
    nodeObj.put(JsonKeys.nodeDomain.name(), nodeDomain);
    nodeObj.put(JsonKeys.isUri.name(), isUri);
    return nodeObj;
}

39. USER#toJson()

Project: BeeFramework_Android
Source File: USER.java
View license
public JSONObject toJson() throws JSONException {
    JSONObject localItemObject = new JSONObject();
    JSONArray itemJSONArray = new JSONArray();
    localItemObject.put("location", location);
    localItemObject.put("remark", remark);
    localItemObject.put("verified_reason", verified_reason);
    localItemObject.put("statuses_count", statuses_count);
    localItemObject.put("city", city);
    localItemObject.put("id", id);
    localItemObject.put("following", following);
    localItemObject.put("favourites_count", favourites_count);
    localItemObject.put("description", description);
    localItemObject.put("verified", verified);
    localItemObject.put("name", name);
    localItemObject.put("domain", domain);
    localItemObject.put("province", province);
    localItemObject.put("gender", gender);
    localItemObject.put("created_at", created_at);
    localItemObject.put("followers_count", followers_count);
    localItemObject.put("online_status", online_status);
    localItemObject.put("bi_followers_count", bi_followers_count);
    localItemObject.put("geo_enabled", geo_enabled);
    localItemObject.put("allow_all_comment", allow_all_comment);
    localItemObject.put("allow_all_act_msg", allow_all_act_msg);
    localItemObject.put("url", url);
    localItemObject.put("avatar_large", avatar_large);
    localItemObject.put("friends_count", friends_count);
    localItemObject.put("screen_name", screen_name);
    localItemObject.put("profile_image_url", profile_image_url);
    localItemObject.put("follow_me", follow_me);
    return localItemObject;
}

40. BaseCardBuilder#build()

View license
@Override
protected void build(JSONObject json, JSONObject paymentMethodNonceJson) throws JSONException {
    paymentMethodNonceJson.put(NUMBER_KEY, mCardnumber);
    paymentMethodNonceJson.put(CVV_KEY, mCvv);
    paymentMethodNonceJson.put(EXPIRATION_MONTH_KEY, mExpirationMonth);
    paymentMethodNonceJson.put(EXPIRATION_YEAR_KEY, mExpirationYear);
    paymentMethodNonceJson.put(EXPIRATION_DATE_KEY, mExpirationDate);
    paymentMethodNonceJson.put(CARDHOLDER_NAME_KEY, mCardholderName);
    JSONObject billingAddressJson = new JSONObject();
    billingAddressJson.put(FIRST_NAME_KEY, mFirstName);
    billingAddressJson.put(LAST_NAME_KEY, mLastName);
    billingAddressJson.put(COUNTRY_NAME_KEY, mCountryName);
    billingAddressJson.put(LOCALITY_KEY, mLocality);
    billingAddressJson.put(POSTAL_CODE_KEY, mPostalCode);
    billingAddressJson.put(REGION_KEY, mRegion);
    billingAddressJson.put(STREET_ADDRESS_KEY, mStreetAddress);
    if (billingAddressJson.length() > 0) {
        paymentMethodNonceJson.put(BILLING_ADDRESS_KEY, billingAddressJson);
    }
    json.put(CREDIT_CARD_KEY, paymentMethodNonceJson);
}

41. PersonServiceTest#updatePerson()

View license
private JSONObject updatePerson(String userName, String title, String firstName, String lastName, String organisation, String jobTitle, String email, String bio, String avatarUrl, int expectedStatus) throws Exception {
    // switch to admin user to create a person
    String currentUser = this.authenticationComponent.getCurrentUserName();
    String adminUser = this.authenticationComponent.getSystemUserName();
    this.authenticationComponent.setCurrentUser(adminUser);
    JSONObject person = new JSONObject();
    person.put("userName", userName);
    person.put("title", title);
    person.put("firstName", firstName);
    person.put("lastName", lastName);
    person.put("organisation", organisation);
    person.put("jobtitle", jobTitle);
    person.put("email", email);
    Response response = sendRequest(new PutRequest(URL_PEOPLE + "/" + userName, person.toString(), "application/json"), expectedStatus);
    // switch back to non-admin user
    this.authenticationComponent.setCurrentUser(currentUser);
    return new JSONObject(response.getContentAsString());
}

42. RuleServiceTest#buildTestRule()

View license
private JSONObject buildTestRule(String title) throws JSONException {
    JSONObject result = new JSONObject();
    result.put("title", title);
    result.put("description", "this is description for test_rule");
    JSONArray ruleType = new JSONArray();
    ruleType.put("outbound");
    result.put("ruleType", ruleType);
    result.put("applyToChildren", true);
    result.put("executeAsynchronously", false);
    result.put("disabled", false);
    result.put("action", buildTestAction("composite-action", true, true));
    return result;
}

43. ActivityFeedEntity#getJSONString()

View license
public String getJSONString() throws JSONException {
    JSONObject jo = new JSONObject();
    jo.put(KEY_ACTIVITY_FEED_ID, id);
    jo.put(KEY_ACTIVITY_FEED_POST_USERID, postUserId);
    if (postUserAvatarNodeRef != null) {
        jo.put(KEY_ACTIVITY_FEED_POST_USER_AVATAR_NODE, postUserAvatarNodeRef.toString());
    }
    jo.put(KEY_ACTIVITY_FEED_POST_DATE, ISO8601DateFormat.format(postDate));
    // eg. site feed
    if (getFeedUserId() != null) {
        jo.put(KEY_ACTIVITY_FEED_USERID, getFeedUserId());
    }
    jo.put(KEY_ACTIVITY_FEED_SITE, siteNetwork);
    jo.put(KEY_ACTIVITY_FEED_TYPE, getActivityType());
    jo.put(KEY_ACTIVITY_FEED_SUMMARY, getActivitySummary());
    return jo.toString();
}

44. DeviceInfoTests#testGetMetrics()

View license
public void testGetMetrics() throws UnsupportedEncodingException, JSONException {
    final JSONObject json = new JSONObject();
    json.put("_device", DeviceInfo.getDevice());
    json.put("_os", DeviceInfo.getOS());
    json.put("_os_version", DeviceInfo.getOSVersion());
    if (!"".equals(DeviceInfo.getCarrier(getContext()))) {
        // ensure tests pass on non-cellular devices
        json.put("_carrier", DeviceInfo.getCarrier(getContext()));
    }
    json.put("_resolution", DeviceInfo.getResolution(getContext()));
    json.put("_density", DeviceInfo.getDensity(getContext()));
    json.put("_locale", DeviceInfo.getLocale());
    json.put("_app_version", DeviceInfo.getAppVersion(getContext()));
    final String expected = URLEncoder.encode(json.toString(), "UTF-8");
    assertNotNull(expected);
    assertEquals(expected, DeviceInfo.getMetrics(getContext()));
}

45. Cumulio#associate()

Project: cumul.io-sdk-java
Source File: Cumulio.java
View license
public JSONObject associate(String resource, String id, String associationRole, String associationId, JSONObject properties) throws IOException {
    JSONObject association = new JSONObject();
    association.put("role", associationRole);
    association.put("id", associationId);
    JSONObject query = new JSONObject();
    query.put("action", "associate");
    query.put("id", id);
    query.put("resource", association);
    query.put("properties", properties);
    return _emit(resource, "LINK", query);
}

46. Sender#toJson()

Project: gcm
Source File: Sender.java
View license
public JSONObject toJson() throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(NAME, name);
    jsonObject.put(SENDER_ID, senderId);
    jsonObject.put(API_KEYS, new JSONArray(apiKeys));
    JSONArray jsonAppTokens = new JSONArray();
    for (Token token : appTokens.values()) {
        jsonAppTokens.put(token.toJson());
    }
    jsonObject.put(APP_TOKENS, jsonAppTokens);
    jsonObject.put(OTHER_TOKENS, new JSONObject(otherTokens));
    jsonObject.put(TOPICS, new JSONObject(topics));
    JSONArray jsonGroups = new JSONArray();
    for (DeviceGroup deviceGroup : groups.values()) {
        jsonGroups.put(deviceGroup.toJson());
    }
    jsonObject.put(GROUPS, jsonGroups);
    return jsonObject;
}

47. WorkQueueRepository#broadcastLongRunningProcessChange()

Project: lumify
Source File: WorkQueueRepository.java
View license
public void broadcastLongRunningProcessChange(JSONObject longRunningProcessQueueItem) {
    String userId = longRunningProcessQueueItem.optString("userId");
    checkNotNull(userId, "userId cannot be null");
    JSONObject json = new JSONObject();
    json.put("type", "longRunningProcessChange");
    JSONObject permissions = new JSONObject();
    JSONArray users = new JSONArray();
    users.put(userId);
    permissions.put("users", users);
    json.put("permissions", permissions);
    JSONObject dataJson = new JSONObject(longRunningProcessQueueItem.toString());
    /// because results can get quite large we don't want this going on in a web socket message
    if (dataJson.has("results")) {
        dataJson.remove("results");
    }
    json.put("data", dataJson);
    broadcastJson(json);
}

48. WorkQueueRepository#pushUserNotification()

Project: lumify
Source File: WorkQueueRepository.java
View license
public void pushUserNotification(UserNotification notification) {
    JSONObject json = new JSONObject();
    json.put("type", "notification");
    JSONObject permissions = new JSONObject();
    JSONArray users = new JSONArray();
    users.put(notification.getUserId());
    permissions.put("users", users);
    json.put("permissions", permissions);
    JSONObject data = new JSONObject();
    json.put("data", data);
    data.put("notification", UserNotificationRepository.toJSONObject(notification));
    broadcastJson(json);
}

49. Api#buildStatData()

Project: OpenMemories-AppStore
Source File: Api.java
View license
public static JSONObject buildStatData(PackageManager pm) throws JSONException {
    JSONObject device = new JSONObject();
    device.put("name", ScalarProperties.getString(ScalarProperties.PROP_MODEL_NAME));
    device.put("productcode", ScalarProperties.getString(ScalarProperties.PROP_MODEL_CODE));
    device.put("deviceid", ScalarProperties.getString(ScalarProperties.PROP_MODEL_SERIAL_CODE));
    device.put("fwversion", ScalarProperties.getFirmwareVersion());
    JSONArray apps = new JSONArray();
    for (PackageInfo info : pm.getInstalledPackages(0)) {
        JSONObject app = new JSONObject();
        app.put("name", info.packageName);
        app.put("version", info.versionName);
        apps.put(app);
    }
    JSONObject stats = new JSONObject();
    stats.put("deviceinfo", device);
    stats.put("applications", apps);
    return stats;
}

50. SwiftToken#keystoneRequest()

Project: opensearchserver
Source File: SwiftToken.java
View license
private DownloadItem keystoneRequest(HttpDownloader httpDownloader, String authUrl, String username, String tenantName, String password) throws JSONException, URISyntaxException, ClientProtocolException, UnsupportedEncodingException, IOException, IllegalStateException {
    JSONObject jsonPasswordCredentials = new JSONObject();
    jsonPasswordCredentials.put("username", username);
    jsonPasswordCredentials.put("password", password);
    JSONObject jsonAuth = new JSONObject();
    jsonAuth.put("passwordCredentials", jsonPasswordCredentials);
    jsonAuth.put("tenantName", tenantName);
    JSONObject json = new JSONObject();
    json.put("auth", jsonAuth);
    URI uri = new URI(authUrl + "/tokens");
    List<HeaderItem> headers = new ArrayList<HeaderItem>(1);
    headers.add(new HeaderItem("Accept", "application/json"));
    return httpDownloader.post(uri, null, headers, null, new StringEntity(json.toString(), ContentType.APPLICATION_JSON));
}

51. ControllerRequestBuilder#buildCreateOfflineTableJSON()

Project: pinot
Source File: ControllerRequestBuilder.java
View license
public static JSONObject buildCreateOfflineTableJSON(String tableName, String serverTenant, String brokerTenant, String timeColumnName, String timeType, String retentionTimeUnit, String retentionTimeValue, int numReplicas, String segmentAssignmentStrategy, List<String> invertedIndexColumns, String loadMode) throws JSONException {
    JSONObject creationRequest = new JSONObject();
    creationRequest.put("tableName", tableName);
    JSONObject segmentsConfig = new JSONObject();
    segmentsConfig.put("retentionTimeUnit", retentionTimeUnit);
    segmentsConfig.put("retentionTimeValue", retentionTimeValue);
    segmentsConfig.put("segmentPushFrequency", "daily");
    segmentsConfig.put("segmentPushType", "APPEND");
    segmentsConfig.put("replication", numReplicas);
    segmentsConfig.put("schemaName", "baseball");
    segmentsConfig.put("timeColumnName", timeColumnName);
    segmentsConfig.put("timeType", timeType);
    segmentsConfig.put("segmentAssignmentStrategy", segmentAssignmentStrategy);
    creationRequest.put("segmentsConfig", segmentsConfig);
    JSONObject tableIndexConfig = new JSONObject();
    tableIndexConfig.put("invertedIndexColumns", invertedIndexColumns);
    if (loadMode != null && loadMode.equals("MMAP")) {
        tableIndexConfig.put("loadMode", "MMAP");
    } else {
        tableIndexConfig.put("loadMode", "HEAP");
    }
    tableIndexConfig.put("lazyLoad", "false");
    creationRequest.put("tableIndexConfig", tableIndexConfig);
    JSONObject tenants = new JSONObject();
    tenants.put("broker", brokerTenant);
    tenants.put("server", serverTenant);
    creationRequest.put("tenants", tenants);
    creationRequest.put("tableType", "OFFLINE");
    JSONObject metadata = new JSONObject();
    JSONObject customConfigs = new JSONObject();
    customConfigs.put("d2Name", "xlntBetaPinot");
    customConfigs.put("messageBasedRefresh", "true");
    metadata.put("customConfigs", customConfigs);
    creationRequest.put("metadata", metadata);
    return creationRequest;
}

52. TimeBoundaryServiceTest#addingTableToPropertyStore()

Project: pinot
Source File: TimeBoundaryServiceTest.java
View license
private void addingTableToPropertyStore(String tableName) throws Exception {
    JSONObject offlineTableConfigJson = new JSONObject();
    offlineTableConfigJson.put("tableName", tableName);
    JSONObject segmentsConfig = new JSONObject();
    segmentsConfig.put("retentionTimeUnit", "DAYS");
    segmentsConfig.put("retentionTimeValue", -1);
    segmentsConfig.put("segmentPushFrequency", "daily");
    segmentsConfig.put("segmentPushType", "APPEND");
    segmentsConfig.put("replication", 1);
    segmentsConfig.put("schemaName", "tableSchema");
    segmentsConfig.put("timeColumnName", "timestamp");
    segmentsConfig.put("timeType", "daysSinceEpoch");
    segmentsConfig.put("segmentAssignmentStrategy", "");
    offlineTableConfigJson.put("segmentsConfig", segmentsConfig);
    JSONObject tableIndexConfig = new JSONObject();
    JSONArray invertedIndexColumns = new JSONArray();
    invertedIndexColumns.put("column1");
    invertedIndexColumns.put("column2");
    tableIndexConfig.put("invertedIndexColumns", invertedIndexColumns);
    tableIndexConfig.put("loadMode", "HEAP");
    tableIndexConfig.put("lazyLoad", "false");
    offlineTableConfigJson.put("tableIndexConfig", tableIndexConfig);
    JSONObject tenants = new JSONObject();
    tenants.put("broker", "brokerTenant");
    tenants.put("server", "serverTenant");
    offlineTableConfigJson.put("tenants", tenants);
    offlineTableConfigJson.put("tableType", "OFFLINE");
    JSONObject metadata = new JSONObject();
    JSONObject customConfigs = new JSONObject();
    customConfigs.put("d2Name", "xlntBetaPinot");
    metadata.put("customConfigs", customConfigs);
    offlineTableConfigJson.put("metadata", metadata);
    AbstractTableConfig offlineTableConfig = AbstractTableConfig.init(offlineTableConfigJson.toString());
    String offlineTableName = TableNameBuilder.OFFLINE_TABLE_NAME_BUILDER.forTable(tableName);
    ZKMetadataProvider.setOfflineTableConfig(_propertyStore, offlineTableName, AbstractTableConfig.toZnRecord(offlineTableConfig));
}

53. PDashboardSlider#position()

Project: Protocoder
Source File: PDashboardSlider.java
View license
//TODO this method doesnt work yet
//
[email protected](description = "change the slider value", example = "")
[email protected](params = { "value" })
public void position(float position) throws UnknownHostException, JSONException {
    JSONObject msg = new JSONObject();
    msg.put("type", "widget");
    msg.put("action", "setValue");
    JSONObject values = new JSONObject();
    values.put("id", id);
    values.put("type", "label");
    values.put("val", position);
    msg.put("values", values);
    CustomWebsocketServer ws = CustomWebsocketServer.getInstance(getContext());
    ws.send(msg);
}

54. RealmJsonTests#createObjectFromJson_childObjectList()

Project: realm-java
Source File: RealmJsonTests.java
View license
@Test
public void createObjectFromJson_childObjectList() throws JSONException {
    JSONObject allTypesObject = new JSONObject();
    JSONObject dog1 = new JSONObject();
    dog1.put("name", "Fido-1");
    JSONObject dog2 = new JSONObject();
    dog2.put("name", "Fido-2");
    JSONObject dog3 = new JSONObject();
    dog3.put("name", "Fido-3");
    JSONArray dogList = new JSONArray();
    dogList.put(dog1);
    dogList.put(dog2);
    dogList.put(dog3);
    allTypesObject.put("columnRealmList", dogList);
    realm.beginTransaction();
    realm.createObjectFromJson(AllTypes.class, allTypesObject);
    realm.commitTransaction();
    AllTypes obj = realm.where(AllTypes.class).findFirst();
    assertEquals(3, obj.getColumnRealmList().size());
    assertEquals("Fido-3", obj.getColumnRealmList().get(2).getName());
}

55. SyncState#asJSON()

View license
/**
	 * @return json representation of sync
	 * @throws JSONException
	 */
public JSONObject asJSON() throws JSONException {
    JSONObject sync = new JSONObject();
    sync.put(SmartStore.SOUP_ENTRY_ID, id);
    sync.put(SYNC_TYPE, type.name());
    if (target != null)
        sync.put(SYNC_TARGET, target.asJSON());
    if (options != null)
        sync.put(SYNC_OPTIONS, options.asJSON());
    sync.put(SYNC_SOUP_NAME, soupName);
    sync.put(SYNC_STATUS, status.name());
    sync.put(SYNC_PROGRESS, progress);
    sync.put(SYNC_TOTAL_SIZE, totalSize);
    sync.put(SYNC_MAX_TIME_STAMP, maxTimeStamp);
    return sync;
}

56. AlignmentSVGVisualizationUpdate#getForceLayoutNodeJsonObject()

View license
private JSONObject getForceLayoutNodeJsonObject(int id, String label, String nodeId, String nodeType, boolean isForcedByUser, String nodeDomain, boolean isUri) throws JSONException {
    JSONObject nodeObj = new JSONObject();
    nodeObj.put(JsonKeys.label.name(), label);
    nodeObj.put(JsonKeys.id.name(), id);
    nodeObj.put(JsonKeys.nodeId.name(), nodeId);
    nodeObj.put(JsonKeys.nodeType.name(), nodeType);
    nodeObj.put(JsonKeys.isForcedByUser.name(), isForcedByUser);
    nodeObj.put(JsonKeys.nodeDomain.name(), nodeDomain);
    nodeObj.put(JsonKeys.isUri.name(), isUri);
    return nodeObj;
}

57. TestUtils#getJsonDataNode()

Project: ambry
Source File: TestUtils.java
View license
/**
   * Generate a JSON data node object with a defined [email protected] rackId}.
   *
   * @param hostname the hostname for the node
   * @param port the plaintext port number for the node
   * @param sslPort the ssl port number for the node
   * @param rackId the rack ID for the node
   * @param hardwareState A [email protected] HardwareState} value for the node
   * @param disks an array of disks belonging to the node
   * @return a [email protected] JSONObject) representing the node with the properties passed into the function
   * @throws JSONException
   */
public static JSONObject getJsonDataNode(String hostname, int port, int sslPort, long rackId, HardwareState hardwareState, JSONArray disks) throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("hostname", hostname);
    jsonObject.put("port", port);
    jsonObject.put("sslport", sslPort);
    jsonObject.put("rackId", rackId);
    jsonObject.put("hardwareState", hardwareState);
    jsonObject.put("disks", disks);
    return jsonObject;
}

58. ABTestEventReportingService#jsonFromABTestEvent()

View license
private static JSONObject jsonFromABTestEvent(ABTestEvent model) throws JSONException {
    JSONObject payload = new JSONObject();
    payload.put(KEY_TEST, model.getValue(ABTestEvent.TEST_NAME));
    payload.put(KEY_VARIANT, model.getValue(ABTestEvent.TEST_VARIANT));
    payload.put(KEY_NEW_USER, model.getValue(ABTestEvent.NEW_USER) > 0 ? true : false);
    payload.put(KEY_ACTIVE_USER, model.getValue(ABTestEvent.ACTIVATED_USER) > 0 ? true : false);
    payload.put(KEY_DAYS, new JSONArray().put(model.getValue(ABTestEvent.TIME_INTERVAL)));
    long date = model.getValue(ABTestEvent.DATE_RECORDED) / 1000L;
    payload.put(KEY_DATE, date);
    return payload;
}

59. SyncMessageTest#getMakeChanges()

Project: astrid
Source File: SyncMessageTest.java
View license
private JSONObject getMakeChanges(String... extraChanges) throws JSONException {
    JSONObject makeChanges = new JSONObject();
    makeChanges.put("type", ServerToClientMessage.TYPE_MAKE_CHANGES);
    makeChanges.put("table", NameMaps.TABLE_ID_TASKS);
    JSONObject changes = new JSONObject();
    changes.put("title", MAKE_CHANGES_TITLE);
    changes.put("importance", Task.IMPORTANCE_DO_OR_DIE);
    if (extraChanges != null) {
        for (int i = 0; i < extraChanges.length - 1; i += 2) {
            String key = extraChanges[i];
            String value = extraChanges[i + 1];
            changes.put(key, value);
        }
    }
    makeChanges.put("changes", changes);
    return makeChanges;
}

60. UnionPayCapabilitiesUnitTest#fromJson_creates()

View license
@Test
public void fromJson_creates() throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("isUnionPay", true);
    jsonObject.put("isDebit", false);
    JSONObject unionPayObject = new JSONObject();
    unionPayObject.put("supportsTwoStepAuthAndCapture", true);
    unionPayObject.put("isUnionPayEnrollmentRequired", false);
    jsonObject.put("unionPay", unionPayObject);
    UnionPayCapabilities unionPayCapabilities = UnionPayCapabilities.fromJson(jsonObject.toString());
    assertTrue(unionPayCapabilities.isUnionPay());
    assertFalse(unionPayCapabilities.isDebit());
    assertTrue(unionPayCapabilities.supportsTwoStepAuthAndCapture());
    assertFalse(unionPayCapabilities.isUnionPayEnrollmentRequired());
}

61. InvitationWebScriptTest#createModeratedInvitation()

View license
private String createModeratedInvitation(String siteName, String inviteeComments, String inviteeUserName, String inviteeRoleName) throws Exception {
    /*
         * Create a new moderated invitation
         */
    JSONObject newInvitation = new JSONObject();
    newInvitation.put("invitationType", "MODERATED");
    newInvitation.put("inviteeRoleName", inviteeRoleName);
    newInvitation.put("inviteeComments", inviteeComments);
    newInvitation.put("inviteeUserName", inviteeUserName);
    Response response = sendRequest(new PostRequest(URL_SITES + "/" + siteName + "/invitations", newInvitation.toString(), "application/json"), 201);
    JSONObject top = new JSONObject(response.getContentAsString());
    JSONObject data = top.getJSONObject("data");
    String inviteId = data.getString("inviteId");
    createdInvitations.add(new Tracker(inviteId, siteName));
    return inviteId;
}

62. InviteServiceTest#createModeratedInvitation()

View license
private String createModeratedInvitation(String siteName, String inviteeComments, String inviteeUserName, String inviteeRoleName) throws Exception {
    String URL_SITES = "/api/sites";
    /*
         * Create a new moderated invitation
         */
    JSONObject newInvitation = new JSONObject();
    newInvitation.put("invitationType", "MODERATED");
    newInvitation.put("inviteeRoleName", inviteeRoleName);
    newInvitation.put("inviteeComments", inviteeComments);
    newInvitation.put("inviteeUserName", inviteeUserName);
    Response response = sendRequest(new PostRequest(URL_SITES + "/" + siteName + "/invitations", newInvitation.toString(), "application/json"), 201);
    JSONObject top = new JSONObject(response.getContentAsString());
    JSONObject data = top.getJSONObject("data");
    String inviteId = data.getString("inviteId");
    return inviteId;
}

63. SiteServiceTest#createModeratedInvitation()

View license
private String createModeratedInvitation(String siteName, String inviteeComments, String inviteeUserName, String inviteeRoleName) throws Exception {
    /*
         * Create a new moderated invitation
         */
    JSONObject newInvitation = new JSONObject();
    newInvitation.put("invitationType", "MODERATED");
    newInvitation.put("inviteeRoleName", inviteeRoleName);
    newInvitation.put("inviteeComments", inviteeComments);
    newInvitation.put("inviteeUserName", inviteeUserName);
    Response response = sendRequest(new PostRequest(URL_SITES + "/" + siteName + "/invitations", newInvitation.toString(), "application/json"), 201);
    JSONObject top = new JSONObject(response.getContentAsString());
    JSONObject data = top.getJSONObject("data");
    String inviteId = data.getString("inviteId");
    return inviteId;
}

64. Notification#toString()

View license
/**
     * Encode options to JSON.
     */
public String toString() {
    JSONObject dict = options.getDict();
    JSONObject json = new JSONObject();
    try {
        json = new JSONObject(dict.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    json.remove("firstAt");
    json.remove("updated");
    json.remove("soundUri");
    json.remove("iconUri");
    return json.toString();
}

65. DesignDocumentTest#views()

View license
@Test
public void views() throws Exception {
    final JSONObject view = new JSONObject();
    view.put("index", "function(doc) { return null; }");
    final JSONObject fulltext = new JSONObject();
    fulltext.put("foo", view);
    final JSONObject json = new JSONObject();
    json.put("_id", "_design/hello");
    json.put("fulltext", fulltext);
    final DesignDocument ddoc = new DesignDocument(json);
    assertThat(ddoc.getView("foo"), notNullValue());
    assertThat(ddoc.getAllViews().size(), is(1));
}

66. ItsSerializer#serializeFace()

Project: CtsVerifier
Source File: ItsSerializer.java
View license
@SuppressWarnings("unchecked")
private static Object serializeFace(Face face) throws org.json.JSONException {
    JSONObject faceObj = new JSONObject();
    faceObj.put("bounds", serializeRect(face.getBounds()));
    faceObj.put("score", face.getScore());
    faceObj.put("id", face.getId());
    faceObj.put("leftEye", serializePoint(face.getLeftEyePosition()));
    faceObj.put("rightEye", serializePoint(face.getRightEyePosition()));
    faceObj.put("mouth", serializePoint(face.getMouthPosition()));
    return faceObj;
}

67. Cumulio#dissociate()

Project: cumul.io-sdk-java
Source File: Cumulio.java
View license
public JSONObject dissociate(String resource, String id, String associationRole, String associationId) throws IOException {
    JSONObject association = new JSONObject();
    association.put("role", associationRole);
    association.put("id", associationId);
    JSONObject query = new JSONObject();
    query.put("action", "associate");
    query.put("id", id);
    query.put("resource", association);
    return _emit(resource, "UNLINK", query);
}

68. KCXMLHttpRequest#handleHeaders()

View license
// send headers to the JS layer
private void handleHeaders(KCWebView webView, KCHeaderGroup headerGroup, KCStatusLine sl) throws JSONException {
    KCHeader[] headers = headerGroup.getAllHeaders();
    JSONObject jsonHeaders = new JSONObject();
    for (KCHeader h : headers) {
        String name = h.getName();
        String value = h.getValue();
        if (name.equalsIgnoreCase(KCHttpDefine.HEADER_CONTENT_TYPE)) {
            mResponseCharset = readCharset(value, DEFAULT_RESPONSE_CHARSET);
        }
        jsonHeaders.put(name, value);
    }
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("id", mId);
    jsonObject.put("readyState", HEADERS_RECEIVED);
    jsonObject.put("status", sl.getStatusCode());
    jsonObject.put("statusText", sl.getReasonPhrase());
    jsonObject.put("headers", jsonHeaders);
    callJSSetProperties(webView, jsonObject);
}

69. UserNotificationRepository#toJSONObject()

View license
public static JSONObject toJSONObject(UserNotification notification) {
    JSONObject json = new JSONObject();
    json.put("id", notification.getId());
    json.put("type", "user");
    json.put("title", notification.getTitle());
    json.put("message", notification.getMessage());
    json.put("sentDate", notification.getSentDate().getTime());
    if (notification.getActionEvent() != null) {
        JSONObject action = new JSONObject();
        action.put("event", notification.getActionEvent());
        action.putOpt("data", notification.getActionPayload());
        json.put("action", action);
    }
    json.put("hash", hash(json.toString()));
    return json;
}

70. WorkQueueRepository#pushSessionExpiration()

Project: lumify
Source File: WorkQueueRepository.java
View license
public void pushSessionExpiration(String userId, String sessionId) {
    JSONObject json = new JSONObject();
    json.put("type", "sessionExpiration");
    JSONObject permissions = new JSONObject();
    JSONArray users = new JSONArray();
    users.put(userId);
    permissions.put("users", users);
    JSONArray sessionIds = new JSONArray();
    sessionIds.put(sessionId);
    permissions.put("sessionIds", sessionIds);
    json.put("permissions", permissions);
    json.putOpt("sessionId", sessionId);
    broadcastJson(json);
}

71. StumblerBundleTest#getExpectedGeosubmit()

Project: MozStumbler
Source File: StumblerBundleTest.java
View license
protected JSONObject getExpectedGeosubmit() throws JSONException {
    ISystemClock clock = (ISystemClock) ServiceLocator.getInstance().getService(ISystemClock.class);
    // Set each wifi scan to be WIFI_SCAN_uSec expressed in millisec precision
    long ageMS = WIFI_SCAN_uSec_DELTA / 1000;
    List<JSONObject> wifiList = new ArrayList<JSONObject>();
    JSONObject wifi = new JSONObject();
    wifi.put("macAddress", "01:23:45:67:89:ab");
    wifi.put("age", ageMS);
    wifiList.add(wifi);
    wifi = new JSONObject();
    wifi.put("macAddress", "23:45:67:89:ab:cd");
    wifi.put("age", ageMS);
    wifiList.add(wifi);
    JSONArray wifiArray = new JSONArray(wifiList);
    JSONObject stumbleBlob = new JSONObject();
    stumbleBlob.put("wifiAccessPoints", wifiArray);
    JSONObject itemsContainer = new JSONObject();
    List<JSONObject> cellTowerList = new ArrayList<JSONObject>();
    JSONObject cellTower = new JSONObject();
    cellTower.put("cellId", 12345);
    cellTower.put("radioType", "lte");
    cellTower.put("locationAreaCode", 2);
    cellTower.put("mobileCountryCode", 208);
    cellTower.put("mobileNetworkCode", 1);
    cellTower.put("signalStrength", -51);
    cellTower.put("timingAdvance", 1);
    cellTower.put("asu", 31);
    cellTowerList.add(cellTower);
    JSONArray cellTowerArray = new JSONArray(cellTowerList);
    stumbleBlob.put(DataStorageConstants.ReportsColumns.CELL, cellTowerArray);
    // The timestamp of the blob should be the current system time which is what the mock location
    // in geosubmit and geolocate will use for the GPS timestamp
    stumbleBlob.put(DataStorageConstants.ReportsColumns.TIME, clock.currentTimeMillis());
    stumbleBlob.put(DataStorageConstants.ReportsColumns.ALTITUDE, 202.9f);
    stumbleBlob.put(DataStorageConstants.ReportsColumns.LON, -43.5f);
    stumbleBlob.put(DataStorageConstants.ReportsColumns.LAT, -22.5f);
    stumbleBlob.put(DataStorageConstants.ReportsColumns.ACCURACY, 20.5f);
    stumbleBlob.put(DataStorageConstants.ReportsColumns.SPEED, 0.0);
    stumbleBlob.put(DataStorageConstants.ReportsColumns.HEADING, 0.0);
    List<JSONObject> itemsList = new ArrayList<JSONObject>();
    itemsList.add(stumbleBlob);
    JSONArray itemsArray = new JSONArray(itemsList);
    itemsContainer.put("items", itemsArray);
    return itemsContainer;
}

72. OperaMobileEmulationTest#fromJsonDeserializesProperly()

View license
@Test
public void fromJsonDeserializesProperly() throws JSONException {
    JSONObject json = new JSONObject();
    json.put("profileName", "hoobaflooba");
    json.put("width", 100);
    json.put("height", 200);
    json.put("ppi", 300);
    json.put("ime", "tablet");
    json.put("userAgent", "MeeGo");
    EmulationProfile profile = OperaMobileEmulation.fromJson(json);
    assertEquals("hoobaflooba", profile.getProfileName());
    assertEquals(new Dimension(100, 200), profile.getResolution());
    assertEquals(300, profile.getPPI());
    assertEquals(EmulationProfile.IME.TABLET, profile.getIME());
    assertEquals(OperaMobileEmulation.UserAgent.MEEGO.toString(), profile.getUserAgent());
}

73. SelftestTest#fromJsonDeserializesProperly()

Project: operaprestodriver
Source File: SelftestTest.java
View license
@Test
public void fromJsonDeserializesProperly() throws JSONException {
    JSONObject json = new JSONObject();
    json.put("testName", "name");
    json.put("groupName", "group");
    json.put("fileName", "filename");
    json.put("reason", "reason");
    json.put("result", SelftestResult.Result.PASS);
    json.put("lineNumber", 333);
    Selftest.SelftestResult expected = ((ScopeSelftestResult) ScopeSelftestResult.builder().build()).fromJson(json);
    assertEquals("name", expected.getTestName());
    assertEquals("group", expected.getGroupName());
    assertEquals("filename", expected.getFileName());
    assertEquals("reason", expected.getReason());
    assertEquals(SelftestResult.Result.PASS, expected.getResult());
    assertEquals(333, expected.getLineNumber());
}

74. ParseACLTest#testCreateACLFromJSONObject()

Project: Parse-SDK-Android
Source File: ParseACLTest.java
View license
//endregion
//region testCreateACLFromJSONObject
@Test
public void testCreateACLFromJSONObject() throws Exception {
    JSONObject aclJson = new JSONObject();
    JSONObject permission = new JSONObject();
    permission.put(READ_PERMISSION, true);
    permission.put(WRITE_PERMISSION, true);
    aclJson.put("userId", permission);
    ParseUser unresolvedUser = new ParseUser();
    JSONObject unresolvedUserJson = new JSONObject();
    aclJson.put("unresolvedUser", unresolvedUserJson);
    // Mock decoder
    ParseDecoder mockDecoder = mock(ParseDecoder.class);
    when(mockDecoder.decode(eq(unresolvedUserJson))).thenReturn(unresolvedUser);
    ParseACL acl = ParseACL.createACLFromJSONObject(aclJson, mockDecoder);
    assertSame(unresolvedUser, acl.getUnresolvedUser());
    assertTrue(acl.getReadAccess("userId"));
    assertTrue(acl.getWriteAccess("userId"));
    assertEquals(1, acl.getPermissionsById().size());
}

75. AbstractTableConfig#fromZnRecord()

Project: pinot
Source File: AbstractTableConfig.java
View license
public static AbstractTableConfig fromZnRecord(ZNRecord record) throws JsonParseException, JsonMappingException, JsonProcessingException, JSONException, IOException {
    Map<String, String> simpleFields = record.getSimpleFields();
    JSONObject str = new JSONObject();
    str.put("tableName", simpleFields.get("tableName"));
    str.put("tableType", simpleFields.get("tableType"));
    str.put("segmentsConfig", new JSONObject(simpleFields.get("segmentsConfig")));
    str.put("tenants", new JSONObject(simpleFields.get("tenants")));
    str.put("tableIndexConfig", new JSONObject(simpleFields.get("tableIndexConfig")));
    str.put("metadata", new JSONObject(simpleFields.get("metadata")));
    return init(str.toString());
}

76. TenantTest#testDeserializeFromJson()

Project: pinot
Source File: TenantTest.java
View license
@Test
public void testDeserializeFromJson() throws JSONException, IOException {
    JSONObject json = new JSONObject();
    json.put("tenantRole", "SERVER");
    json.put("tenantName", "newTenant");
    json.put("numberOfInstances", 10);
    json.put("offlineInstances", 5);
    json.put("realtimeInstances", 5);
    json.put("keyIDontKnow", "blahblahblah");
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree(json.toString());
    Tenant tenant = mapper.readValue(jsonNode, Tenant.class);
    Assert.assertEquals(5, tenant.getOfflineInstances());
    Assert.assertEquals(10, tenant.getNumberOfInstances());
    Assert.assertEquals("newTenant", tenant.getTenantName());
    Assert.assertEquals(TenantRole.SERVER, tenant.getTenantRole());
}

77. ChannelInfo#toJSONObject()

View license
// @cond INTERNAL
@Override
public JSONObject toJSONObject() throws JSONException {
    JSONObject obj = new JSONObject();
    obj.put("name", channelName);
    obj.put("id", channelId);
    obj.put("number", channelNumber);
    obj.put("majorNumber", majorNumber);
    obj.put("minorNumber", minorNumber);
    obj.put("rawData", rawData);
    return obj;
}

78. RealmJsonTests#createObjectFromJson_allSimpleObjectAllTypes()

Project: realm-java
Source File: RealmJsonTests.java
View license
@Test
public void createObjectFromJson_allSimpleObjectAllTypes() throws JSONException {
    JSONObject json = new JSONObject();
    json.put("columnString", "String");
    json.put("columnLong", 1L);
    json.put("columnFloat", 1.23F);
    json.put("columnDouble", 1.23D);
    json.put("columnBoolean", true);
    json.put("columnBinary", new String(Base64.encode(new byte[] { 1, 2, 3 }, Base64.DEFAULT)));
    realm.beginTransaction();
    realm.createObjectFromJson(AllTypes.class, json);
    realm.commitTransaction();
    AllTypes obj = realm.where(AllTypes.class).findFirst();
    // Check that all primitive types are imported correctly
    assertEquals("String", obj.getColumnString());
    assertEquals(1L, obj.getColumnLong());
    assertEquals(1.23F, obj.getColumnFloat(), 0F);
    assertEquals(1.23D, obj.getColumnDouble(), 0D);
    assertEquals(true, obj.isColumnBoolean());
    assertArrayEquals(new byte[] { 1, 2, 3 }, obj.getColumnBinary());
}

79. AbstractSmartStoreTest#testUpsertWithNonUniqueExternalId()

View license
/**
	 * Testing upsert with an external id that is not unique in the soup
	 * @throws JSONException
	 */
public void testUpsertWithNonUniqueExternalId() throws JSONException {
    JSONObject soupElt1 = new JSONObject("{'key':'ka', 'value':'va1'}");
    JSONObject soupElt2 = new JSONObject("{'key':'ka', 'value':'va2'}");
    JSONObject soupElt3 = new JSONObject("{'key':'ka', 'value':'va3'}");
    JSONObject soupElt1Upserted = store.upsert(TEST_SOUP, soupElt1);
    JSONObject soupElt2Upserted = store.upsert(TEST_SOUP, soupElt2);
    JSONObject soupElt1Retrieved = store.retrieve(TEST_SOUP, idOf(soupElt1Upserted)).getJSONObject(0);
    JSONObject soupElt2Retrieved = store.retrieve(TEST_SOUP, idOf(soupElt2Upserted)).getJSONObject(0);
    JSONTestHelper.assertSameJSON("Retrieve mismatch", soupElt1Upserted, soupElt1Retrieved);
    JSONTestHelper.assertSameJSON("Retrieve mismatch", soupElt2Upserted, soupElt2Retrieved);
    try {
        store.upsert(TEST_SOUP, soupElt3, "key");
        fail("Exception was expected: key is not unique in the soup");
    } catch (RuntimeException e) {
        assertTrue("Wrong exception", e.getMessage().contains("are more than one soup elements"));
    }
}

80. ActionChainTest#testPauseAction()

Project: selendroid
Source File: ActionChainTest.java
View license
@Test
public void testPauseAction() throws JSONException {
    JSONObject actionJSON = new JSONObject();
    JSONArray jsonArray = new JSONArray();
    JSONObject obj1 = new JSONObject();
    obj1.put("name", TouchActionName.PAUSE);
    obj1.put("ms", 500);
    jsonArray.put(obj1);
    actionJSON.put("actions", jsonArray);
    actionJSON.put("inputDevice", "TestDevice");
    ActionChain actionChain = new ActionChain(actionJSON);
    // Should not be paused, should have 1 item next
    Assert.assertTrue(actionChain.hasNext());
    JSONObject nextItem = actionChain.next();
    // Should be paused, should not have next.
    Assert.assertEquals(nextItem.get("name"), TouchActionName.PAUSE);
    Assert.assertEquals(actionChain.getPauseTime(), 500);
    Assert.assertEquals(nextItem, obj1);
    Assert.assertFalse(actionChain.hasNext());
}

81. InitService#initStatistic()

Project: solo
Source File: InitService.java
View license
/**
     * Initializes statistic.
     *
     * @throws RepositoryException repository exception
     * @throws JSONException json exception
     */
private void initStatistic() throws RepositoryException, JSONException {
    LOGGER.info("Initializing statistic....");
    final JSONObject statistic = new JSONObject();
    statistic.put(Keys.OBJECT_ID, Statistic.STATISTIC);
    statistic.put(Statistic.STATISTIC_BLOG_ARTICLE_COUNT, 0);
    statistic.put(Statistic.STATISTIC_PUBLISHED_ARTICLE_COUNT, 0);
    statistic.put(Statistic.STATISTIC_BLOG_VIEW_COUNT, 0);
    statistic.put(Statistic.STATISTIC_BLOG_COMMENT_COUNT, 0);
    statistic.put(Statistic.STATISTIC_PUBLISHED_BLOG_COMMENT_COUNT, 0);
    statisticRepository.add(statistic);
    LOGGER.info("Initialized statistic");
}

82. LinkMgmtServiceTestCase#changeOrder()

Project: solo
Source File: LinkMgmtServiceTestCase.java
View license
/**
     * Change Order.
     * 
     * @throws Exception exception
     */
@Test(dependsOnMethods = "addLink")
public void changeOrder() throws Exception {
    final LinkMgmtService linkMgmtService = getLinkMgmtService();
    final JSONObject requestJSONObject = new JSONObject();
    final JSONObject link = new JSONObject();
    requestJSONObject.put(Link.LINK, link);
    link.put(Link.LINK_TITLE, "link4 title");
    link.put(Link.LINK_ADDRESS, "link4 address");
    link.put(Link.LINK_DESCRIPTION, "link4 description");
    final String linkId = linkMgmtService.addLink(requestJSONObject);
    Assert.assertNotNull(linkId);
    final int oldOrder = link.getInt(Link.LINK_ORDER);
    linkMgmtService.changeOrder(linkId, "up");
    final JSONObject result = getLinkQueryService().getLink(linkId);
    Assert.assertNotNull(result);
    Assert.assertTrue(oldOrder > result.getJSONObject(Link.LINK).getInt(Link.LINK_ORDER));
}

83. ConfigurationMetadataAnnotationProcessorTests#mergingOfAdditionalMetadata()

View license
@Test
public void mergingOfAdditionalMetadata() throws Exception {
    File metaInfFolder = new File(this.compiler.getOutputLocation(), "META-INF");
    metaInfFolder.mkdirs();
    File additionalMetadataFile = new File(metaInfFolder, "additional-spring-configuration-metadata.json");
    additionalMetadataFile.createNewFile();
    JSONObject property = new JSONObject();
    property.put("name", "foo");
    property.put("type", "java.lang.String");
    property.put("sourceType", AdditionalMetadata.class.getName());
    JSONArray properties = new JSONArray();
    properties.put(property);
    JSONObject additionalMetadata = new JSONObject();
    additionalMetadata.put("properties", properties);
    FileWriter writer = new FileWriter(additionalMetadataFile);
    additionalMetadata.write(writer);
    writer.flush();
    ConfigurationMetadata metadata = compile(SimpleProperties.class);
    assertThat(metadata).has(Metadata.withProperty("simple.comparator"));
    assertThat(metadata).has(Metadata.withProperty("foo", String.class).fromSource(AdditionalMetadata.class));
}

84. Notification#toString()

Project: VallasciApp-ionic
Source File: Notification.java
View license
/**
     * Encode options to JSON.
     */
public String toString() {
    JSONObject dict = options.getDict();
    JSONObject json = new JSONObject();
    try {
        json = new JSONObject(dict.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    json.remove("firstAt");
    json.remove("updated");
    json.remove("soundUri");
    json.remove("iconUri");
    return json.toString();
}

85. ImportSQLCommand#createImport()

Project: Web-Karma
Source File: ImportSQLCommand.java
View license
@Override
protected Import createImport(Workspace workspace) {
    JSONObject prefObject = new JSONObject();
    prefObject.put(PreferenceKeys.dBorSIDName.name(), dBorSIDName);
    prefObject.put(PreferenceKeys.dbType.name(), dbType);
    prefObject.put(PreferenceKeys.hostname.name(), hostname);
    prefObject.put(PreferenceKeys.portnumber.name(), portnumber);
    prefObject.put(PreferenceKeys.query.name(), query);
    prefObject.put(PreferenceKeys.username.name(), username);
    workspace.getCommandPreferences().setCommandPreferences(ImportSQLCommand.class.getSimpleName() + "Preferences", prefObject);
    return new SQLImport(dbType, hostname, portnumber, username, password, dBorSIDName, query, workspace, "");
}

86. GraphObjectFactoryTests#testCanConvertFromJSON()

Project: astrid
Source File: GraphObjectFactoryTests.java
View license
@SmallTest
@MediumTest
@LargeTest
public void testCanConvertFromJSON() throws JSONException {
    JSONObject jsonLocation = new JSONObject();
    jsonLocation.put("city", "Paris");
    jsonLocation.put("country", "France");
    JSONObject jsonPlace = new JSONObject();
    jsonPlace.put("location", jsonLocation);
    jsonPlace.put("name", "Eiffel Tower");
    GraphPlace graphPlace = GraphObject.Factory.create(jsonPlace, GraphPlace.class);
    GraphLocation graphLocation = graphPlace.getLocation();
    assertEquals("Paris", graphLocation.getCity());
}

87. SiteActivitySystemTest#createSite()

View license
protected void createSite(String siteId, boolean isPublic, String ticket) throws Exception {
    JSONObject site = new JSONObject();
    site.put("sitePreset", "myPreset");
    site.put("shortName", siteId);
    site.put("title", "myTitle");
    site.put("description", "myDescription");
    site.put("isPublic", isPublic);
    String url = WEBSCRIPT_ENDPOINT + URL_SITES;
    String response = callPostWebScript(url, ticket, site.toString());
    if (logger.isDebugEnabled()) {
        logger.debug("createSite: " + siteId);
        logger.debug("----------");
        logger.debug(url);
        logger.debug(response);
    }
}

88. SiteActivitySystemTest#createUser()

View license
protected void createUser(String ticket, String username, String password) throws JSONException, IOException, URISyntaxException {
    // Build the JSON person object
    JSONObject person = new JSONObject();
    person.put("userName", username);
    person.put("firstName", "first");
    person.put("lastName", "last");
    person.put("email", "[email protected]");
    person.put("password", password);
    String url = WEBSCRIPT_ENDPOINT + URL_PEOPLE;
    String response = callPostWebScript(url, ticket, person.toString());
    if (logger.isDebugEnabled()) {
        logger.debug("addPerson: " + username);
        logger.debug("--------------");
        logger.debug(url);
        logger.debug(response);
    }
}

89. InvitationWebScriptTest#createSite()

View license
private JSONObject createSite(String sitePreset, String shortName, String title, String description, SiteVisibility visibility, int expectedStatus) throws Exception {
    JSONObject site = new JSONObject();
    site.put("sitePreset", sitePreset);
    site.put("shortName", shortName);
    site.put("title", title);
    site.put("description", description);
    site.put("visibility", visibility.toString());
    Response response = sendRequest(new PostRequest(URL_SITES, site.toString(), "application/json"), expectedStatus);
    this.createdSites.add(shortName);
    return new JSONObject(response.getContentAsString());
}

90. RuleServiceTest#buildCopyAction()

View license
private JSONObject buildCopyAction(NodeRef destination) throws JSONException {
    JSONObject result = new JSONObject();
    // add actionDefinitionName
    result.put("actionDefinitionName", "copy");
    // build parameterValues
    JSONObject parameterValues = new JSONObject();
    parameterValues.put("destination-folder", destination);
    // add parameterValues
    result.put("parameterValues", parameterValues);
    // add executeAsync
    result.put("executeAsync", false);
    return result;
}

91. AbstractSiteServiceTest#createSite()

View license
protected JSONObject createSite(String sitePreset, String shortName, String title, String description, SiteVisibility visibility, int expectedStatus) throws Exception {
    JSONObject site = new JSONObject();
    site.put("sitePreset", sitePreset);
    site.put("shortName", shortName);
    site.put("title", title);
    site.put("description", description);
    site.put("visibility", visibility.toString());
    Response response = sendRequest(new PostRequest(URL_SITES, site.toString(), "application/json"), expectedStatus);
    this.createdSites.add(shortName);
    return new JSONObject(response.getContentAsString());
}

92. SiteServiceTest#testUpdateSite()

View license
public void testUpdateSite() throws Exception {
    // Create a site
    String shortName = GUID.generate();
    JSONObject result = createSite("myPreset", shortName, "myTitle", "myDescription", SiteVisibility.PUBLIC, 200);
    // Update the site
    result.put("title", "abs123abc");
    result.put("description", "123abc123");
    result.put("visibility", SiteVisibility.PRIVATE.toString());
    Response response = sendRequest(new PutRequest(URL_SITES + "/" + shortName, result.toString(), "application/json"), 200);
    result = new JSONObject(response.getContentAsString());
    assertEquals("abs123abc", result.get("title"));
    assertEquals("123abc123", result.get("description"));
    assertFalse(result.getBoolean("isPublic"));
    assertEquals(SiteVisibility.PRIVATE.toString(), result.get("visibility"));
    // Try and get the site and double check it's changed
    response = sendRequest(new GetRequest(URL_SITES + "/" + shortName), 200);
    result = new JSONObject(response.getContentAsString());
    assertEquals("abs123abc", result.get("title"));
    assertEquals("123abc123", result.get("description"));
    assertFalse(result.getBoolean("isPublic"));
    assertEquals(SiteVisibility.PRIVATE.toString(), result.get("visibility"));
}

93. FileUtils#getFileMetadata()

View license
/**
     * Returns a File that represents the current state of the file that this FileEntry represents.
     *
     * @param filePath to entry
     * @return returns a JSONObject represent a W3C File object
     * @throws FileNotFoundException
     * @throws JSONException
     */
private JSONObject getFileMetadata(String filePath) throws FileNotFoundException, JSONException {
    File file = createFileObject(filePath);
    if (!file.exists()) {
        throw new FileNotFoundException("File: " + filePath + " does not exist.");
    }
    JSONObject metadata = new JSONObject();
    metadata.put("size", file.length());
    metadata.put("type", FileHelper.getMimeType(filePath, cordova));
    metadata.put("name", file.getName());
    metadata.put("fullPath", filePath);
    metadata.put("lastModifiedDate", file.lastModified());
    return metadata;
}

94. EventTests#testFromJSON_nullSegmentation()

Project: countly-sdk-android
Source File: EventTests.java
View license
public void testFromJSON_nullSegmentation() throws JSONException {
    final Event expected = new Event();
    expected.key = "eventKey";
    expected.timestamp = 1234;
    expected.count = 42;
    expected.sum = 3.2;
    final JSONObject jsonObj = new JSONObject();
    jsonObj.put("key", expected.key);
    jsonObj.put("timestamp", expected.timestamp);
    jsonObj.put("count", expected.count);
    jsonObj.put("sum", expected.sum);
    jsonObj.put("segmentation", JSONObject.NULL);
    final Event actual = Event.fromJSON(jsonObj);
    assertEquals(expected, actual);
    assertEquals(expected.count, actual.count);
    assertEquals(expected.sum, actual.sum);
}

95. EventTests#testFromJSON_segmentationNotADictionary()

Project: countly-sdk-android
Source File: EventTests.java
View license
public void testFromJSON_segmentationNotADictionary() throws JSONException {
    final Event expected = new Event();
    expected.key = "eventKey";
    expected.timestamp = 1234;
    expected.count = 42;
    expected.sum = 3.2;
    final JSONObject jsonObj = new JSONObject();
    jsonObj.put("key", expected.key);
    jsonObj.put("timestamp", expected.timestamp);
    jsonObj.put("count", expected.count);
    jsonObj.put("sum", expected.sum);
    jsonObj.put("segmentation", 1234);
    assertNull(Event.fromJSON(jsonObj));
}

96. EventTests#testFromJSON_emptySegmentation()

Project: countly-sdk-android
Source File: EventTests.java
View license
public void testFromJSON_emptySegmentation() throws JSONException {
    final Event expected = new Event();
    expected.key = "eventKey";
    expected.timestamp = 1234;
    expected.count = 42;
    expected.sum = 3.2;
    expected.segmentation = new HashMap<String, String>();
    final JSONObject jsonObj = new JSONObject();
    jsonObj.put("key", expected.key);
    jsonObj.put("timestamp", expected.timestamp);
    jsonObj.put("count", expected.count);
    jsonObj.put("sum", expected.sum);
    jsonObj.put("segmentation", new JSONObject(expected.segmentation));
    final Event actual = Event.fromJSON(jsonObj);
    assertEquals(expected, actual);
    assertEquals(expected.count, actual.count);
    assertEquals(expected.sum, actual.sum);
}

97. EventTests#testFromJSON_withSegmentation()

Project: countly-sdk-android
Source File: EventTests.java
View license
public void testFromJSON_withSegmentation() throws JSONException {
    final Event expected = new Event();
    expected.key = "eventKey";
    expected.timestamp = 1234;
    expected.count = 42;
    expected.sum = 3.2;
    expected.segmentation = new HashMap<String, String>();
    expected.segmentation.put("segkey", "segvalue");
    final JSONObject jsonObj = new JSONObject();
    jsonObj.put("key", expected.key);
    jsonObj.put("timestamp", expected.timestamp);
    jsonObj.put("count", expected.count);
    jsonObj.put("sum", expected.sum);
    jsonObj.put("segmentation", new JSONObject(expected.segmentation));
    final Event actual = Event.fromJSON(jsonObj);
    assertEquals(expected, actual);
    assertEquals(expected.count, actual.count);
    assertEquals(expected.sum, actual.sum);
}

98. EventTests#testFromJSON_withSegmentation_nonStringValue()

Project: countly-sdk-android
Source File: EventTests.java
View license
public void testFromJSON_withSegmentation_nonStringValue() throws JSONException {
    final Event expected = new Event();
    expected.key = "eventKey";
    expected.timestamp = 1234;
    expected.count = 42;
    expected.sum = 3.2;
    expected.segmentation = new HashMap<String, String>();
    expected.segmentation.put("segkey", "1234");
    final Map<Object, Object> badMap = new HashMap<Object, Object>();
    // JSONObject.getString will end up converting this to the string "1234"
    badMap.put("segkey", 1234);
    final JSONObject jsonObj = new JSONObject();
    jsonObj.put("key", expected.key);
    jsonObj.put("timestamp", expected.timestamp);
    jsonObj.put("count", expected.count);
    jsonObj.put("sum", expected.sum);
    jsonObj.put("segmentation", new JSONObject(badMap));
    final Event actual = Event.fromJSON(jsonObj);
    assertEquals(expected, actual);
    assertEquals(expected.count, actual.count);
    assertEquals(expected.sum, actual.sum);
}

99. HSZendeskGear#retrieveRequestProperties()

View license
private JSONObject retrieveRequestProperties(String body, String[] attachmentToken) throws JSONException {
    JSONObject comment = new JSONObject();
    JSONObject requestProperties = new JSONObject();
    JSONObject requestObject = new JSONObject();
    comment.put("body", body);
    if (attachmentToken != null) {
        JSONArray attachmentsArray = new JSONArray();
        for (int i = 0; i < attachmentToken.length; i++) {
            attachmentsArray.put(attachmentToken[i]);
        }
        comment.put("uploads", attachmentsArray);
    }
    requestProperties.put("comment", comment);
    requestObject.put("request", requestProperties);
    return requestObject;
}

100. KCXMLHttpRequest#returnResult()

View license
//if statusCode is 200, reasonPhrase is "OK"
private void returnResult(KCWebView webView, int statusCode, String reasonPhrase, String responseText) throws JSONException {
    if (mAborted)
        return;
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("id", mId);
    jsonObject.put("readyState", DONE);
    jsonObject.put("status", statusCode);
    jsonObject.put("statusText", reasonPhrase);
    jsonObject.put("responseText", responseText);
    callJSSetProperties(webView, jsonObject);
    mState = DONE;
}