Search in sources :

Example 81 with RequestProcessing

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

the class CommentConsole method getPageComments.

/**
     * Gets comments of a page specified by the article id for administrator.
     *
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": boolean,
     *     "comments": [{
     *         "oId": "",
     *         "commentName": "",
     *         "commentEmail": "",
     *         "thumbnailUrl": "",
     *         "commentURL": "",
     *         "commentContent": "",
     *         "commentTime": long,
     *         "commentSharpURL": "",
     *         "isReply": boolean
     *      }, ....]
     * }
     * </pre>
     * </p>
     *
     * @param context the specified http request context
     * @param request the specified http servlet request
     * @param response the specified http servlet response
     * @throws Exception exception
     */
@RequestProcessing(value = "/console/comments/page/*", method = HTTPRequestMethod.GET)
public void getPageComments(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    if (!userQueryService.isLoggedIn(request, response)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    try {
        final JSONObject ret = new JSONObject();
        renderer.setJSONObject(ret);
        final String requestURI = request.getRequestURI();
        final String pageId = requestURI.substring((Latkes.getContextPath() + "/console/comments/page/").length());
        final List<JSONObject> comments = commentQueryService.getComments(pageId);
        ret.put(Comment.COMMENTS, comments);
        ret.put(Keys.STATUS_CODE, true);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        final JSONObject jsonObject = QueryResults.defaultResult();
        renderer.setJSONObject(jsonObject);
        jsonObject.put(Keys.MSG, langPropsService.get("getFailLabel"));
    }
}
Also used : JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 82 with RequestProcessing

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

the class LinkConsole method addLink.

/**
     * Adds a link with the specified request.
     * 
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": boolean,
     *     "oId": "", // Generated link id
     *     "msg": ""
     * }
     * </pre>
     * </p>
     * 
     * @param request the specified http servlet request, for example,
     * <pre>
     * {
     *     "link": {
     *         "linkTitle": "",
     *         "linkAddress": "",
     *         "linkDescription": ""
     *     }
     * }
     * </pre>
     * @param response the specified http servlet response
     * @param context the specified http request context
     * @throws Exception exception
     */
@RequestProcessing(value = "/console/link/", method = HTTPRequestMethod.POST)
public void addLink(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 ret = new JSONObject();
    try {
        final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response);
        final String linkId = linkMgmtService.addLink(requestJSONObject);
        ret.put(Keys.OBJECT_ID, linkId);
        ret.put(Keys.MSG, langPropsService.get("addSuccLabel"));
        ret.put(Keys.STATUS_CODE, true);
        renderer.setJSONObject(ret);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        final JSONObject jsonObject = QueryResults.defaultResult();
        renderer.setJSONObject(jsonObject);
        jsonObject.put(Keys.MSG, langPropsService.get("addFailLabel"));
    }
}
Also used : JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 83 with RequestProcessing

use of org.b3log.latke.servlet.annotation.RequestProcessing 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 84 with RequestProcessing

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

the class MetaWeblogAPI method metaWeblog.

/**
     * MetaWeblog requests processing.
     *
     * @param request the specified http servlet request
     * @param response the specified http servlet response
     * @param context the specified http request context
     */
@RequestProcessing(value = "/apis/metaweblog", method = HTTPRequestMethod.POST)
public void metaWeblog(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) {
    final TextXMLRenderer renderer = new TextXMLRenderer();
    context.setRenderer(renderer);
    String responseContent = null;
    try {
        final ServletInputStream inputStream = request.getInputStream();
        final String xml = IOUtils.toString(inputStream, "UTF-8");
        final JSONObject requestJSONObject = XML.toJSONObject(xml);
        final JSONObject methodCall = requestJSONObject.getJSONObject(METHOD_CALL);
        final String methodName = methodCall.getString(METHOD_NAME);
        LOGGER.log(Level.INFO, "MetaWeblog[methodName={0}]", methodName);
        final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");
        if (METHOD_DELETE_POST.equals(methodName)) {
            // Removes the first argument "appkey"
            params.remove(0);
        }
        final String userEmail = params.getJSONObject(INDEX_USER_EMAIL).getJSONObject("value").getString("string");
        final JSONObject user = userQueryService.getUserByEmail(userEmail);
        if (null == user) {
            throw new Exception("No user[email=" + userEmail + "]");
        }
        final String userPwd = params.getJSONObject(INDEX_USER_PWD).getJSONObject("value").getString("string");
        if (!user.getString(User.USER_PASSWORD).equals(MD5.hash(userPwd))) {
            throw new Exception("Wrong password");
        }
        if (METHOD_GET_USERS_BLOGS.equals(methodName)) {
            responseContent = getUsersBlogs();
        } else if (METHOD_GET_CATEGORIES.equals(methodName)) {
            responseContent = getCategories();
        } else if (METHOD_GET_RECENT_POSTS.equals(methodName)) {
            final int numOfPosts = params.getJSONObject(INDEX_NUM_OF_POSTS).getJSONObject("value").getInt("int");
            responseContent = getRecentPosts(numOfPosts);
        } else if (METHOD_NEW_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail);
            addArticle(article);
            final StringBuilder stringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>").append("<params><param><value><string>").append(article.getString(Keys.OBJECT_ID)).append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_GET_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value").getString("string");
            responseContent = getPost(postId);
        } else if (METHOD_EDIT_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value").getString("string");
            article.put(Keys.OBJECT_ID, postId);
            article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail);
            final JSONObject updateArticleRequest = new JSONObject();
            updateArticleRequest.put(Article.ARTICLE, article);
            articleMgmtService.updateArticle(updateArticleRequest);
            final StringBuilder stringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>").append("<params><param><value><string>").append(postId).append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_DELETE_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value").getString("string");
            articleMgmtService.removeArticle(postId);
            final StringBuilder stringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>").append("<params><param><value><boolean>").append(true).append("</boolean></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else {
            throw new UnsupportedOperationException("Unsupported method[name=" + methodName + "]");
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        final StringBuilder stringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>").append("<fault><value><struct>").append("<member><name>faultCode</name><value><int>500</int></value></member>").append("<member><name>faultString</name><value><string>").append(e.getMessage()).append("</string></value></member></struct></value></fault></methodResponse>");
        responseContent = stringBuilder.toString();
    }
    renderer.setContent(responseContent);
}
Also used : ServletInputStream(javax.servlet.ServletInputStream) JSONObject(org.json.JSONObject) TextXMLRenderer(org.b3log.latke.servlet.renderer.TextXMLRenderer) JSONArray(org.json.JSONArray) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException) ParseException(java.text.ParseException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 85 with RequestProcessing

use of org.b3log.latke.servlet.annotation.RequestProcessing 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)

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