Search in sources :

Example 36 with Before

use of org.b3log.latke.servlet.annotation.Before in project symphony by b3log.

the class ArticleProcessor method reward.

/**
 * Article rewards.
 *
 * @param request  the specified http servlet request
 * @param response the specified http servlet response
 * @param context  the specified http request context
 * @throws Exception exception
 */
@RequestProcessing(value = "/article/reward", method = HTTPRequestMethod.POST)
@Before(adviceClass = StopwatchStartAdvice.class)
@After(adviceClass = StopwatchEndAdvice.class)
public void reward(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) throws Exception {
    final JSONObject currentUser = userQueryService.getCurrentUser(request);
    if (null == currentUser) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    final String articleId = request.getParameter(Article.ARTICLE_T_ID);
    if (Strings.isEmptyOrNull(articleId)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    context.renderJSON();
    try {
        articleMgmtService.reward(articleId, currentUser.optString(Keys.OBJECT_ID));
    } catch (final ServiceException e) {
        context.renderMsg(langPropsService.get("transferFailLabel"));
        return;
    }
    final JSONObject article = articleQueryService.getArticle(articleId);
    articleQueryService.processArticleContent(article, request);
    String markdownText = article.optString(Article.ARTICLE_REWARD_CONTENT);
    markdownText = shortLinkQueryService.linkArticle(markdownText);
    markdownText = shortLinkQueryService.linkTag(markdownText);
    markdownText = Emotions.toAliases(markdownText);
    markdownText = Emotions.convert(markdownText);
    markdownText = Markdowns.toHTML(markdownText);
    markdownText = Markdowns.clean(markdownText, "");
    context.renderTrueResult().renderJSONValue(Article.ARTICLE_REWARD_CONTENT, markdownText);
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) Before(org.b3log.latke.servlet.annotation.Before) After(org.b3log.latke.servlet.annotation.After) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 37 with Before

use of org.b3log.latke.servlet.annotation.Before in project symphony by b3log.

the class ArticleProcessor method addArticle.

/**
 * Adds an article locally.
 * <p>
 * The request json object (an article):
 * <pre>
 * {
 *   "articleTitle": "",
 *   "articleTags": "", // Tags spliting by ','
 *   "articleContent": "",
 *   "articleCommentable": boolean,
 *   "articleType": int,
 *   "articleRewardContent": "",
 *   "articleRewardPoint": int,
 *   "articleAnonymous": boolean
 * }
 * </pre>
 * </p>
 *
 * @param context the specified context
 * @param request the specified request
 */
@RequestProcessing(value = "/article", method = HTTPRequestMethod.POST)
@Before(adviceClass = { StopwatchStartAdvice.class, LoginCheck.class, CSRFCheck.class, ArticleAddValidation.class, PermissionCheck.class })
@After(adviceClass = StopwatchEndAdvice.class)
public void addArticle(final HTTPRequestContext context, final HttpServletRequest request, final JSONObject requestJSONObject) {
    context.renderJSON();
    final String articleTitle = requestJSONObject.optString(Article.ARTICLE_TITLE);
    String articleTags = requestJSONObject.optString(Article.ARTICLE_TAGS);
    final String articleContent = requestJSONObject.optString(Article.ARTICLE_CONTENT);
    // final boolean articleCommentable = requestJSONObject.optBoolean(Article.ARTICLE_COMMENTABLE);
    final boolean articleCommentable = true;
    final int articleType = requestJSONObject.optInt(Article.ARTICLE_TYPE, Article.ARTICLE_TYPE_C_NORMAL);
    final String articleRewardContent = requestJSONObject.optString(Article.ARTICLE_REWARD_CONTENT);
    final int articleRewardPoint = requestJSONObject.optInt(Article.ARTICLE_REWARD_POINT);
    final String ip = Requests.getRemoteAddr(request);
    String ua = request.getHeader(Common.USER_AGENT);
    final boolean isAnonymous = requestJSONObject.optBoolean(Article.ARTICLE_ANONYMOUS, false);
    final int articleAnonymous = isAnonymous ? Article.ARTICLE_ANONYMOUS_C_ANONYMOUS : Article.ARTICLE_ANONYMOUS_C_PUBLIC;
    final boolean syncWithSymphonyClient = requestJSONObject.optBoolean(Article.ARTICLE_SYNC_TO_CLIENT, false);
    final JSONObject article = new JSONObject();
    article.put(Article.ARTICLE_TITLE, articleTitle);
    article.put(Article.ARTICLE_CONTENT, articleContent);
    article.put(Article.ARTICLE_EDITOR_TYPE, 0);
    article.put(Article.ARTICLE_COMMENTABLE, articleCommentable);
    article.put(Article.ARTICLE_TYPE, articleType);
    article.put(Article.ARTICLE_REWARD_CONTENT, articleRewardContent);
    article.put(Article.ARTICLE_REWARD_POINT, articleRewardPoint);
    article.put(Article.ARTICLE_IP, "");
    if (StringUtils.isNotBlank(ip)) {
        article.put(Article.ARTICLE_IP, ip);
    }
    article.put(Article.ARTICLE_UA, "");
    if (StringUtils.isNotBlank(ua)) {
        ua = Jsoup.clean(ua, Whitelist.none());
        article.put(Article.ARTICLE_UA, ua);
    }
    article.put(Article.ARTICLE_ANONYMOUS, articleAnonymous);
    article.put(Article.ARTICLE_SYNC_TO_CLIENT, syncWithSymphonyClient);
    try {
        final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER);
        article.put(Article.ARTICLE_AUTHOR_ID, currentUser.optString(Keys.OBJECT_ID));
        if (!Role.ROLE_ID_C_ADMIN.equals(currentUser.optString(User.USER_ROLE))) {
            articleTags = articleMgmtService.filterReservedTags(articleTags);
        }
        if (Article.ARTICLE_TYPE_C_DISCUSSION == articleType && StringUtils.isBlank(articleTags)) {
            articleTags = "小黑屋";
        }
        if (Article.ARTICLE_TYPE_C_THOUGHT == articleType && StringUtils.isBlank(articleTags)) {
            articleTags = "思绪";
        }
        article.put(Article.ARTICLE_TAGS, articleTags);
        final String articleId = articleMgmtService.addArticle(article);
        context.renderJSONValue(Keys.STATUS_CODE, StatusCodes.SUCC);
        context.renderJSONValue(Article.ARTICLE_T_ID, articleId);
    } catch (final ServiceException e) {
        final String msg = e.getMessage();
        LOGGER.log(Level.ERROR, "Adds article[title=" + articleTitle + "] failed: {0}", e.getMessage());
        context.renderMsg(msg);
        context.renderJSONValue(Keys.STATUS_CODE, StatusCodes.ERR);
    }
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) Before(org.b3log.latke.servlet.annotation.Before) After(org.b3log.latke.servlet.annotation.After) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 38 with Before

