Search in sources :

Example 1 with AbstractFreeMarkerRenderer

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

the class ArticleProcessor method showAuthorArticles.

/**
     * Shows author articles with the specified context.
     *
     * @param context the specified context
     * @param request the specified request
     * @param response the specified response
     * @throws IOException io exception
     * @throws JSONException json exception
     */
@RequestProcessing(value = "/authors/**", method = HTTPRequestMethod.GET)
public void showAuthorArticles(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws IOException, JSONException {
    final AbstractFreeMarkerRenderer renderer = new FreeMarkerRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("author-articles.ftl");
    try {
        String requestURI = request.getRequestURI();
        if (!requestURI.endsWith("/")) {
            requestURI += "/";
        }
        final String authorId = getAuthorId(requestURI);
        LOGGER.log(Level.DEBUG, "Request author articles[requestURI={0}, authorId={1}]", new Object[] { requestURI, authorId });
        final int currentPageNum = getAuthorCurrentPageNum(requestURI, authorId);
        if (-1 == currentPageNum) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        LOGGER.log(Level.DEBUG, "Request author articles[authorId={0}, currentPageNum={1}]", new Object[] { authorId, currentPageNum });
        final JSONObject preference = preferenceQueryService.getPreference();
        if (null == preference) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        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 JSONObject result = userQueryService.getUser(authorId);
        if (null == result) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        final JSONObject author = result.getJSONObject(User.USER);
        final String authorEmail = author.getString(User.USER_EMAIL);
        final List<JSONObject> articles = articleQueryService.getArticlesByAuthorEmail(authorEmail, currentPageNum, pageSize);
        if (articles.isEmpty()) {
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            } catch (final IOException ex) {
                LOGGER.error(ex.getMessage());
            }
        }
        filler.setArticlesExProperties(request, articles, author, preference);
        if (preference.optBoolean(Option.ID_C_ENABLE_ARTICLE_UPDATE_HINT)) {
            Collections.sort(articles, Comparators.ARTICLE_UPDATE_DATE_COMPARATOR);
        } else {
            Collections.sort(articles, Comparators.ARTICLE_CREATE_DATE_COMPARATOR);
        }
        final int articleCount = author.getInt(UserExt.USER_PUBLISHED_ARTICLE_COUNT);
        final int pageCount = (int) Math.ceil((double) articleCount / (double) pageSize);
        final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize);
        final Map<String, Object> dataModel = renderer.getDataModel();
        prepareShowAuthorArticles(pageNums, dataModel, pageCount, currentPageNum, articles, author);
        filler.fillBlogHeader(request, response, dataModel, preference);
        filler.fillBlogFooter(request, dataModel, preference);
        filler.fillSide(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 ServiceException 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) ServiceException(org.b3log.latke.service.ServiceException) 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) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 2 with AbstractFreeMarkerRenderer

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

the class ArticleProcessor method showArchiveArticles.

/**
     * Shows archive articles with the specified context.
     *
     * @param context the specified context
     * @param request the specified request
     * @param response the specified response
     */
