Search in sources :

Example 61 with RequestProcessing

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

the class TagProcessor method showTagArticles.

/**
     * Shows articles related with a tag with the specified context.
     *
     * @param context the specified context
     * @throws IOException io exception
     */
@RequestProcessing(value = "/tags/**", method = HTTPRequestMethod.GET)
public void showTagArticles(final HTTPRequestContext context) throws IOException {
    final AbstractFreeMarkerRenderer renderer = new FreeMarkerRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("tag-articles.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();
    final HttpServletRequest request = context.getRequest();
    final HttpServletResponse response = context.getResponse();
    try {
        String requestURI = request.getRequestURI();
        if (!requestURI.endsWith("/")) {
            requestURI += "/";
        }
        String tagTitle = getTagTitle(requestURI);
        final int currentPageNum = getCurrentPageNum(requestURI, tagTitle);
        if (-1 == currentPageNum) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        LOGGER.log(Level.DEBUG, "Tag[title={0}, currentPageNum={1}]", new Object[] { tagTitle, currentPageNum });
        tagTitle = URLDecoder.decode(tagTitle, "UTF-8");
        final JSONObject result = tagQueryService.getTagByTitle(tagTitle);
        if (null == result) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        final JSONObject tag = result.getJSONObject(Tag.TAG);
        final String tagId = tag.getString(Keys.OBJECT_ID);
        final JSONObject preference = preferenceQueryService.getPreference();
        Skins.fillLangs(preference.optString(Option.ID_C_LOCALE_STRING), (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), dataModel);
        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 List<JSONObject> articles = articleQueryService.getArticlesByTag(tagId, currentPageNum, pageSize);
        if (articles.isEmpty()) {
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            } catch (final IOException ex) {
                LOGGER.error(ex.getMessage());
            }
        }
        final boolean hasMultipleUsers = userQueryService.hasMultipleUsers();
        if (hasMultipleUsers) {
            filler.setArticlesExProperties(request, articles, preference);
        } else {
            // All articles composed by the same author
            final JSONObject author = articleQueryService.getAuthor(articles.get(0));
            filler.setArticlesExProperties(request, articles, author, preference);
        }
        final int tagArticleCount = tag.getInt(Tag.TAG_PUBLISHED_REFERENCE_COUNT);
        final int pageCount = (int) Math.ceil((double) tagArticleCount / (double) pageSize);
        LOGGER.log(Level.TRACE, "Paginate tag-articles[currentPageNum={0}, pageSize={1}, pageCount={2}, windowSize={3}]", new Object[] { currentPageNum, pageSize, pageCount, windowSize });
        final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize);
        LOGGER.log(Level.TRACE, "tag-articles[pageNums={0}]", pageNums);
        Collections.sort(articles, Comparators.ARTICLE_CREATE_DATE_COMPARATOR);
        fillPagination(dataModel, pageCount, currentPageNum, articles, pageNums);
        dataModel.put(Common.PATH, "/tags/" + URLEncoder.encode(tagTitle, "UTF-8"));
        dataModel.put(Keys.OBJECT_ID, tagId);
        dataModel.put(Tag.TAG, tag);
        filler.fillSide(request, dataModel, preference);
        filler.fillBlogHeader(request, response, dataModel, preference);
        filler.fillBlogFooter(request, dataModel, preference);
        statisticMgmtService.incBlogViewCount(request, response);
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (final IOException ex) {
            LOGGER.error(ex.getMessage());
        }
    } catch (final JSONException 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 : HttpServletResponse(javax.servlet.http.HttpServletResponse) JSONException(org.json.JSONException) FreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.FreeMarkerRenderer) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) IOException(java.io.IOException) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) HttpServletRequest(javax.servlet.http.HttpServletRequest) JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) JSONObject(org.json.JSONObject) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 62 with RequestProcessing

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

the class UserTemplateProcessor method showPage.

/**
     * 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 = "/*.html", method = HTTPRequestMethod.GET)
public void showPage(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 page[requestURI={0}, templateName={1}]", new Object[] { requestURI, templateName });
    final AbstractFreeMarkerRenderer renderer = new FreeMarkerRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName(templateName);
    final Map<String, Object> dataModel = renderer.getDataModel();
    final Template template = Templates.getTemplate((String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), templateName);
    if (null == template) {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        } catch (final IOException ex) {
            LOGGER.error(ex.getMessage());
        }
    }
    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.fillUserTemplate(request, template, dataModel, preference);
        filler.fillBlogFooter(request, dataModel, preference);
        Skins.fillLangs(preference.optString(Option.ID_C_LOCALE_STRING), (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), dataModel);
        statisticMgmtService.incBlogViewCount(request, response);
    } 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) FreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.FreeMarkerRenderer) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) IOException(java.io.IOException) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) IOException(java.io.IOException) Template(freemarker.template.Template) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 63 with RequestProcessing

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

the class AdminConsole method showAdminFunctions.

/**
     * Shows administrator functions with the specified context.
     *
     * @param request the specified request
     * @param context the specified context
     */