use of org.b3log.latke.servlet.annotation.Before in project symphony by b3log.

the class ArticleProcessor method checkArticleTitle.

/**
 * Checks article title.
 *
 * @param context  the specified context
 * @param request  the specified request
 * @param response the specified response
 * @throws Exception exception
 */
@RequestProcessing(value = "/article/check-title", method = HTTPRequestMethod.POST)
@Before(adviceClass = { StopwatchStartAdvice.class, LoginCheck.class })
@After(adviceClass = { StopwatchEndAdvice.class })
public void checkArticleTitle(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER);
    final String currentUserId = currentUser.optString(Keys.OBJECT_ID);
    final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, context.getResponse());
    String title = requestJSONObject.optString(Article.ARTICLE_TITLE);
    title = StringUtils.trim(title);
    String id = requestJSONObject.optString(Article.ARTICLE_T_ID);
    final JSONObject article = articleQueryService.getArticleByTitle(title);
    if (null == article) {
        context.renderJSON(true);
        return;
    }
    if (StringUtils.isBlank(id)) {
        // Add
        final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID);
        String msg;
        if (authorId.equals(currentUserId)) {
            msg = langPropsService.get("duplicatedArticleTitleSelfLabel");
            msg = msg.replace("{article}", "<a target='_blank' href='/article/" + article.optString(Keys.OBJECT_ID) + "'>" + title + "</a>");
        } else {
            final JSONObject author = userQueryService.getUser(authorId);
            final String userName = author.optString(User.USER_NAME);
            msg = langPropsService.get("duplicatedArticleTitleLabel");
            msg = msg.replace("{user}", "<a target='_blank' href='/member/" + userName + "'>" + userName + "</a>");
            msg = msg.replace("{article}", "<a target='_blank' href='/article/" + article.optString(Keys.OBJECT_ID) + "'>" + title + "</a>");
        }
        final JSONObject ret = new JSONObject();
        ret.put(Keys.STATUS_CODE, false);
        ret.put(Keys.MSG, msg);
        context.renderJSON(ret);
    } else {
        // Update
        final JSONObject oldArticle = articleQueryService.getArticle(id);
        if (oldArticle.optString(Article.ARTICLE_TITLE).equals(title)) {
            context.renderJSON(true);
            return;
        }
        final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID);
        String msg;
        if (authorId.equals(currentUserId)) {
            msg = langPropsService.get("duplicatedArticleTitleSelfLabel");
            msg = msg.replace("{article}", "<a target='_blank' href='/article/" + article.optString(Keys.OBJECT_ID) + "'>" + title + "</a>");
        } else {
            final JSONObject author = userQueryService.getUser(authorId);
            final String userName = author.optString(User.USER_NAME);
            msg = langPropsService.get("duplicatedArticleTitleLabel");
            msg = msg.replace("{user}", "<a target='_blank' href='/member/" + userName + "'>" + userName + "</a>");
            msg = msg.replace("{article}", "<a target='_blank' href='/article/" + article.optString(Keys.OBJECT_ID) + "'>" + title + "</a>");
        }
        final JSONObject ret = new JSONObject();
        ret.put(Keys.STATUS_CODE, false);
        ret.put(Keys.MSG, msg);
        context.renderJSON(ret);
    }
}
Also used : JSONObject(org.json.JSONObject) Before(org.b3log.latke.servlet.annotation.Before) After(org.b3log.latke.servlet.annotation.After) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 39 with Before

