/** * Gets links by the specified request json object. * * @param requestJSONObject the specified request json object, for example, * <pre> * { * "paginationCurrentPageNum": 1, * "paginationPageSize": 20, * "paginationWindowSize": 10 * }, see {@link Pagination} for more details * </pre> * * @return for example, * <pre> * { * "pagination": { * "paginationPageCount": 100, * "paginationPageNums": [1, 2, 3, 4, 5] * }, * "links": [{ * "oId": "", * "linkTitle": "", * "linkAddress": "", * ""linkDescription": "" * }, ....] * } * </pre> * * @throws ServiceException service exception * @see Pagination */ public JSONObject getLinks(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 Query query = new Query() .setCurrentPageNum(currentPageNum) .setPageSize(pageSize) .addSort(Link.LINK_ORDER, SortDirection.ASCENDING); final JSONObject result = linkRepository.get(query); final int pageCount = result.getJSONObject(Pagination.PAGINATION).getInt(Pagination.PAGINATION_PAGE_COUNT); final JSONObject pagination = new JSONObject(); 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 links = result.getJSONArray(Keys.RESULTS); ret.put(Pagination.PAGINATION, pagination); ret.put(Link.LINKS, links); return ret; } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets links failed", e); throw new ServiceException(e); } }
/** * Gets users by the specified request json object. * * @param requestJSONObject the specified request json object, for example, * <pre> * { * "paginationCurrentPageNum": 1, * "paginationPageSize": 20, * "paginationWindowSize": 10, * }, see {@link Pagination} for more details * </pre> * * @return for example, * <pre> * { * "pagination": { * "paginationPageCount": 100, * "paginationPageNums": [1, 2, 3, 4, 5] * }, * "users": [{ * "oId": "", * "userName": "", * "userEmail": "", * "userPassword": "", * "roleName": "" * }, ....] * } * </pre> * * @throws ServiceException service exception * @see Pagination */ public JSONObject getUsers(final JSONObject requestJSONObject) throws ServiceException { final JSONObject ret = new JSONObject(); final int currentPageNum = requestJSONObject.optInt(Pagination.PAGINATION_CURRENT_PAGE_NUM); final int pageSize = requestJSONObject.optInt(Pagination.PAGINATION_PAGE_SIZE); final int windowSize = requestJSONObject.optInt(Pagination.PAGINATION_WINDOW_SIZE); final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize); JSONObject result = null; try { result = userRepository.get(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets users failed", e); throw new ServiceException(e); } final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT); 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 users = result.optJSONArray(Keys.RESULTS); ret.put(User.USERS, users); return ret; }
/** * Shows article with the specified article id. * * @param context the specified context * @param request the specified request * @param response the specified response * @param articleId the specified article id * @throws Exception exception */ @RequestProcessing(value = "/article/{articleId}", method = HTTPRequestMethod.GET) @Before(adviceClass = StopwatchStartAdvice.class) @After(adviceClass = {CSRFToken.class, StopwatchEndAdvice.class}) public void showArticle( final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response, final String articleId) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(); context.setRenderer(renderer); renderer.setTemplateName("/article.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); final JSONObject article = articleQueryService.getArticleById(articleId); if (null == article) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final HttpSession session = request.getSession(false); if (null != session) { session.setAttribute(Article.ARTICLE_T_ID, articleId); } filler.fillHeaderAndFooter(request, response, dataModel); final String authorEmail = article.optString(Article.ARTICLE_AUTHOR_EMAIL); final JSONObject author = userQueryService.getUserByEmail(authorEmail); article.put(Article.ARTICLE_T_AUTHOR_NAME, author.optString(User.USER_NAME)); article.put(Article.ARTICLE_T_AUTHOR_URL, author.optString(User.USER_URL)); article.put(Article.ARTICLE_T_AUTHOR_INTRO, author.optString(UserExt.USER_INTRO)); dataModel.put(Article.ARTICLE, article); article.put(Common.IS_MY_ARTICLE, false); article.put(Article.ARTICLE_T_AUTHOR, author); article.put(Common.REWARDED, false); articleQueryService.processArticleContent(article, request); final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN); JSONObject currentUser; String currentUserId = null; if (isLoggedIn) { currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER); currentUserId = currentUser.optString(Keys.OBJECT_ID); article.put( Common.IS_MY_ARTICLE, currentUserId.equals(article.optString(Article.ARTICLE_AUTHOR_ID))); final boolean isFollowing = followQueryService.isFollowing(currentUserId, articleId); dataModel.put(Common.IS_FOLLOWING, isFollowing); final int vote = voteQueryService.isVoted(currentUserId, articleId); dataModel.put(Vote.VOTE, vote); if (currentUserId.equals(author.optString(Keys.OBJECT_ID))) { article.put(Common.REWARDED, true); } else { article.put( Common.REWARDED, rewardQueryService.isRewarded(currentUserId, articleId, Reward.TYPE_C_ARTICLE)); } } if (!(Boolean) request.getAttribute(Keys.HttpRequest.IS_SEARCH_ENGINE_BOT)) { articleMgmtService.incArticleViewCount(articleId); } filler.fillRelevantArticles(dataModel, article); filler.fillRandomArticles(dataModel); filler.fillHotArticles(dataModel); // Qiniu file upload authenticate final Auth auth = Auth.create(Symphonys.get("qiniu.accessKey"), Symphonys.get("qiniu.secretKey")); final String uploadToken = auth.uploadToken(Symphonys.get("qiniu.bucket")); dataModel.put("qiniuUploadToken", uploadToken); dataModel.put("qiniuDomain", Symphonys.get("qiniu.domain")); dataModel.put(Common.DISCUSSION_VIEWABLE, article.optBoolean(Common.DISCUSSION_VIEWABLE)); if (!article.optBoolean(Common.DISCUSSION_VIEWABLE)) { article.put(Article.ARTICLE_T_COMMENTS, (Object) Collections.emptyList()); return; } String pageNumStr = request.getParameter("p"); if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) { pageNumStr = "1"; } final int pageNum = Integer.valueOf(pageNumStr); final int pageSize = Symphonys.getInt("articleCommentsPageSize"); final int windowSize = Symphonys.getInt("articleCommentsWindowSize"); final List<JSONObject> articleComments = commentQueryService.getArticleComments(articleId, pageNum, pageSize); article.put(Article.ARTICLE_T_COMMENTS, (Object) articleComments); // Fill reward(thank) for (final JSONObject comment : articleComments) { String thankTemplate = langPropsService.get("thankConfirmLabel"); thankTemplate = thankTemplate .replace("{point}", String.valueOf(Symphonys.getInt("pointThankComment"))) .replace( "{user}", comment.optJSONObject(Comment.COMMENT_T_COMMENTER).optString(User.USER_NAME)); comment.put(Comment.COMMENT_T_THANK_LABEL, thankTemplate); final String commentId = comment.optString(Keys.OBJECT_ID); if (isLoggedIn) { comment.put( Common.REWARDED, rewardQueryService.isRewarded(currentUserId, commentId, Reward.TYPE_C_COMMENT)); } comment.put( Common.REWARED_COUNT, rewardQueryService.rewardedCount(commentId, Reward.TYPE_C_COMMENT)); } final int commentCnt = article.getInt(Article.ARTICLE_COMMENT_CNT); final int pageCount = (int) Math.ceil((double) commentCnt / (double) pageSize); final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize); if (!pageNums.isEmpty()) { dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0)); dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1)); } dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum); dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); dataModel.put(Common.ARTICLE_COMMENTS_PAGE_SIZE, pageSize); }
/** * Gets comments by the specified request json object. * * @param requestJSONObject the specified request json object, for example, * <pre> * { * "paginationCurrentPageNum": 1, * "paginationPageSize": 20, * "paginationWindowSize": 10, * }, see {@link Pagination} for more details * </pre> * * @param commentFields the specified article fields to return * @return for example, * <pre> * { * "pagination": { * "paginationPageCount": 100, * "paginationPageNums": [1, 2, 3, 4, 5] * }, * "comments": [{ * "oId": "", * "commentContent": "", * "commentCreateTime": "", * .... * }, ....] * } * </pre> * * @throws ServiceException service exception * @see Pagination */ public JSONObject getComments( final JSONObject requestJSONObject, final Map<String, Class<?>> commentFields) throws ServiceException { final JSONObject ret = new JSONObject(); final int currentPageNum = requestJSONObject.optInt(Pagination.PAGINATION_CURRENT_PAGE_NUM); final int pageSize = requestJSONObject.optInt(Pagination.PAGINATION_PAGE_SIZE); final int windowSize = requestJSONObject.optInt(Pagination.PAGINATION_WINDOW_SIZE); final Query query = new Query() .setCurrentPageNum(currentPageNum) .setPageSize(pageSize) .addSort(Comment.COMMENT_CREATE_TIME, SortDirection.DESCENDING); for (final Map.Entry<String, Class<?>> commentField : commentFields.entrySet()) { query.addProjection(commentField.getKey(), commentField.getValue()); } JSONObject result = null; try { result = commentRepository.get(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets comments failed", e); throw new ServiceException(e); } final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT); 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 data = result.optJSONArray(Keys.RESULTS); final List<JSONObject> comments = CollectionUtils.<JSONObject>jsonArrayToList(data); try { for (final JSONObject comment : comments) { organizeComment(comment); final String articleId = comment.optString(Comment.COMMENT_ON_ARTICLE_ID); final JSONObject article = articleRepository.get(articleId); comment.put( Comment.COMMENT_T_ARTICLE_TITLE, Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS) ? langPropsService.get("articleTitleBlockLabel") : Emotions.convert(article.optString(Article.ARTICLE_TITLE))); comment.put( Comment.COMMENT_T_ARTICLE_PERMALINK, article.optString(Article.ARTICLE_PERMALINK)); } } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Organizes comments failed", e); throw new ServiceException(e); } ret.put(Comment.COMMENTS, comments); return ret; }
/** * Shows articles related with a tag with the specified context. * * @param context the specified context * @throws IOException io exception */ @RequestProcessing(value = "/tags/**", method = HTTPRequestMethod.GET) public void showTagArticles(final HTTPRequestContext context) throws IOException { final AbstractFreeMarkerRenderer renderer = new FreeMarkerRenderer(); context.setRenderer(renderer); renderer.setTemplateName("tag-articles.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); final HttpServletRequest request = context.getRequest(); final HttpServletResponse response = context.getResponse(); try { String requestURI = request.getRequestURI(); if (!requestURI.endsWith("/")) { requestURI += "/"; } String tagTitle = getTagTitle(requestURI); final int currentPageNum = getCurrentPageNum(requestURI, tagTitle); if (-1 == currentPageNum) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } LOGGER.log( Level.DEBUG, "Tag[title={0}, currentPageNum={1}]", new Object[] {tagTitle, currentPageNum}); tagTitle = URLDecoder.decode(tagTitle, "UTF-8"); final JSONObject result = tagQueryService.getTagByTitle(tagTitle); if (null == result) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final JSONObject tag = result.getJSONObject(Tag.TAG); final String tagId = tag.getString(Keys.OBJECT_ID); final JSONObject preference = preferenceQueryService.getPreference(); Skins.fillLangs( preference.optString(Option.ID_C_LOCALE_STRING), (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), dataModel); final int pageSize = preference.getInt(Option.ID_C_ARTICLE_LIST_DISPLAY_COUNT); final int windowSize = preference.getInt(Option.ID_C_ARTICLE_LIST_PAGINATION_WINDOW_SIZE); final List<JSONObject> articles = articleQueryService.getArticlesByTag(tagId, currentPageNum, pageSize); if (articles.isEmpty()) { try { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (final IOException ex) { LOGGER.error(ex.getMessage()); } } final boolean hasMultipleUsers = userQueryService.hasMultipleUsers(); if (hasMultipleUsers) { filler.setArticlesExProperties(request, articles, preference); } else { // All articles composed by the same author final JSONObject author = articleQueryService.getAuthor(articles.get(0)); filler.setArticlesExProperties(request, articles, author, preference); } final int tagArticleCount = tag.getInt(Tag.TAG_PUBLISHED_REFERENCE_COUNT); final int pageCount = (int) Math.ceil((double) tagArticleCount / (double) pageSize); LOGGER.log( Level.TRACE, "Paginate tag-articles[currentPageNum={0}, pageSize={1}, pageCount={2}, windowSize={3}]", new Object[] {currentPageNum, pageSize, pageCount, windowSize}); final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize); LOGGER.log(Level.TRACE, "tag-articles[pageNums={0}]", pageNums); Collections.sort(articles, Comparators.ARTICLE_CREATE_DATE_COMPARATOR); fillPagination(dataModel, pageCount, currentPageNum, articles, pageNums); dataModel.put(Common.PATH, "/tags/" + URLEncoder.encode(tagTitle, "UTF-8")); dataModel.put(Keys.OBJECT_ID, tagId); dataModel.put(Tag.TAG, tag); filler.fillSide(request, dataModel, preference); filler.fillBlogHeader(request, response, dataModel, preference); filler.fillBlogFooter(request, dataModel, preference); statisticMgmtService.incBlogViewCount(request, response); } catch (final ServiceException e) { LOGGER.log(Level.ERROR, e.getMessage(), e); try { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (final IOException ex) { LOGGER.error(ex.getMessage()); } } catch (final JSONException e) { LOGGER.log(Level.ERROR, e.getMessage(), e); try { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (final IOException ex) { LOGGER.error(ex.getMessage()); } } }