/** * Shows update article. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/update", method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, LoginCheck.class}) @After(adviceClass = {CSRFToken.class, StopwatchEndAdvice.class}) public void showUpdateArticle( final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String articleId = request.getParameter("id"); if (Strings.isEmptyOrNull(articleId)) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final JSONObject article = articleQueryService.getArticleById(articleId); if (null == article) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final JSONObject currentUser = Sessions.currentUser(request); if (null == currentUser || !currentUser .optString(Keys.OBJECT_ID) .equals(article.optString(Article.ARTICLE_AUTHOR_ID))) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } final AbstractFreeMarkerRenderer renderer = new SkinRenderer(); context.setRenderer(renderer); renderer.setTemplateName("/home/post.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); dataModel.put(Article.ARTICLE, article); filler.fillHeaderAndFooter(request, response, 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")); }
/** * Shows pre-add article. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/pre-post", method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, LoginCheck.class}) @After(adviceClass = {CSRFToken.class, StopwatchEndAdvice.class}) public void showPreAddArticle( final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(); context.setRenderer(renderer); renderer.setTemplateName("/home/pre-post.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); filler.fillHeaderAndFooter(request, response, dataModel); }
/** * Render a page template with the destination URL. * * @param context the context * @param pageTemplate the page template * @param destinationURL the destination URL * @param request for reset password page * @throws JSONException the JSONException * @throws ServiceException the ServiceException */ private void renderPage( final HTTPRequestContext context, final String pageTemplate, final String destinationURL, final HttpServletRequest request) throws JSONException, ServiceException { final AbstractFreeMarkerRenderer renderer = new ConsoleRenderer(); renderer.setTemplateName(pageTemplate); context.setRenderer(renderer); final Map<String, Object> dataModel = renderer.getDataModel(); final Map<String, String> langs = langPropsService.getAll(Latkes.getLocale()); final JSONObject preference = preferenceQueryService.getPreference(); dataModel.putAll(langs); dataModel.put(Common.GOTO, destinationURL); dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR))); dataModel.put(Common.VERSION, SoloServletListener.VERSION); dataModel.put(Common.STATIC_RESOURCE_VERSION, Latkes.getStaticResourceVersion()); dataModel.put(Preference.BLOG_TITLE, preference.getString(Preference.BLOG_TITLE)); final String token = request.getParameter("token"); final String email = request.getParameter("login"); final JSONObject tokenObj = optionQueryService.getOptionById(token); if (tokenObj == null) { dataModel.put("inputType", "email"); } else { // TODO verify the expired time in the tokenObj dataModel.put("inputType", "password"); dataModel.put("userEmailHidden", email); } final String from = request.getParameter("from"); if ("forgot".equals(from)) { dataModel.put("resetMsg", langPropsService.get("resetPwdSuccessSend")); } else if ("reset".equals(from)) { dataModel.put("resetMsg", langPropsService.get("resetPwdSuccessMsg")); } else { dataModel.put("resetMsg", ""); } Keys.fillRuntime(dataModel); filler.fillMinified(dataModel); }
/** * 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); }
/** * Shows add article. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/post", method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, LoginCheck.class}) @After(adviceClass = {CSRFToken.class, StopwatchEndAdvice.class}) public void showAddArticle( final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(); context.setRenderer(renderer); renderer.setTemplateName("/home/post.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); // 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")); String tags = request.getParameter(Tag.TAGS); if (StringUtils.isBlank(tags)) { tags = ""; dataModel.put(Tag.TAGS, tags); } else { tags = articleMgmtService.formatArticleTags(tags); final String[] tagTitles = tags.split(","); final StringBuilder tagBuilder = new StringBuilder(); for (final String title : tagTitles) { final String tagTitle = title.trim(); if (Strings.isEmptyOrNull(tagTitle)) { continue; } if (!Tag.TAG_TITLE_PATTERN.matcher(tagTitle).matches()) { continue; } if (Strings.isEmptyOrNull(tagTitle) || tagTitle.length() > Tag.MAX_TAG_TITLE_LENGTH || tagTitle.length() < 1) { continue; } final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER); if (!Role.ADMIN_ROLE.equals(currentUser.optString(User.USER_ROLE)) && ArrayUtils.contains(Symphonys.RESERVED_TAGS, tagTitle)) { continue; } tagBuilder.append(tagTitle).append(","); } if (tagBuilder.length() > 0) { tagBuilder.deleteCharAt(tagBuilder.length() - 1); } dataModel.put(Tag.TAGS, tagBuilder.toString()); } final String type = request.getParameter(Common.TYPE); if (StringUtils.isBlank(type)) { dataModel.put(Article.ARTICLE_TYPE, Article.ARTICLE_TYPE_C_NORMAL); } else { int articleType = Article.ARTICLE_TYPE_C_NORMAL; try { articleType = Integer.valueOf(type); } catch (final Exception e) { LOGGER.log(Level.WARN, "Gets article type error [" + type + "]", e); } if (Article.isInvalidArticleType(articleType)) { articleType = Article.ARTICLE_TYPE_C_NORMAL; } dataModel.put(Article.ARTICLE_TYPE, articleType); } filler.fillHeaderAndFooter(request, response, dataModel); }
/** * 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()); } } }