Search in sources :

Example 56 with JSONRenderer

use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.

the class LinkConsole method removeLink.

/**
     * Removes a link by the specified request.
     * 
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": boolean,
     *     "msg": ""
     * }
     * </pre>
     * </p>
     *
     * @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 = "/console/link/*", method = HTTPRequestMethod.DELETE)
public void removeLink(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) throws Exception {
    if (!userQueryService.isAdminLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject jsonObject = new JSONObject();
    renderer.setJSONObject(jsonObject);
    try {
        final String linkId = request.getRequestURI().substring((Latkes.getContextPath() + "/console/link/").length());
        linkMgmtService.removeLink(linkId);
        jsonObject.put(Keys.STATUS_CODE, true);
        jsonObject.put(Keys.MSG, langPropsService.get("removeSuccLabel"));
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        jsonObject.put(Keys.STATUS_CODE, false);
        jsonObject.put(Keys.MSG, langPropsService.get("removeFailLabel"));
    }
}
Also used : JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 57 with JSONRenderer

use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.

the class ArticleReceiver method updateArticle.

/**
     * Updates an article with the specified request.
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": boolean,
     *     "msg": ""
     * }
     * </pre>
     * </p>
     *
     * @param request  the specified http servlet request, for example,
     *                 "article": {
     *                 "oId": "", // Symphony Article#clientArticleId
     *                 "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.PUT)
public void updateArticle(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);
    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 update article");
            return;
        }
        article.remove("userB3Key");
        final String articleId = article.getString(Keys.OBJECT_ID);
        if (null == articleQueryService.getArticleById(articleId)) {
            ret.put(Keys.MSG, "No found article[oId=" + articleId + "] to update");
            ret.put(Keys.STATUS_CODE, false);
            return;
        }
        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);
        //            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.updateArticle(requestJSONObject);
        ret.put(Keys.MSG, "update article succ");
        ret.put(Keys.STATUS_CODE, true);
    } 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 58 with JSONRenderer

use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.

the class BlogProcessor method getInterestTags.

/**
     * Gets interest tags (top 10 and bottom 10).
     *
     * <pre>
     * {
     *     "data": ["tag1", "tag2", ....]
     * }
     * </pre>
     *
     * @param context the specified context
     * @param request the specified HTTP servlet request
     * @param response the specified HTTP servlet response
     * @throws Exception io exception
     */
@RequestProcessing(value = "/blog/interest-tags", method = HTTPRequestMethod.GET)
public void getInterestTags(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject ret = new JSONObject();
    renderer.setJSONObject(ret);
    final Set<String> tagTitles = new HashSet<>();
    final List<JSONObject> topTags = tagQueryService.getTopTags(10);
    for (final JSONObject topTag : topTags) {
        tagTitles.add(topTag.optString(Tag.TAG_TITLE));
    }
    final List<JSONObject> bottomTags = tagQueryService.getBottomTags(10);
    for (final JSONObject bottomTag : bottomTags) {
        tagTitles.add(bottomTag.optString(Tag.TAG_TITLE));
    }
    ret.put("data", tagTitles);
}
Also used : JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) HashSet(java.util.HashSet) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 59 with JSONRenderer

use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.

the class BlogProcessor method getArticlesTags.

/**
     * Gets tags of all articles.
     *
     * <pre>
     * {
     *     "data": [
     *         ["tag1", "tag2", ....], // tags of one article
     *         ["tagX", "tagY", ....], // tags of another article
     *         ....
     *     ]
     * }
     * </pre>
     *
     * @param context the specified context
     * @param request the specified HTTP servlet request
     * @param response the specified HTTP servlet response
     * @throws Exception io exception
     */