use of org.b3log.latke.servlet.annotation.Before in project symphony by b3log.

the class IndexProcessor method showRecent.

/**
 * Shows recent articles.
 *
 * @param context  the specified context
 * @param request  the specified request
 * @param response the specified response
 * @throws Exception exception
 */
@RequestProcessing(value = { "/recent", "/recent/hot", "/recent/good", "/recent/reply" }, method = HTTPRequestMethod.GET)
@Before(adviceClass = { StopwatchStartAdvice.class, AnonymousViewCheck.class })
@After(adviceClass = { PermissionGrant.class, StopwatchEndAdvice.class })
public void showRecent(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
    context.setRenderer(renderer);
    renderer.setTemplateName("recent.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();
    String pageNumStr = request.getParameter("p");
    if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
        pageNumStr = "1";
    }
    final int pageNum = Integer.valueOf(pageNumStr);
    int pageSize = Symphonys.getInt("indexArticlesCnt");
    final JSONObject user = userQueryService.getCurrentUser(request);
    if (null != user) {
        pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE);
        if (!UserExt.finshedGuide(user)) {
            response.sendRedirect(Latkes.getServePath() + "/guide");
            return;
        }
    }
    final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
    String sortModeStr = StringUtils.substringAfter(request.getRequestURI(), "/recent");
    int sortMode;
    switch(sortModeStr) {
        case "":
            sortMode = 0;
            break;
        case "/hot":
            sortMode = 1;
            break;
        case "/good":
            sortMode = 2;
            break;
        case "/reply":
            sortMode = 3;
            break;
        default:
            sortMode = 0;
    }
    dataModel.put(Common.SELECTED, Common.RECENT);
    final JSONObject result = articleQueryService.getRecentArticles(avatarViewMode, sortMode, pageNum, pageSize);
    final List<JSONObject> allArticles = (List<JSONObject>) result.get(Article.ARTICLES);
    final List<JSONObject> stickArticles = new ArrayList<>();
    final Iterator<JSONObject> iterator = allArticles.iterator();
    while (iterator.hasNext()) {
        final JSONObject article = iterator.next();
        final boolean stick = article.optInt(Article.ARTICLE_T_STICK_REMAINS) > 0;
        article.put(Article.ARTICLE_T_IS_STICK, stick);
        if (stick) {
            stickArticles.add(article);
            iterator.remove();
        }
    }
    dataModel.put(Common.STICK_ARTICLES, stickArticles);
    dataModel.put(Common.LATEST_ARTICLES, allArticles);
    final JSONObject pagination = result.getJSONObject(Pagination.PAGINATION);
    final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT);
    final List<Integer> pageNums = (List<Integer>) pagination.get(Pagination.PAGINATION_PAGE_NUMS);
    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);
    dataModelService.fillHeaderAndFooter(request, response, dataModel);
    dataModelService.fillRandomArticles(avatarViewMode, dataModel);
    dataModelService.fillSideHotArticles(avatarViewMode, dataModel);
    dataModelService.fillSideTags(dataModel);
    dataModelService.fillLatestCmts(dataModel);
    dataModel.put(Common.CURRENT, StringUtils.substringAfter(request.getRequestURI(), "/recent"));
}
Also used : AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) Before(org.b3log.latke.servlet.annotation.Before) After(org.b3log.latke.servlet.annotation.After) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 40 with Before

