Search in sources :

Example 31 with Before

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

the class AdminProcessor method exchangePoint.

/**
 * Exchanges a user's point.
 *
 * @param context  the specified context
 * @param request  the specified request
 * @param response the specified response
 * @param userId   the specified user id
 * @throws Exception exception
 */
@RequestProcessing(value = "/admin/user/{userId}/exchange-point", method = HTTPRequestMethod.POST)
@Before(adviceClass = { StopwatchStartAdvice.class, PermissionCheck.class })
@After(adviceClass = { PermissionGrant.class, StopwatchEndAdvice.class })
public void exchangePoint(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response, final String userId) throws Exception {
    final String pointStr = request.getParameter(Common.POINT);
    try {
        final int point = Integer.valueOf(pointStr);
        final JSONObject user = userQueryService.getUser(userId);
        final int currentPoint = user.optInt(UserExt.USER_POINT);
        if (currentPoint - point < Symphonys.getInt("pointExchangeMin")) {
            final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
            context.setRenderer(renderer);
            renderer.setTemplateName("admin/error.ftl");
            final Map<String, Object> dataModel = renderer.getDataModel();
            dataModel.put(Keys.MSG, langPropsService.get("insufficientBalanceLabel"));
            dataModelService.fillHeaderAndFooter(request, response, dataModel);
            return;
        }
        final String memo = String.valueOf(Math.floor(point / (double) Symphonys.getInt("pointExchangeUnit")));
        final String transferId = pointtransferMgmtService.transfer(userId, Pointtransfer.ID_C_SYS, Pointtransfer.TRANSFER_TYPE_C_EXCHANGE, point, memo, System.currentTimeMillis());
        final JSONObject notification = new JSONObject();
        notification.put(Notification.NOTIFICATION_USER_ID, userId);
        notification.put(Notification.NOTIFICATION_DATA_ID, transferId);
        notificationMgmtService.addPointExchangeNotification(notification);
    } catch (final Exception e) {
        final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
        context.setRenderer(renderer);
        renderer.setTemplateName("admin/error.ftl");
        final Map<String, Object> dataModel = renderer.getDataModel();
        dataModel.put(Keys.MSG, e.getMessage());
        dataModelService.fillHeaderAndFooter(request, response, dataModel);
        return;
    }
    response.sendRedirect(Latkes.getServePath() + "/admin/user/" + userId);
}
Also used : JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) ServiceException(org.b3log.latke.service.ServiceException) ParseException(java.text.ParseException) IOException(java.io.IOException) Before(org.b3log.latke.servlet.annotation.Before) After(org.b3log.latke.servlet.annotation.After) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 32 with Before

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

the class AdminProcessor method abusePoint.

/**
 * Deducts a user's abuse point.
 *
 * @param context  the specified context
 * @param request  the specified request
 * @param response the specified response
 * @param userId   the specified user id
 * @throws Exception exception
 */
@RequestProcessing(value = "/admin/user/{userId}/abuse-point", method = HTTPRequestMethod.POST)
@Before(adviceClass = { StopwatchStartAdvice.class, PermissionCheck.class })
@After(adviceClass = { PermissionGrant.class, StopwatchEndAdvice.class })
public void abusePoint(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response, final String userId) throws Exception {
    final String pointStr = request.getParameter(Common.POINT);
    try {
        final int point = Integer.valueOf(pointStr);
        final JSONObject user = userQueryService.getUser(userId);
        final int currentPoint = user.optInt(UserExt.USER_POINT);
        if (currentPoint - point < 0) {
            final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
            context.setRenderer(renderer);
            renderer.setTemplateName("admin/error.ftl");
            final Map<String, Object> dataModel = renderer.getDataModel();
            dataModel.put(Keys.MSG, langPropsService.get("insufficientBalanceLabel"));
            dataModelService.fillHeaderAndFooter(request, response, dataModel);
            return;
        }
        final String memo = request.getParameter(Common.MEMO);
        final String transferId = pointtransferMgmtService.transfer(userId, Pointtransfer.ID_C_SYS, Pointtransfer.TRANSFER_TYPE_C_ABUSE_DEDUCT, point, memo, System.currentTimeMillis());
        final JSONObject notification = new JSONObject();
        notification.put(Notification.NOTIFICATION_USER_ID, userId);
        notification.put(Notification.NOTIFICATION_DATA_ID, transferId);
        notificationMgmtService.addAbusePointDeductNotification(notification);
    } catch (final Exception e) {
        final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
        context.setRenderer(renderer);
        renderer.setTemplateName("admin/error.ftl");
        final Map<String, Object> dataModel = renderer.getDataModel();
        dataModel.put(Keys.MSG, e.getMessage());
        dataModelService.fillHeaderAndFooter(request, response, dataModel);
        return;
    }
    response.sendRedirect(Latkes.getServePath() + "/admin/user/" + userId);
}
Also used : JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) ServiceException(org.b3log.latke.service.ServiceException) ParseException(java.text.ParseException) IOException(java.io.IOException) Before(org.b3log.latke.servlet.annotation.Before) After(org.b3log.latke.servlet.annotation.After) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 33 with Before

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

the class AdminProcessor method showArticle.

