Search in sources :

Example 6 with RequestProcessing

use of org.b3log.latke.servlet.annotation.RequestProcessing in project solo by b3log.

the class CommentProcessor method addArticleComment.

/**
     * Adds a comment to an article.
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "oId": generatedCommentId,
     *     "sc": "COMMENT_ARTICLE_SUCC",
     *     "commentDate": "", // yyyy/MM/dd HH:mm:ss
     *     "commentSharpURL": "",
     *     "commentThumbnailURL": "",
     *     "commentOriginalCommentName": "", // if exists this key, the comment is an reply
     *     "commentContent": "" // HTML
     * }
     * </pre>
     * </p>
     *
     * @param context the specified context, including a request json object, for example,
     *                "captcha": "",
     *                "oId": articleId,
     *                "commentName": "",
     *                "commentEmail": "",
     *                "commentURL": "",
     *                "commentContent": "",
     *                "commentOriginalCommentId": "" // optional, if exists this key, the comment is an reply
     * @throws ServletException servlet exception
     * @throws IOException      io exception
     */
@RequestProcessing(value = "/add-article-comment.do", method = HTTPRequestMethod.POST)
public void addArticleComment(final HTTPRequestContext context) throws ServletException, IOException {
    final HttpServletRequest httpServletRequest = context.getRequest();
    final HttpServletResponse httpServletResponse = context.getResponse();
    final JSONObject requestJSONObject = Requests.parseRequestJSONObject(httpServletRequest, httpServletResponse);
    requestJSONObject.put(Common.TYPE, Article.ARTICLE);
    fillCommenter(requestJSONObject, httpServletRequest, httpServletResponse);
    final JSONObject jsonObject = commentMgmtService.checkAddCommentRequest(requestJSONObject);
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    renderer.setJSONObject(jsonObject);
    if (!jsonObject.optBoolean(Keys.STATUS_CODE)) {
        LOGGER.log(Level.WARN, "Can't add comment[msg={0}]", jsonObject.optString(Keys.MSG));
        return;
    }
    final HttpSession session = httpServletRequest.getSession(false);
    if (null == session) {
        jsonObject.put(Keys.STATUS_CODE, false);
        jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
        return;
    }
    final String storedCaptcha = (String) session.getAttribute(CaptchaProcessor.CAPTCHA);
    session.removeAttribute(CaptchaProcessor.CAPTCHA);
    if (!userQueryService.isLoggedIn(httpServletRequest, httpServletResponse)) {
        final String captcha = requestJSONObject.optString(CaptchaProcessor.CAPTCHA);
        if (null == storedCaptcha || !storedCaptcha.equals(captcha)) {
            jsonObject.put(Keys.STATUS_CODE, false);
            jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
            return;
        }
    }
    try {
        final JSONObject addResult = commentMgmtService.addArticleComment(requestJSONObject);
        final Map<String, Object> dataModel = new HashMap<>();
        dataModel.put(Comment.COMMENT, addResult);
        final JSONObject article = addResult.optJSONObject(Article.ARTICLE);
        article.put(Common.COMMENTABLE, addResult.opt(Common.COMMENTABLE));
        article.put(Common.PERMALINK, addResult.opt(Common.PERMALINK));
        dataModel.put(Article.ARTICLE, article);
        // https://github.com/b3log/solo/issues/12246
        try {
            final String skinDirName = (String) httpServletRequest.getAttribute(Keys.TEMAPLTE_DIR_NAME);
            final Template template = Templates.MAIN_CFG.getTemplate("common-comment.ftl");
            final JSONObject preference = preferenceQueryService.getPreference();
            Skins.fillLangs(preference.optString(Option.ID_C_LOCALE_STRING), skinDirName, dataModel);
            Keys.fillServer(dataModel);
            final StringWriter stringWriter = new StringWriter();
            template.process(dataModel, stringWriter);
            stringWriter.close();
            addResult.put("cmtTpl", stringWriter.toString());
        } catch (final Exception e) {
        // 1.9.0 向后兼容
        }
        addResult.put(Keys.STATUS_CODE, true);
        renderer.setJSONObject(addResult);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Can not add comment on article", e);
        jsonObject.put(Keys.STATUS_CODE, false);
        jsonObject.put(Keys.MSG, langPropsService.get("addFailLabel"));
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) JSONObject(org.json.JSONObject) JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) HttpServletResponse(javax.servlet.http.HttpServletResponse) JSONObject(org.json.JSONObject) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) Template(freemarker.template.Template) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 7 with RequestProcessing