@RequestProcessing(value = { "/admin-article.do", "/admin-article-list.do", "/admin-comment-list.do", "/admin-link-list.do", "/admin-page-list.do", "/admin-others.do", "/admin-draft-list.do", "/admin-user-list.do", "/admin-plugin-list.do", "/admin-main.do", "/admin-about.do" }, method = HTTPRequestMethod.GET)
public void showAdminFunctions(final HttpServletRequest request, final HTTPRequestContext context) {
    final AbstractFreeMarkerRenderer renderer = new ConsoleRenderer();
    context.setRenderer(renderer);
    final String requestURI = request.getRequestURI();
    final String templateName = StringUtils.substringBetween(requestURI, Latkes.getContextPath() + '/', ".") + ".ftl";
    LOGGER.log(Level.TRACE, "Admin function[templateName={0}]", templateName);
    renderer.setTemplateName(templateName);
    final Locale locale = Latkes.getLocale();
    final Map<String, String> langs = langPropsService.getAll(locale);
    final Map<String, Object> dataModel = renderer.getDataModel();
    dataModel.put("isMySQL", RuntimeDatabase.MYSQL == Latkes.getRuntimeDatabase());
    dataModel.putAll(langs);
    Keys.fillRuntime(dataModel);
    dataModel.put(Option.ID_C_LOCALE_STRING, locale.toString());
    fireFreeMarkerActionEvent(templateName, dataModel);
}
Also used : Locale(java.util.Locale) JSONObject(org.json.JSONObject) ConsoleRenderer(org.b3log.solo.processor.renderer.ConsoleRenderer) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 64 with RequestProcessing

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

the class ArticleConsole method removeArticle.

/**
     * Removes an article by the specified request.
     *
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": boolean,
     *     "msg": ""
     * }
     * </pre>
     * </p>
     *
     * @param context the specified http request context
     * @param request the specified http servlet request
     * @param response the specified http servlet response
     * @param articleId the specified article id
     * @throws Exception exception
     */
@RequestProcessing(value = "/console/article/{articleId}", method = HTTPRequestMethod.DELETE)
public void removeArticle(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response, final String articleId) throws Exception {
    if (!userQueryService.isLoggedIn(request, response)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject ret = new JSONObject();
    renderer.setJSONObject(ret);
    try {
        if (!articleQueryService.canAccessArticle(articleId, request)) {
            ret.put(Keys.STATUS_CODE, false);
            ret.put(Keys.MSG, langPropsService.get("forbiddenLabel"));
            return;
        }
        articleMgmtService.removeArticle(articleId);
        ret.put(Keys.STATUS_CODE, true);
        ret.put(Keys.MSG, langPropsService.get("removeSuccLabel"));
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        final JSONObject jsonObject = new JSONObject();
        renderer.setJSONObject(jsonObject);
        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) ServiceException(org.b3log.latke.service.ServiceException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 65 with RequestProcessing

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

the class PageConsole method addPage.

/**
     * Adds a page with the specified request.
     * 
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": boolean,
     *     "oId": "", // Generated page id
     *     "msg": ""
     * }
     * </pre>
     * </p>
     * 
     * @param context the specified http request context
     * @param request the specified http servlet request, for example,
     * <pre>
     * {
     *     "page": {
     *         "pageTitle": "",
     *         "pageContent": "",
     *         "pagePermalink": "" // optional,
     *         "pageCommentable": boolean,
     *         "pageType": "",
     *         "pageOpenTarget": ""
     *     }
     * }, see {@link org.b3log.solo.model.Page} for more details
     * </pre>
     * @param response the specified http servlet response
     * @throws Exception exception
     */
@RequestProcessing(value = "/console/page/", method = HTTPRequestMethod.POST)
public void addPage(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) 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 pageId = pageMgmtService.addPage(requestJSONObject);
        ret.put(Keys.OBJECT_ID, pageId);
        ret.put(Keys.MSG, langPropsService.get("addSuccLabel"));
        ret.put(Keys.STATUS_CODE, true);
        renderer.setJSONObject(ret);
    } catch (final ServiceException e) {
        // May be permalink check exception
        LOGGER.log(Level.WARN, 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