/**
 * Shows an article.
 *
 * @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 = "/admin/article/{articleId}", method = HTTPRequestMethod.GET)
@Before(adviceClass = { StopwatchStartAdvice.class, PermissionCheck.class })
@After(adviceClass = { PermissionGrant.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(request);
    context.setRenderer(renderer);
    renderer.setTemplateName("admin/article.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();
    final JSONObject article = articleQueryService.getArticle(articleId);
    Escapes.escapeHTML(article);
    dataModel.put(Article.ARTICLE, article);
    dataModelService.fillHeaderAndFooter(request, response, 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)

Example 34 with Before

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

the class ArticleProcessor method showAddArticle.

/**
 * 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, PermissionGrant.class, StopwatchEndAdvice.class })
public void showAddArticle(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
    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"));
    if (!Symphonys.getBoolean("qiniu.enabled")) {
        dataModel.put("qiniuUploadToken", "");
    }
    final long imgMaxSize = Symphonys.getLong("upload.img.maxSize");
    dataModel.put("imgMaxSize", imgMaxSize);
    final long fileMaxSize = Symphonys.getLong("upload.file.maxSize");
    dataModel.put("fileMaxSize", fileMaxSize);
    String tags = request.getParameter(Tag.TAGS);
    final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER);
    if (StringUtils.isBlank(tags)) {
        tags = "";
        dataModel.put(Tag.TAGS, tags);
    } else {
        tags = Tag.formatTags(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.containsWhiteListTags(tagTitle)) {
                tagBuilder.append(tagTitle).append(",");
                continue;
            }
            if (!Tag.TAG_TITLE_PATTERN.matcher(tagTitle).matches()) {
                continue;
            }
            if (tagTitle.length() > Tag.MAX_TAG_TITLE_LENGTH) {
                continue;
            }
            if (!Role.ROLE_ID_C_ADMIN.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);
    }
    String at = request.getParameter(Common.AT);
    at = StringUtils.trim(at);
    if (StringUtils.isNotBlank(at)) {
        dataModel.put(Common.AT, at + " ");
    }
    dataModelService.fillHeaderAndFooter(request, response, dataModel);
    String rewardEditorPlaceholderLabel = langPropsService.get("rewardEditorPlaceholderLabel");
    rewardEditorPlaceholderLabel = rewardEditorPlaceholderLabel.replace("{point}", String.valueOf(Pointtransfer.TRANSFER_SUM_C_ADD_ARTICLE_REWARD));
    dataModel.put("rewardEditorPlaceholderLabel", rewardEditorPlaceholderLabel);
    dataModel.put(Common.BROADCAST_POINT, Pointtransfer.TRANSFER_SUM_C_ADD_ARTICLE_BROADCAST);
    String articleContentErrorLabel = langPropsService.get("articleContentErrorLabel");
    articleContentErrorLabel = articleContentErrorLabel.replace("{maxArticleContentLength}", String.valueOf(ArticleAddValidation.MAX_ARTICLE_CONTENT_LENGTH));
    dataModel.put("articleContentErrorLabel", articleContentErrorLabel);
    final String b3Key = currentUser.optString(UserExt.USER_B3_KEY);
    final String b3ClientAddArticle = currentUser.optString(UserExt.USER_B3_CLIENT_ADD_ARTICLE_URL);
    final String b3ClientUpdateArticle = currentUser.optString(UserExt.USER_B3_CLIENT_UPDATE_ARTICLE_URL);
    dataModel.put("hasB3Key", StringUtils.isNotBlank(b3Key) && StringUtils.isNotBlank(b3ClientAddArticle) && StringUtils.isNotBlank(b3ClientUpdateArticle));
    fillPostArticleRequisite(dataModel, currentUser);
    fillDomainsWithTags(dataModel);
}
Also used : JSONObject(org.json.JSONObject) Auth(com.qiniu.util.Auth) JSONObject(org.json.JSONObject) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) 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 35 with Before

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

the class ArticleProcessor method updateArticle.

/**
 * Updates an article locally.
 * <p>
 * The request json object (an article):
 * <pre>
 * {
 *   "articleTitle": "",
 *   "articleTags": "", // Tags spliting by ','
 *   "articleContent": "",
 *   "articleCommentable": boolean,
 *   "articleType": int,
 *   "articleRewardContent": "",
 *   "articleRewardPoint": int
 * }
 * </pre>
 * </p>
 *
 * @param context  the specified context
 * @param request  the specified request
 * @param response the specified response
 * @param id       the specified article id
 * @throws Exception exception
 */
@RequestProcessing(value = "/article/{id}", method = HTTPRequestMethod.PUT)
@Before(adviceClass = { StopwatchStartAdvice.class, LoginCheck.class, CSRFCheck.class, ArticleUpdateValidation.class, PermissionCheck.class })
@After(adviceClass = StopwatchEndAdvice.class)
public void updateArticle(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response, final String id) throws Exception {
    if (Strings.isEmptyOrNull(id)) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
    final JSONObject oldArticle = articleQueryService.getArticleById(avatarViewMode, id);
    if (null == oldArticle) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    context.renderJSON();
    if (Article.ARTICLE_STATUS_C_VALID != oldArticle.optInt(Article.ARTICLE_STATUS)) {
        context.renderMsg(langPropsService.get("articleLockedLabel"));
        context.renderJSONValue(Keys.STATUS_CODE, StatusCodes.ERR);
        return;
    }
    final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST);
    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 JSONObject article = new JSONObject();
    article.put(Keys.OBJECT_ID, id);
    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);
    }
    final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER);
    if (null == currentUser || !currentUser.optString(Keys.OBJECT_ID).equals(oldArticle.optString(Article.ARTICLE_AUTHOR_ID))) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    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);
    try {
        articleMgmtService.updateArticle(article);
        context.renderJSONValue(Keys.STATUS_CODE, StatusCodes.SUCC);
        context.renderJSONValue(Article.ARTICLE_T_ID, id);
    } 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)

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