@RequestProcessing(value = "/blog/articles-tags", method = HTTPRequestMethod.GET)
public void getArticlesTags(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final String pwd = request.getParameter("pwd");
    if (Strings.isEmptyOrNull(pwd)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    final JSONObject admin = userQueryService.getAdmin();
    if (!MD5.hash(pwd).equals(admin.getString(User.USER_PASSWORD))) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    final JSONObject requestJSONObject = new JSONObject();
    requestJSONObject.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, 1);
    requestJSONObject.put(Pagination.PAGINATION_PAGE_SIZE, Integer.MAX_VALUE);
    requestJSONObject.put(Pagination.PAGINATION_WINDOW_SIZE, Integer.MAX_VALUE);
    requestJSONObject.put(Article.ARTICLE_IS_PUBLISHED, true);
    final JSONArray excludes = new JSONArray();
    excludes.put(Article.ARTICLE_CONTENT);
    excludes.put(Article.ARTICLE_UPDATE_DATE);
    excludes.put(Article.ARTICLE_CREATE_DATE);
    excludes.put(Article.ARTICLE_AUTHOR_EMAIL);
    excludes.put(Article.ARTICLE_HAD_BEEN_PUBLISHED);
    excludes.put(Article.ARTICLE_IS_PUBLISHED);
    excludes.put(Article.ARTICLE_RANDOM_DOUBLE);
    requestJSONObject.put(Keys.EXCLUDES, excludes);
    final JSONObject result = articleQueryService.getArticles(requestJSONObject);
    final JSONArray articles = result.optJSONArray(Article.ARTICLES);
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject ret = new JSONObject();
    renderer.setJSONObject(ret);
    final JSONArray data = new JSONArray();
    ret.put("data", data);
    for (int i = 0; i < articles.length(); i++) {
        final JSONObject article = articles.optJSONObject(i);
        final String tagString = article.optString(Article.ARTICLE_TAGS_REF);
        final JSONArray tagArray = new JSONArray();
        data.put(tagArray);
        final String[] tags = tagString.split(",");
        for (final String tag : tags) {
            final String trim = tag.trim();
            if (!Strings.isEmptyOrNull(trim)) {
                tagArray.put(tag);
            }
        }
    }
}
Also used : JSONObject(org.json.JSONObject) JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONArray(org.json.JSONArray) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 60 with JSONRenderer

use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.

the class CommentProcessor method addPageComment.

/**
     * Adds a comment to a page.
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "oId": generatedCommentId,
     *     "sc": "COMMENT_PAGE_SUCC"
     *     "commentDate": "", // yyyy/MM/dd HH:mm:ss
     *     "commentSharpURL": "",
     *     "commentThumbnailURL": "",
     *     "commentOriginalCommentName": "" // if exists this key, the comment is an reply
     * }
     * </pre>
     * </p>
     *
     * @param context the specified context, including a request json object, for example,
     *                "captcha": "",
     *                "oId": pageId,
     *                "commentName": "",
     *                "commentEmail": "",
     *                "commentURL": "",
     *                "commentContent": "", // HTML
     *                "commentOriginalCommentId": "" // optional, if exists this key, the comment is an reply
     * @throws ServletException servlet exception
     * @throws IOException      io exception
     */
@RequestProcessing(value = "/add-page-comment.do", method = HTTPRequestMethod.POST)
public void addPageComment(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, Page.PAGE);
    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.addPageComment(requestJSONObject);
        final Map<String, Object> dataModel = new HashMap<>();
        dataModel.put(Comment.COMMENT, addResult);
        final JSONObject page = addResult.optJSONObject(Page.PAGE);
        page.put(Common.COMMENTABLE, addResult.opt(Common.COMMENTABLE));
        page.put(Common.PERMALINK, addResult.opt(Common.PERMALINK));
        dataModel.put(Article.ARTICLE, page);
        // 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 page", 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)

Aggregations

RequestProcessing (org.b3log.latke.servlet.annotation.RequestProcessing)67 JSONRenderer (org.b3log.latke.servlet.renderer.JSONRenderer)67 JSONObject (org.json.JSONObject)67 ServiceException (org.b3log.latke.service.ServiceException)38 IOException (java.io.IOException)12 JSONException (org.json.JSONException)7 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 MalformedURLException (java.net.MalformedURLException)4 EventException (org.b3log.latke.event.EventException)4 JSONArray (org.json.JSONArray)4 RepositoryException (org.b3log.latke.repository.RepositoryException)3 Template (freemarker.template.Template)2 StringWriter (java.io.StringWriter)2 URL (java.net.URL)2 HashMap (java.util.HashMap)2 ServletException (javax.servlet.ServletException)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 HttpSession (javax.servlet.http.HttpSession)2 HTTPRequest (org.b3log.latke.urlfetch.HTTPRequest)2