use of org.b3log.latke.servlet.annotation.Before in project symphony by b3log.

the class IndexProcessor method showIndex.

/**
 * Shows index.
 *
 * @param context  the specified context
 * @param request  the specified request
 * @param response the specified response
 * @throws Exception exception
 */
@RequestProcessing(value = { "", "/" }, method = HTTPRequestMethod.GET)
@Before(adviceClass = { StopwatchStartAdvice.class })
@After(adviceClass = { PermissionGrant.class, StopwatchEndAdvice.class })
public void showIndex(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
    context.setRenderer(renderer);
    renderer.setTemplateName("index.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();
    final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
    final List<JSONObject> recentArticles = articleQueryService.getIndexRecentArticles(avatarViewMode);
    dataModel.put(Common.RECENT_ARTICLES, recentArticles);
    JSONObject currentUser = userQueryService.getCurrentUser(request);
    if (null == currentUser) {
        userMgmtService.tryLogInWithCookie(request, context.getResponse());
    }
    currentUser = userQueryService.getCurrentUser(request);
    if (null != currentUser) {
        if (!UserExt.finshedGuide(currentUser)) {
            response.sendRedirect(Latkes.getServePath() + "/guide");
            return;
        }
        final String userId = currentUser.optString(Keys.OBJECT_ID);
        final int pageSize = Symphonys.getInt("indexArticlesCnt");
        final List<JSONObject> followingTagArticles = articleQueryService.getFollowingTagArticles(avatarViewMode, userId, 1, pageSize);
        dataModel.put(Common.FOLLOWING_TAG_ARTICLES, followingTagArticles);
        final List<JSONObject> followingUserArticles = articleQueryService.getFollowingUserArticles(avatarViewMode, userId, 1, pageSize);
        dataModel.put(Common.FOLLOWING_USER_ARTICLES, followingUserArticles);
    } else {
        dataModel.put(Common.FOLLOWING_TAG_ARTICLES, Collections.emptyList());
        dataModel.put(Common.FOLLOWING_USER_ARTICLES, Collections.emptyList());
    }
    final List<JSONObject> perfectArticles = articleQueryService.getIndexPerfectArticles(avatarViewMode);
    dataModel.put(Common.PERFECT_ARTICLES, perfectArticles);
    dataModel.put(Common.SELECTED, Common.INDEX);
    dataModelService.fillHeaderAndFooter(request, response, dataModel);
    dataModelService.fillIndexTags(dataModel);
}
Also used : JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) Before(org.b3log.latke.servlet.annotation.Before) After(org.b3log.latke.servlet.annotation.After) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Aggregations

Before (org.b3log.latke.servlet.annotation.Before)169 RequestProcessing (org.b3log.latke.servlet.annotation.RequestProcessing)169 JSONObject (org.json.JSONObject)166 After (org.b3log.latke.servlet.annotation.After)135 AbstractFreeMarkerRenderer (org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer)105 ServiceException (org.b3log.latke.service.ServiceException)37 Date (java.util.Date)13 IOException (java.io.IOException)9 ArrayList (java.util.ArrayList)8 JSONArray (org.json.JSONArray)8 Auth (com.qiniu.util.Auth)7 ParseException (java.text.ParseException)6 List (java.util.List)6 ServletException (javax.servlet.ServletException)3 Configuration (com.qiniu.storage.Configuration)1 UploadManager (com.qiniu.storage.UploadManager)1 BufferedImage (java.awt.image.BufferedImage)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1