Search in sources :

Example 1 with RequestProcessing

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

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

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

the class ArticleProcessor method onArticlePwdForm.

/**
     * Processes the article view password form submits.
     *
     * @param context the specified context
     * @param request the specified HTTP servlet request
     * @param response the specified HTTP servlet response
     * @throws Exception exception
     */
@RequestProcessing(value = "/console/article-pwd", method = HTTPRequestMethod.POST)
public void onArticlePwdForm(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    try {
        final String articleId = request.getParameter("articleId");
        final String pwdTyped = request.getParameter("pwdTyped");
        final JSONObject article = articleQueryService.getArticleById(articleId);
        if (article.getString(Article.ARTICLE_VIEW_PWD).equals(pwdTyped)) {
            final HttpSession session = request.getSession(false);
            if (null != session) {
                @SuppressWarnings("unchecked") Map<String, String> viewPwds = (Map<String, String>) session.getAttribute(Common.ARTICLES_VIEW_PWD);
                if (null == viewPwds) {
                    viewPwds = new HashMap<String, String>();
                }
                viewPwds.put(articleId, pwdTyped);
                session.setAttribute(Common.ARTICLES_VIEW_PWD, viewPwds);
            }
            response.sendRedirect(Latkes.getServePath() + article.getString(Article.ARTICLE_PERMALINK));
            return;
        }
        response.sendRedirect(Latkes.getServePath() + "/console/article-pwd?articleId=" + article.optString(Keys.OBJECT_ID) + "&msg=1");
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Processes article view password form submits failed", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}
Also used : JSONObject(org.json.JSONObject) HttpSession(javax.servlet.http.HttpSession) 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 4 with RequestProcessing

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

the class BlogProcessor method getBlogInfo.

/**
     * Gets blog information.
     *
     * <ul>
     * <li>Time of the recent updated article</li>
     * <li>Article count</li>
     * <li>Comment count</li>
     * <li>Tag count</li>
     * <li>Serve path</li>
     * <li>Static serve path</li>
     * <li>Solo version</li>
     * <li>Runtime environment (LOCAL)</li>
     * <li>Locale</li>
     * </ul>
     *
     * @param context the specified context
     * @throws Exception exception
     */
@RequestProcessing(value = "/blog/info", method = HTTPRequestMethod.GET)
public void getBlogInfo(final HTTPRequestContext context) throws Exception {
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject jsonObject = new JSONObject();
    renderer.setJSONObject(jsonObject);
    jsonObject.put("recentArticleTime", articleQueryService.getRecentArticleTime());
    final JSONObject statistic = statisticQueryService.getStatistic();
    jsonObject.put("articleCount", statistic.getLong(Statistic.STATISTIC_PUBLISHED_ARTICLE_COUNT));
    jsonObject.put("commentCount", statistic.getLong(Statistic.STATISTIC_PUBLISHED_BLOG_COMMENT_COUNT));
    jsonObject.put("tagCount", tagQueryService.getTagCount());
    jsonObject.put("servePath", Latkes.getServePath());
    jsonObject.put("staticServePath", Latkes.getStaticServePath());
    jsonObject.put("version", SoloServletListener.VERSION);
    jsonObject.put("locale", Latkes.getLocale());
    jsonObject.put("runtimeMode", Latkes.getRuntimeMode());
    final RuntimeEnv runtimeEnv = Latkes.getRuntimeEnv();
    jsonObject.put("runtimeEnv", runtimeEnv);
    if (RuntimeEnv.LOCAL == runtimeEnv) {
        jsonObject.put("runtimeDatabase", Latkes.getRuntimeDatabase());
    }
}
Also used : JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) RuntimeEnv(org.b3log.latke.RuntimeEnv) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 5 with RequestProcessing

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

the class BlogProcessor method syncUser.

/**
     * Sync user to https://hacpai.com.
     *
     * @param context the specified context
     * @throws Exception exception
     */
@RequestProcessing(value = "/blog/symphony/user", method = HTTPRequestMethod.GET)
public void syncUser(final HTTPRequestContext context) throws Exception {
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject jsonObject = new JSONObject();
    renderer.setJSONObject(jsonObject);
    if (Latkes.getServePath().contains("localhost")) {
        return;
    }
    final JSONObject preference = preferenceQueryService.getPreference();
    if (null == preference) {
        // not init yet
        return;
    }
    final HTTPRequest httpRequest = new HTTPRequest();
    httpRequest.setURL(new URL(SoloServletListener.B3LOG_SYMPHONY_SERVE_PATH + "/apis/user"));
    httpRequest.setRequestMethod(HTTPRequestMethod.POST);
    final JSONObject requestJSONObject = new JSONObject();
    final JSONObject admin = userQueryService.getAdmin();
    requestJSONObject.put(User.USER_NAME, admin.getString(User.USER_NAME));
    requestJSONObject.put(User.USER_EMAIL, admin.getString(User.USER_EMAIL));
    requestJSONObject.put(User.USER_PASSWORD, admin.getString(User.USER_PASSWORD));
    requestJSONObject.put("userB3Key", preference.optString(Option.ID_C_KEY_OF_SOLO));
    requestJSONObject.put("clientHost", Latkes.getServePath());
    httpRequest.setPayload(requestJSONObject.toString().getBytes("UTF-8"));
    urlFetchService.fetchAsync(httpRequest);
}
Also used : HTTPRequest(org.b3log.latke.urlfetch.HTTPRequest) JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) URL(java.net.URL) 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