use of org.b3log.latke.servlet.annotation.RequestProcessing in project solo by b3log.

the class ErrorProcessor method showErrorPage.

/**
     * Shows the user template page.
     *
     * @param context the specified context
     * @param request the specified HTTP servlet request
     * @param response the specified HTTP servlet response
     * @throws IOException io exception
     */
@RequestProcessing(value = "/error/*.html", method = HTTPRequestMethod.GET)
public void showErrorPage(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    final String requestURI = request.getRequestURI();
    String templateName = StringUtils.substringAfterLast(requestURI, "/");
    templateName = StringUtils.substringBefore(templateName, ".") + ".ftl";
    LOGGER.log(Level.DEBUG, "Shows error page[requestURI={0}, templateName={1}]", new Object[] { requestURI, templateName });
    final ConsoleRenderer renderer = new ConsoleRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("error/" + templateName);
    final Map<String, Object> dataModel = renderer.getDataModel();
    try {
        final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request));
        dataModel.putAll(langs);
        final JSONObject preference = preferenceQueryService.getPreference();
        filler.fillBlogHeader(request, response, dataModel, preference);
        filler.fillBlogFooter(request, dataModel, preference);
        dataModel.put(Common.LOGIN_URL, userService.createLoginURL(Common.ADMIN_INDEX_URI));
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (final IOException ex) {
            LOGGER.error(ex.getMessage());
        }
    }
}
Also used : JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) ConsoleRenderer(org.b3log.solo.processor.renderer.ConsoleRenderer) IOException(java.io.IOException) IOException(java.io.IOException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 8 with RequestProcessing

use of org.b3log.latke.servlet.annotation.RequestProcessing in project solo by b3log.

the class ArticleReceiver method addArticle.

/**
     * Adds an article with the specified request.
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": boolean,
     *     "oId": "", // Generated article id
     *     "msg": ""
     * }
     * </pre>
     * </p>
     *
     * @param request  the specified http servlet request, for example,
     *                 "article": {
     *                 "oId": "",
     *                 "articleTitle": "",
     *                 "articleContent": "",
     *                 "articleTags": "tag1,tag2,tag3",
     *                 "userB3Key": "",
     *                 "articleEditorType": ""
     *                 }
     * @param response the specified http servlet response
     * @param context  the specified http request context
     * @throws Exception exception
     */
@RequestProcessing(value = "/apis/symphony/article", method = HTTPRequestMethod.POST)
public void addArticle(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) throws Exception {
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject ret = new JSONObject();
    try {
        final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response);
        final JSONObject article = requestJSONObject.optJSONObject(Article.ARTICLE);
        final String userB3Key = article.optString("userB3Key");
        final JSONObject preference = preferenceQueryService.getPreference();
        if (!userB3Key.equals(preference.optString(Option.ID_C_KEY_OF_SOLO))) {
            LOGGER.log(Level.WARN, "B3 key not match, ignored add article");
            return;
        }
        article.remove("userB3Key");
        final JSONObject admin = userQueryService.getAdmin();
        article.put(Article.ARTICLE_AUTHOR_EMAIL, admin.getString(User.USER_EMAIL));
        final String articleContent = article.optString(Article.ARTICLE_CONTENT);
        final String plainTextContent = Jsoup.clean(Markdowns.toHTML(articleContent), Whitelist.none());
        if (plainTextContent.length() > ARTICLE_ABSTRACT_LENGTH) {
            article.put(Article.ARTICLE_ABSTRACT, plainTextContent.substring(0, ARTICLE_ABSTRACT_LENGTH) + "....");
        } else {
            article.put(Article.ARTICLE_ABSTRACT, plainTextContent);
        }
        article.put(Article.ARTICLE_IS_PUBLISHED, true);
        // Do not send to rhythm
        article.put(Common.POST_TO_COMMUNITY, false);
        article.put(Article.ARTICLE_COMMENTABLE, true);
        article.put(Article.ARTICLE_VIEW_PWD, "");
        String content = article.getString(Article.ARTICLE_CONTENT);
        final String articleId = article.getString(Keys.OBJECT_ID);
        //            content += "\n\n<p style='font-size: 12px;'><i>该文章同步自 <a href='https://hacpai.com/article/" + articleId
        //                + "' target='_blank'>黑客派</a></i></p>";
        article.put(Article.ARTICLE_CONTENT, content);
        articleMgmtService.addArticle(requestJSONObject);
        ret.put(Keys.OBJECT_ID, articleId);
        ret.put(Keys.MSG, "add article succ");
        ret.put(Keys.STATUS_CODE, true);
        renderer.setJSONObject(ret);
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        final JSONObject jsonObject = QueryResults.defaultResult();
        renderer.setJSONObject(jsonObject);
        jsonObject.put(Keys.MSG, e.getMessage());
    }
}
Also used : JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 9 with RequestProcessing