@RequestProcessing(value = "/archives/**", method = HTTPRequestMethod.GET)
public void showArchiveArticles(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) {
    final AbstractFreeMarkerRenderer renderer = new FreeMarkerRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("archive-articles.ftl");
    try {
        String requestURI = request.getRequestURI();
        if (!requestURI.endsWith("/")) {
            requestURI += "/";
        }
        final String archiveDateString = getArchiveDate(requestURI);
        final int currentPageNum = getArchiveCurrentPageNum(requestURI);
        if (-1 == currentPageNum) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        LOGGER.log(Level.DEBUG, "Request archive date[string={0}, currentPageNum={1}]", new Object[] { archiveDateString, currentPageNum });
        final JSONObject result = archiveDateQueryService.getByArchiveDateString(archiveDateString);
        if (null == result) {
            LOGGER.log(Level.WARN, "Can not find articles for the specified archive date[string={0}]", archiveDateString);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        final JSONObject archiveDate = result.getJSONObject(ArchiveDate.ARCHIVE_DATE);
        final String archiveDateId = archiveDate.getString(Keys.OBJECT_ID);
        final JSONObject preference = preferenceQueryService.getPreference();
        final int pageSize = preference.getInt(Option.ID_C_ARTICLE_LIST_DISPLAY_COUNT);
        final int articleCount = archiveDate.getInt(ArchiveDate.ARCHIVE_DATE_PUBLISHED_ARTICLE_COUNT);
        final int pageCount = (int) Math.ceil((double) articleCount / (double) pageSize);
        final List<JSONObject> articles = articleQueryService.getArticlesByArchiveDate(archiveDateId, 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 if (!articles.isEmpty()) {
            final JSONObject author = articleQueryService.getAuthor(articles.get(0));
            filler.setArticlesExProperties(request, articles, author, preference);
        }
        sort(preference, articles);
        final Map<String, Object> dataModel = renderer.getDataModel();
        Skins.fillLangs(preference.optString(Option.ID_C_LOCALE_STRING), (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), dataModel);
        prepareShowArchiveArticles(preference, dataModel, articles, currentPageNum, pageCount, archiveDateString, archiveDate);
        filler.fillBlogHeader(request, response, dataModel, preference);
        filler.fillBlogFooter(request, dataModel, preference);
        filler.fillSide(request, dataModel, preference);
        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) 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)

Example 3 with AbstractFreeMarkerRenderer

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

the class PageProcessor method showPage.

/**
     * Shows page with the specified context.
     *
     * @param context the specified context
     */
@RequestProcessing(value = "/page", method = HTTPRequestMethod.GET)
public void showPage(final HTTPRequestContext context) {
    final AbstractFreeMarkerRenderer renderer = new FreeMarkerRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("page.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();
    final HttpServletRequest request = context.getRequest();
    final HttpServletResponse response = context.getResponse();
    try {
        final JSONObject preference = preferenceQueryService.getPreference();
        if (null == preference) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        Skins.fillLangs(preference.getString(Option.ID_C_LOCALE_STRING), (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), dataModel);
        // See PermalinkFilter#dispatchToArticleOrPageProcessor()
        final JSONObject page = (JSONObject) request.getAttribute(Page.PAGE);
        if (null == page) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        final String pageId = page.getString(Keys.OBJECT_ID);
        page.put(Common.COMMENTABLE, preference.getBoolean(Option.ID_C_COMMENTABLE) && page.getBoolean(Page.PAGE_COMMENTABLE));
        page.put(Common.PERMALINK, page.getString(Page.PAGE_PERMALINK));
        dataModel.put(Page.PAGE, page);
        final List<JSONObject> comments = commentQueryService.getComments(pageId);
        dataModel.put(Page.PAGE_COMMENTS_REF, comments);
        // Markdown
        if ("CodeMirror-Markdown".equals(page.optString(Page.PAGE_EDITOR_TYPE))) {
            Stopwatchs.start("Markdown Page[id=" + page.optString(Keys.OBJECT_ID) + "]");
            String content = page.optString(Page.PAGE_CONTENT);
            content = Emotions.convert(content);
            content = Markdowns.toHTML(content);
            page.put(Page.PAGE_CONTENT, content);
            Stopwatchs.end();
        }
        filler.fillSide(request, dataModel, preference);
        filler.fillBlogHeader(request, response, dataModel, preference);
        filler.fillBlogFooter(request, dataModel, preference);
        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 : HttpServletRequest(javax.servlet.http.HttpServletRequest) JSONObject(org.json.JSONObject) HttpServletResponse(javax.servlet.http.HttpServletResponse) 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) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 4 with AbstractFreeMarkerRenderer

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

the class AdminConsole method showAdminPreferenceFunction.

/**
     * Shows administrator preference function with the specified context.
     *
     * @param request the specified request
     * @param context the specified context
     */
@RequestProcessing(value = "/admin-preference.do", method = HTTPRequestMethod.GET)
public void showAdminPreferenceFunction(final HttpServletRequest request, final HTTPRequestContext context) {
    final AbstractFreeMarkerRenderer renderer = new ConsoleRenderer();
    context.setRenderer(renderer);
    final String templateName = "admin-preference.ftl";
    renderer.setTemplateName(templateName);
    final Locale locale = Latkes.getLocale();
    final Map<String, String> langs = langPropsService.getAll(locale);
    final Map<String, Object> dataModel = renderer.getDataModel();
    dataModel.putAll(langs);
    dataModel.put(Option.ID_C_LOCALE_STRING, locale.toString());
    JSONObject preference = null;
    try {
        preference = preferenceQueryService.getPreference();
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, "Loads preference failed", e);
    }
    final StringBuilder timeZoneIdOptions = new StringBuilder();
    final String[] availableIDs = TimeZone.getAvailableIDs();
    for (int i = 0; i < availableIDs.length; i++) {
        final String id = availableIDs[i];
        String option;
        if (id.equals(preference.optString(Option.ID_C_TIME_ZONE_ID))) {
            option = "<option value=\"" + id + "\" selected=\"true\">" + id + "</option>";
        } else {
            option = "<option value=\"" + id + "\">" + id + "</option>";
        }
        timeZoneIdOptions.append(option);
    }
    dataModel.put("timeZoneIdOptions", timeZoneIdOptions.toString());
    fireFreeMarkerActionEvent(templateName, dataModel);
}
Also used : Locale(java.util.Locale) JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) 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 5 with AbstractFreeMarkerRenderer

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

the class AdminConsole method showAdminIndex.

/**
     * Shows administrator index with the specified context.
     *
     * @param request the specified request
     * @param context the specified context
     */
@RequestProcessing(value = "/admin-index.do", method = HTTPRequestMethod.GET)
public void showAdminIndex(final HttpServletRequest request, final HTTPRequestContext context) {
    final AbstractFreeMarkerRenderer renderer = new ConsoleRenderer();
    context.setRenderer(renderer);
    final String templateName = "admin-index.ftl";
    renderer.setTemplateName(templateName);
    final Map<String, String> langs = langPropsService.getAll(Latkes.getLocale());
    final Map<String, Object> dataModel = renderer.getDataModel();
    dataModel.putAll(langs);
    final JSONObject currentUser = userQueryService.getCurrentUser(request);
    final String userName = currentUser.optString(User.USER_NAME);
    dataModel.put(User.USER_NAME, userName);
    final String roleName = currentUser.optString(User.USER_ROLE);
    dataModel.put(User.USER_ROLE, roleName);
    final String email = currentUser.optString(User.USER_EMAIL);
    final String userAvatar = currentUser.optString(UserExt.USER_AVATAR);
    if (!Strings.isEmptyOrNull(userAvatar)) {
        dataModel.put(Common.GRAVATAR, userAvatar);
    } else {
        final String gravatar = Thumbnails.getGravatarURL(email, "128");
        dataModel.put(Common.GRAVATAR, gravatar);
    }
    try {
        final JSONObject qiniu = optionQueryService.getOptions(Option.CATEGORY_C_QINIU);
        dataModel.put(Option.ID_C_QINIU_DOMAIN, "");
        dataModel.put("qiniuUploadToken", "");
        if (null != qiniu && StringUtils.isNotBlank(qiniu.optString(Option.ID_C_QINIU_ACCESS_KEY)) && StringUtils.isNotBlank(qiniu.optString(Option.ID_C_QINIU_SECRET_KEY)) && StringUtils.isNotBlank(qiniu.optString(Option.ID_C_QINIU_BUCKET)) && StringUtils.isNotBlank(qiniu.optString(Option.ID_C_QINIU_DOMAIN))) {
            try {
                final Auth auth = Auth.create(qiniu.optString(Option.ID_C_QINIU_ACCESS_KEY), qiniu.optString(Option.ID_C_QINIU_SECRET_KEY));
                final String uploadToken = auth.uploadToken(qiniu.optString(Option.ID_C_QINIU_BUCKET), null, 3600 * 6, null);
                dataModel.put("qiniuUploadToken", uploadToken);
                dataModel.put(Option.ID_C_QINIU_DOMAIN, qiniu.optString(Option.ID_C_QINIU_DOMAIN));
            } catch (final Exception e) {
                LOGGER.log(Level.ERROR, "Qiniu settings error", e);
            }
        }
        final JSONObject preference = preferenceQueryService.getPreference();
        dataModel.put(Option.ID_C_LOCALE_STRING, preference.getString(Option.ID_C_LOCALE_STRING));
        dataModel.put(Option.ID_C_BLOG_TITLE, preference.getString(Option.ID_C_BLOG_TITLE));
        dataModel.put(Option.ID_C_BLOG_SUBTITLE, preference.getString(Option.ID_C_BLOG_SUBTITLE));
        dataModel.put(Common.VERSION, SoloServletListener.VERSION);
        dataModel.put(Common.STATIC_RESOURCE_VERSION, Latkes.getStaticResourceVersion());
        dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
        dataModel.put(Option.ID_C_ARTICLE_LIST_DISPLAY_COUNT, preference.getInt(Option.ID_C_ARTICLE_LIST_DISPLAY_COUNT));
        dataModel.put(Option.ID_C_ARTICLE_LIST_PAGINATION_WINDOW_SIZE, preference.getInt(Option.ID_C_ARTICLE_LIST_PAGINATION_WINDOW_SIZE));
        dataModel.put(Option.ID_C_LOCALE_STRING, preference.getString(Option.ID_C_LOCALE_STRING));
        dataModel.put(Option.ID_C_EDITOR_TYPE, preference.getString(Option.ID_C_EDITOR_TYPE));
        dataModel.put(Skin.SKIN_DIR_NAME, preference.getString(Skin.SKIN_DIR_NAME));
        Keys.fillRuntime(dataModel);
        filler.fillMinified(dataModel);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Admin index render failed", e);
    }
    fireFreeMarkerActionEvent(templateName, dataModel);
}
Also used : JSONObject(org.json.JSONObject) Auth(com.qiniu.util.Auth) JSONObject(org.json.JSONObject) ConsoleRenderer(org.b3log.solo.processor.renderer.ConsoleRenderer) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) EventException(org.b3log.latke.event.EventException) ServiceException(org.b3log.latke.service.ServiceException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Aggregations

AbstractFreeMarkerRenderer (org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer)120 RequestProcessing (org.b3log.latke.servlet.annotation.RequestProcessing)119 JSONObject (org.json.JSONObject)117 After (org.b3log.latke.servlet.annotation.After)105 Before (org.b3log.latke.servlet.annotation.Before)105 ServiceException (org.b3log.latke.service.ServiceException)22 IOException (java.io.IOException)15 Date (java.util.Date)12 ArrayList (java.util.ArrayList)8 JSONArray (org.json.JSONArray)8 Auth (com.qiniu.util.Auth)7 FreeMarkerRenderer (org.b3log.latke.servlet.renderer.freemarker.FreeMarkerRenderer)7 ConsoleRenderer (org.b3log.solo.processor.renderer.ConsoleRenderer)7 ParseException (java.text.ParseException)6 List (java.util.List)6 EventException (org.b3log.latke.event.EventException)3 JSONException (org.json.JSONException)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Locale (java.util.Locale)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2