use of org.json.JSONArray in project solo by b3log.
the class ArticleQueryService method getArticles.
/**
* Gets articles(by crate date descending) by the specified request json object.
*
* <p>
* If the property "articleIsPublished" of the specified request json object is {@code true}, the returned articles
* all are published, {@code false} otherwise.
* </p>
*
* <p>
* Specified the "excludes" for results properties exclusion.
* </p>
*
* @param requestJSONObject the specified request json object, for example, <pre>
* {
* "paginationCurrentPageNum": 1,
* "paginationPageSize": 20,
* "paginationWindowSize": 10,
* "articleIsPublished": boolean,
* "excludes": ["", ....] // Optional
* }, see {@link Pagination} for more details
* </pre>
*
* @return for example, <pre>
* {
* "pagination": {
* "paginationPageCount": 100,
* "paginationPageNums": [1, 2, 3, 4, 5]
* },
* "articles": [{
* "oId": "",
* "articleTitle": "",
* "articleCommentCount": int,
* "articleCreateTime"; long,
* "articleViewCount": int,
* "articleTags": "tag1, tag2, ....",
* "articlePutTop": boolean,
* "articleSignId": "",
* "articleViewPwd": "",
* "articleEditorType": "",
* .... // Specified by the "excludes"
* }, ....]
* }
* </pre>, order by article update date and sticky(put top).
*
* @throws ServiceException service exception
* @see Pagination
*/
public JSONObject getArticles(final JSONObject requestJSONObject) throws ServiceException {
final JSONObject ret = new JSONObject();
try {
final int currentPageNum = requestJSONObject.getInt(Pagination.PAGINATION_CURRENT_PAGE_NUM);
final int pageSize = requestJSONObject.getInt(Pagination.PAGINATION_PAGE_SIZE);
final int windowSize = requestJSONObject.getInt(Pagination.PAGINATION_WINDOW_SIZE);
final boolean articleIsPublished = requestJSONObject.optBoolean(ARTICLE_IS_PUBLISHED, true);
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).addSort(ARTICLE_PUT_TOP, SortDirection.DESCENDING).addSort(ARTICLE_CREATE_DATE, SortDirection.DESCENDING).setFilter(new PropertyFilter(ARTICLE_IS_PUBLISHED, FilterOperator.EQUAL, articleIsPublished));
int articleCount = statisticQueryService.getBlogArticleCount();
if (!articleIsPublished) {
articleCount -= statisticQueryService.getPublishedBlogArticleCount();
} else {
articleCount = statisticQueryService.getPublishedBlogArticleCount();
}
final int pageCount = (int) Math.ceil((double) articleCount / (double) pageSize);
query.setPageCount(pageCount);
final JSONObject result = articleRepository.get(query);
final JSONObject pagination = new JSONObject();
ret.put(Pagination.PAGINATION, pagination);
final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize);
pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
final JSONArray articles = result.getJSONArray(Keys.RESULTS);
JSONArray excludes = requestJSONObject.optJSONArray(Keys.EXCLUDES);
excludes = null == excludes ? new JSONArray() : excludes;
for (int i = 0; i < articles.length(); i++) {
final JSONObject article = articles.getJSONObject(i);
final JSONObject author = getAuthor(article);
final String authorName = author.getString(User.USER_NAME);
article.put(Common.AUTHOR_NAME, authorName);
article.put(ARTICLE_CREATE_TIME, ((Date) article.get(ARTICLE_CREATE_DATE)).getTime());
article.put(ARTICLE_UPDATE_TIME, ((Date) article.get(ARTICLE_UPDATE_DATE)).getTime());
// Remove unused properties
for (int j = 0; j < excludes.length(); j++) {
article.remove(excludes.optString(j));
}
}
ret.put(ARTICLES, articles);
return ret;
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Gets articles failed", e);
throw new ServiceException(e);
}
}
use of org.json.JSONArray in project solo by b3log.
the class TagQueryService method getTags.
/**
* Gets all tags.
*
* @return for example, <pre>
* [
* {"tagTitle": "", "tagReferenceCount": int, ....},
* ....
* ]
* </pre>, returns an empty list if not found
*
* @throws ServiceException service exception
*/
public List<JSONObject> getTags() throws ServiceException {
try {
final Query query = new Query().setPageCount(1);
final JSONObject result = tagRepository.get(query);
final JSONArray tagArray = result.optJSONArray(Keys.RESULTS);
return CollectionUtils.jsonArrayToList(tagArray);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets tags failed", e);
throw new ServiceException(e);
}
}
use of org.json.JSONArray in project solo by b3log.
the class TagQueryService method getTopTags.
/**
* Gets top (reference count descending) tags.
*
* @param fetchSize the specified fetch size
* @return for example, <pre>
* [
* {"tagTitle": "", "tagReferenceCount": int, ....},
* ....
* ]
* </pre>, returns an empty list if not found
*
* @throws ServiceException service exception
*/
public List<JSONObject> getTopTags(final int fetchSize) throws ServiceException {
try {
final Query query = new Query().setPageCount(1).setPageSize(fetchSize).addSort(Tag.TAG_PUBLISHED_REFERENCE_COUNT, SortDirection.DESCENDING);
final JSONObject result = tagRepository.get(query);
final JSONArray tagArray = result.optJSONArray(Keys.RESULTS);
return CollectionUtils.jsonArrayToList(tagArray);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets top tags failed", e);
throw new ServiceException(e);
}
}
use of org.json.JSONArray in project solo by b3log.
the class MetaWeblogAPI method parsetPost.
/**
* Parses the specified method call for an article.
*
* @param methodCall the specified method call
* @return article
* @throws Exception exception
*/
private JSONObject parsetPost(final JSONObject methodCall) throws Exception {
final JSONObject ret = new JSONObject();
final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");
final JSONObject post = params.getJSONObject(INDEX_POST).getJSONObject("value").getJSONObject("struct");
final JSONArray members = post.getJSONArray("member");
for (int i = 0; i < members.length(); i++) {
final JSONObject member = members.getJSONObject(i);
final String name = member.getString("name");
if ("dateCreated".equals(name)) {
final String dateString = member.getJSONObject("value").getString("dateTime.iso8601");
Date date;
try {
date = (Date) DateFormatUtils.ISO_DATETIME_FORMAT.parseObject(dateString);
} catch (final ParseException e) {
LOGGER.log(Level.WARN, "Parses article create date failed with ISO8601, retry to parse with " + "pattern[yyyy-MM-dd'T'HH:mm:ss, yyyyMMdd'T'HH:mm:ss'Z']");
date = DateUtils.parseDate(dateString, new String[] { "yyyyMMdd'T'HH:mm:ss", "yyyyMMdd'T'HH:mm:ss'Z'" });
}
ret.put(Article.ARTICLE_CREATE_DATE, date);
} else if ("title".equals(name)) {
ret.put(Article.ARTICLE_TITLE, member.getJSONObject("value").getString("string"));
} else if ("description".equals(name)) {
final String content = member.getJSONObject("value").getString("string");
ret.put(Article.ARTICLE_CONTENT, content);
final String plainTextContent = Jsoup.parse(content).text();
if (plainTextContent.length() > ARTICLE_ABSTRACT_LENGTH) {
ret.put(Article.ARTICLE_ABSTRACT, plainTextContent.substring(0, ARTICLE_ABSTRACT_LENGTH));
} else {
ret.put(Article.ARTICLE_ABSTRACT, plainTextContent);
}
} else if ("categories".equals(name)) {
final StringBuilder tagBuilder = new StringBuilder();
final JSONObject data = member.getJSONObject("value").getJSONObject("array").getJSONObject("data");
if (0 == data.length()) {
throw new Exception("At least one Tag");
}
final Object value = data.get("value");
if (value instanceof JSONArray) {
final JSONArray tags = (JSONArray) value;
for (int j = 0; j < tags.length(); j++) {
final String tagTitle = tags.getJSONObject(j).getString("string");
tagBuilder.append(tagTitle);
if (j < tags.length() - 1) {
tagBuilder.append(",");
}
}
} else {
final JSONObject tag = (JSONObject) value;
tagBuilder.append(tag.getString("string"));
}
ret.put(Article.ARTICLE_TAGS_REF, tagBuilder.toString());
}
}
final boolean publish = 1 == params.getJSONObject(INDEX_PUBLISH).getJSONObject("value").getInt("boolean") ? true : false;
ret.put(Article.ARTICLE_IS_PUBLISHED, publish);
ret.put(Article.ARTICLE_COMMENTABLE, true);
ret.put(Article.ARTICLE_VIEW_PWD, "");
return ret;
}
use of org.json.JSONArray in project platform_frameworks_base by android.
the class AccountSyncSettingsBackupHelper method restoreFromJsonArray.
private void restoreFromJsonArray(JSONArray accountJSONArray) throws JSONException {
HashSet<Account> currentAccounts = getAccounts();
JSONArray unaddedAccountsJSONArray = new JSONArray();
for (int i = 0; i < accountJSONArray.length(); i++) {
JSONObject accountJSON = (JSONObject) accountJSONArray.get(i);
String accountName = accountJSON.getString(KEY_ACCOUNT_NAME);
String accountType = accountJSON.getString(KEY_ACCOUNT_TYPE);
Account account = null;
try {
account = new Account(accountName, accountType);
} catch (IllegalArgumentException iae) {
continue;
}
// yet won't be restored.
if (currentAccounts.contains(account)) {
if (DEBUG)
Log.i(TAG, "Restoring Sync Settings for" + accountName);
restoreExistingAccountSyncSettingsFromJSON(accountJSON);
} else {
unaddedAccountsJSONArray.put(accountJSON);
}
}
if (unaddedAccountsJSONArray.length() > 0) {
try (FileOutputStream fOutput = new FileOutputStream(STASH_FILE)) {
String jsonString = unaddedAccountsJSONArray.toString();
DataOutputStream out = new DataOutputStream(fOutput);
out.writeUTF(jsonString);
} catch (IOException ioe) {
// Error in writing to stash file
Log.e(TAG, "unable to write the sync settings to the stash file", ioe);
}
} else {
File stashFile = new File(STASH_FILE);
if (stashFile.exists())
stashFile.delete();
}
}
Aggregations