use of org.b3log.latke.servlet.annotation.RequestProcessing in project solo by b3log.

the class CommentReceiver method addComment.

/**
     * Adds an article with the specified request.
     *
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": true
     * }
     * </pre>
     * </p>
     *
     * @param request the specified http servlet request, for example,      <pre>
     * {
     *     "comment": {
     *         "userB3Key": "",
     *         "oId": "",
     *         "commentSymphonyArticleId": "",
     *         "commentOnArticleId": "",
     *         "commentAuthorName": "",
     *         "commentAuthorEmail": "",
     *         "commentAuthorURL": "",
     *         "commentContent": "",
     *         "commentOriginalCommentId": "" // optional, if exists this key, the comment is an reply
     *     }
     * }
     * </pre>
     *
     * @param response the specified http servlet response
     * @param context the specified http request context
     * @throws Exception exception
     */
@RequestProcessing(value = "/apis/symphony/comment", method = HTTPRequestMethod.PUT)
public void addComment(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) throws Exception {
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject ret = new JSONObject();
    renderer.setJSONObject(ret);
    final Transaction transaction = commentRepository.beginTransaction();
    try {
        final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response);
        final JSONObject symphonyCmt = requestJSONObject.optJSONObject(Comment.COMMENT);
        final JSONObject preference = preferenceQueryService.getPreference();
        final String keyOfSolo = preference.optString(Option.ID_C_KEY_OF_SOLO);
        final String key = symphonyCmt.optString("userB3Key");
        if (Strings.isEmptyOrNull(keyOfSolo) || !keyOfSolo.equals(key)) {
            ret.put(Keys.STATUS_CODE, HttpServletResponse.SC_FORBIDDEN);
            ret.put(Keys.MSG, "Wrong key");
            return;
        }
        final String articleId = symphonyCmt.getString("commentOnArticleId");
        final JSONObject article = articleRepository.get(articleId);
        if (null == article) {
            ret.put(Keys.STATUS_CODE, HttpServletResponse.SC_NOT_FOUND);
            ret.put(Keys.MSG, "Not found the specified article[id=" + articleId + "]");
            return;
        }
        final String commentName = symphonyCmt.getString("commentAuthorName");
        final String commentEmail = symphonyCmt.getString("commentAuthorEmail").trim().toLowerCase();
        String commentURL = symphonyCmt.optString("commentAuthorURL");
        if (!commentURL.contains("://")) {
            commentURL = "http://" + commentURL;
        }
        try {
            new URL(commentURL);
        } catch (final MalformedURLException e) {
            LOGGER.log(Level.WARN, "The comment URL is invalid [{0}]", commentURL);
            commentURL = "";
        }
        final String commentId = symphonyCmt.optString(Keys.OBJECT_ID);
        String commentContent = symphonyCmt.getString(Comment.COMMENT_CONTENT);
        //            commentContent += "<p class='cmtFromSym'><i>该评论同步自 <a href='" + SoloServletListener.B3LOG_SYMPHONY_SERVE_PATH
        //                    + "/article/" + symphonyCmt.optString("commentSymphonyArticleId") + "#" + commentId
        //                    + "' target='_blank'>黑客派</a></i></p>";
        final String originalCommentId = symphonyCmt.optString(Comment.COMMENT_ORIGINAL_COMMENT_ID);
        // Step 1: Add comment
        final JSONObject comment = new JSONObject();
        JSONObject originalComment = null;
        comment.put(Keys.OBJECT_ID, commentId);
        comment.put(Comment.COMMENT_NAME, commentName);
        comment.put(Comment.COMMENT_EMAIL, commentEmail);
        comment.put(Comment.COMMENT_URL, commentURL);
        comment.put(Comment.COMMENT_CONTENT, commentContent);
        final Date date = new Date();
        comment.put(Comment.COMMENT_DATE, date);
        ret.put(Comment.COMMENT_DATE, DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));
        if (!Strings.isEmptyOrNull(originalCommentId)) {
            originalComment = commentRepository.get(originalCommentId);
            if (null != originalComment) {
                comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, originalCommentId);
                final String originalCommentName = originalComment.getString(Comment.COMMENT_NAME);
                comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, originalCommentName);
                ret.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, originalCommentName);
            } else {
                comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, "");
                comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, "");
                LOGGER.log(Level.WARN, "Not found orginal comment[id={0}] of reply[name={1}, content={2}]", new String[] { originalCommentId, commentName, commentContent });
            }
        } else {
            comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, "");
            comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, "");
        }
        commentMgmtService.setCommentThumbnailURL(comment);
        ret.put(Comment.COMMENT_THUMBNAIL_URL, comment.getString(Comment.COMMENT_THUMBNAIL_URL));
        // Sets comment on article....
        comment.put(Comment.COMMENT_ON_ID, articleId);
        comment.put(Comment.COMMENT_ON_TYPE, Article.ARTICLE);
        final String commentSharpURL = Comments.getCommentSharpURLForArticle(article, commentId);
        comment.put(Comment.COMMENT_SHARP_URL, commentSharpURL);
        commentRepository.add(comment);
        // Step 2: Update article comment count
        articleMgmtService.incArticleCommentCount(articleId);
        // Step 3: Update blog statistic comment count
        statisticMgmtService.incBlogCommentCount();
        statisticMgmtService.incPublishedBlogCommentCount();
        // Step 4: Send an email to admin
        try {
            commentMgmtService.sendNotificationMail(article, comment, originalComment, preference);
        } catch (final Exception e) {
            LOGGER.log(Level.WARN, "Send mail failed", e);
        }
        // Step 5: Fire add comment event
        final JSONObject eventData = new JSONObject();
        eventData.put(Comment.COMMENT, comment);
        eventData.put(Article.ARTICLE, article);
        eventManager.fireEventSynchronously(new Event<JSONObject>(EventTypes.ADD_COMMENT_TO_ARTICLE_FROM_SYMPHONY, eventData));
        transaction.commit();
        ret.put(Keys.STATUS_CODE, true);
        ret.put(Keys.OBJECT_ID, commentId);
        ret.put(Keys.OBJECT_ID, articleId);
        ret.put(Keys.MSG, "add a comment to an article from symphony succ");
        ret.put(Keys.STATUS_CODE, true);
        renderer.setJSONObject(ret);
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        final JSONObject jsonObject = QueryResults.defaultResult();
        renderer.setJSONObject(jsonObject);
        jsonObject.put(Keys.MSG, e.getMessage());
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) Transaction(org.b3log.latke.repository.Transaction) ServiceException(org.b3log.latke.service.ServiceException) URL(java.net.URL) Date(java.util.Date) ServiceException(org.b3log.latke.service.ServiceException) MalformedURLException(java.net.MalformedURLException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 10 with RequestProcessing

use of org.b3log.latke.servlet.annotation.RequestProcessing in project solo by b3log.

the class ArticleProcessor method getArticlesByPage.

/**
     * Gets articles paged with the specified context.
     *
     * @param context the specified context
     * @param request the specified request
     */
@RequestProcessing(value = "/articles/\\d+", uriPatternsMode = URIPatternMode.REGEX, method = HTTPRequestMethod.GET)
public void getArticlesByPage(final HTTPRequestContext context, final HttpServletRequest request) {
    final JSONObject jsonObject = new JSONObject();
    final int currentPageNum = getArticlesPagedCurrentPageNum(request.getRequestURI());
    Stopwatchs.start("Get Articles Paged[pageNum=" + currentPageNum + ']');
    try {
        jsonObject.put(Keys.STATUS_CODE, true);
        final JSONObject preference = preferenceQueryService.getPreference();
        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 StringBuilder pathBuilder = new StringBuilder();
        pathBuilder.append(currentPageNum).append('/').append(pageSize).append('/').append(windowSize);
        final JSONObject requestJSONObject = Requests.buildPaginationRequest(pathBuilder.toString());
        requestJSONObject.put(Article.ARTICLE_IS_PUBLISHED, true);
        final JSONObject result = articleQueryService.getArticles(requestJSONObject);
        final List<JSONObject> articles = org.b3log.latke.util.CollectionUtils.jsonArrayToList(result.getJSONArray(Article.ARTICLES));
        final boolean hasMultipleUsers = userQueryService.hasMultipleUsers();
        if (hasMultipleUsers) {
            filler.setArticlesExProperties(request, articles, preference);
        } else if (!articles.isEmpty()) {
            final JSONObject author = articleQueryService.getAuthor(articles.get(0));
            filler.setArticlesExProperties(request, articles, author, preference);
        }
        jsonObject.put(Keys.RESULTS, result);
    } catch (final Exception e) {
        jsonObject.put(Keys.STATUS_CODE, false);
        LOGGER.log(Level.ERROR, "Gets article paged failed", e);
    } finally {
        Stopwatchs.end();
    }
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    renderer.setJSONObject(jsonObject);
}
Also used : JSONObject(org.json.JSONObject) JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) EventException(org.b3log.latke.event.EventException) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Aggregations

RequestProcessing (org.b3log.latke.servlet.annotation.RequestProcessing)104 JSONObject (org.json.JSONObject)94 JSONRenderer (org.b3log.latke.servlet.renderer.JSONRenderer)67 ServiceException (org.b3log.latke.service.ServiceException)51 IOException (java.io.IOException)35 AbstractFreeMarkerRenderer (org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer)14 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 JSONException (org.json.JSONException)12 JSONArray (org.json.JSONArray)11 HttpServletResponse (javax.servlet.http.HttpServletResponse)9 EventException (org.b3log.latke.event.EventException)9 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 TextHTMLRenderer (org.b3log.latke.servlet.renderer.TextHTMLRenderer)7 FreeMarkerRenderer (org.b3log.latke.servlet.renderer.freemarker.FreeMarkerRenderer)7 ConsoleRenderer (org.b3log.solo.processor.renderer.ConsoleRenderer)7 Date (java.util.Date)6 ExecutionException (java.util.concurrent.ExecutionException)6 ArrayList (java.util.ArrayList)5 MalformedURLException (java.net.MalformedURLException)4 HttpSession (javax.servlet.http.HttpSession)4