PageRenderTime 286ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/b3log-solo/core/src/main/java/org/b3log/solo/web/processor/IndexProcessor.java

http://b3log-solo.googlecode.com/
Java | 321 lines | 210 code | 39 blank | 72 comment | 4 complexity | ba5aa134b7eec12277e4ef87fb8d5ff6 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1
  1. /*
  2. * Copyright (c) 2009, 2010, 2011, B3log Team
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.b3log.solo.web.processor;
  17. import org.b3log.latke.service.ServiceException;
  18. import org.b3log.solo.service.PreferenceQueryService;
  19. import org.b3log.solo.web.util.TopBars;
  20. import org.b3log.latke.util.Locales;
  21. import org.b3log.latke.servlet.renderer.freemarker.FreeMarkerRenderer;
  22. import freemarker.template.Template;
  23. import java.io.PrintWriter;
  24. import java.io.StringWriter;
  25. import org.b3log.latke.Latkes;
  26. import org.b3log.latke.service.LangPropsService;
  27. import org.b3log.solo.web.processor.renderer.FrontFreeMarkerRenderer;
  28. import java.io.IOException;
  29. import java.util.List;
  30. import java.util.Map;
  31. import java.util.logging.Level;
  32. import java.util.logging.Logger;
  33. import javax.servlet.http.HttpServletRequest;
  34. import javax.servlet.http.HttpServletResponse;
  35. import org.b3log.latke.annotation.RequestProcessing;
  36. import org.b3log.latke.annotation.RequestProcessor;
  37. import org.b3log.solo.web.util.Filler;
  38. import org.b3log.latke.model.Pagination;
  39. import org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer;
  40. import org.b3log.latke.servlet.HTTPRequestContext;
  41. import org.b3log.latke.servlet.HTTPRequestMethod;
  42. import org.b3log.latke.servlet.URIPatternMode;
  43. import org.b3log.solo.web.util.Requests;
  44. import org.b3log.solo.model.Article;
  45. import org.b3log.solo.model.Common;
  46. import org.b3log.solo.model.PageTypes;
  47. import org.b3log.solo.util.Skins;
  48. import org.json.JSONObject;
  49. import static org.b3log.latke.action.AbstractCacheablePageAction.*;
  50. /**
  51. * Index processor.
  52. *
  53. * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
  54. * @version 1.1.0.6, Nov 7, 2011
  55. * @since 0.3.1
  56. */
  57. @RequestProcessor
  58. public final class IndexProcessor {
  59. /**
  60. * Logger.
  61. */
  62. private static final Logger LOGGER =
  63. Logger.getLogger(IndexProcessor.class.getName());
  64. /**
  65. * Filler.
  66. */
  67. private Filler filler = Filler.getInstance();
  68. /**
  69. * Preference query service.
  70. */
  71. private PreferenceQueryService preferenceQueryService =
  72. PreferenceQueryService.getInstance();
  73. /**
  74. * Skin utilities.
  75. */
  76. private Skins skins = Skins.getInstance();
  77. /**
  78. * Language service.
  79. */
  80. private LangPropsService langPropsService = LangPropsService.getInstance();
  81. /**
  82. * Shows index with the specified context.
  83. *
  84. * @param context the specified context
  85. */
  86. @RequestProcessing(value = {"/\\d*"}, uriPatternsMode = URIPatternMode.REGEX,
  87. method = HTTPRequestMethod.GET)
  88. public void showIndex(final HTTPRequestContext context) {
  89. final AbstractFreeMarkerRenderer renderer =
  90. new FrontFreeMarkerRenderer();
  91. context.setRenderer(renderer);
  92. renderer.setTemplateName("index.ftl");
  93. final Map<String, Object> dataModel = renderer.getDataModel();
  94. final HttpServletRequest request = context.getRequest();
  95. final HttpServletResponse response = context.getResponse();
  96. final String requestURI = request.getRequestURI();
  97. try {
  98. final int currentPageNum = getCurrentPageNum(requestURI);
  99. final JSONObject preference = preferenceQueryService.getPreference();
  100. skins.fillSkinLangs(preference, dataModel);
  101. final Map<String, String> langs =
  102. langPropsService.getAll(Latkes.getLocale());
  103. request.setAttribute(CACHED_OID, "No id");
  104. request.setAttribute(CACHED_TITLE,
  105. langs.get(PageTypes.INDEX_ARTICLES)
  106. + " [" + langs.get("pageNumLabel") + "="
  107. + currentPageNum + "]");
  108. request.setAttribute(CACHED_TYPE,
  109. langs.get(PageTypes.INDEX_ARTICLES));
  110. request.setAttribute(CACHED_LINK, requestURI);
  111. filler.fillIndexArticles(dataModel, currentPageNum, preference);
  112. @SuppressWarnings("unchecked")
  113. final List<JSONObject> articles =
  114. (List<JSONObject>) dataModel.get(Article.ARTICLES);
  115. if (articles.isEmpty()) {
  116. try {
  117. response.sendError(HttpServletResponse.SC_NOT_FOUND);
  118. return;
  119. } catch (final IOException ex) {
  120. LOGGER.severe(ex.getMessage());
  121. }
  122. }
  123. filler.fillSide(dataModel, preference);
  124. filler.fillBlogHeader(dataModel, preference);
  125. filler.fillBlogFooter(dataModel, preference);
  126. dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, currentPageNum);
  127. final String previousPageNum =
  128. Integer.toString(currentPageNum > 1 ? currentPageNum - 1
  129. : 0);
  130. dataModel.put(Pagination.PAGINATION_PREVIOUS_PAGE_NUM,
  131. "0".equals(previousPageNum) ? "" : previousPageNum);
  132. final Integer pageCount =
  133. (Integer) dataModel.get(Pagination.PAGINATION_PAGE_COUNT);
  134. if (pageCount == currentPageNum + 1) { // The next page is the last page
  135. dataModel.put(Pagination.PAGINATION_NEXT_PAGE_NUM, "");
  136. } else {
  137. dataModel.put(Pagination.PAGINATION_NEXT_PAGE_NUM, currentPageNum
  138. + 1);
  139. }
  140. dataModel.put(Common.PATH, "");
  141. } catch (final ServiceException e) {
  142. LOGGER.log(Level.SEVERE, e.getMessage(), e);
  143. try {
  144. response.sendError(HttpServletResponse.SC_NOT_FOUND);
  145. } catch (final IOException ex) {
  146. LOGGER.severe(ex.getMessage());
  147. }
  148. }
  149. }
  150. /**
  151. * Handles errors with the specified context.
  152. *
  153. * @param context the specified context
  154. * @param request the specified request
  155. * @param response the specified response
  156. */
  157. @RequestProcessing(value = {"/error.do"}, method = HTTPRequestMethod.GET)
  158. public void handleErrors(final HTTPRequestContext context,
  159. final HttpServletRequest request,
  160. final HttpServletResponse response) {
  161. final AbstractFreeMarkerRenderer renderer = new FreeMarkerRenderer();
  162. context.setRenderer(renderer);
  163. renderer.setTemplateName("error.ftl");
  164. final Map<String, Object> dataModel = renderer.getDataModel();
  165. try {
  166. final JSONObject preference =
  167. preferenceQueryService.getPreference();
  168. // Adds the top bar HTML content for output
  169. final String topBarHTML = TopBars.getTopBarHTML(request, response);
  170. dataModel.put(Common.TOP_BAR_REPLACEMENT_FLAG_KEY,
  171. topBarHTML);
  172. skins.fillSkinLangs(preference, dataModel);
  173. filler.fillSide(dataModel, preference);
  174. filler.fillBlogHeader(dataModel, preference);
  175. filler.fillBlogFooter(dataModel, preference);
  176. } catch (final ServiceException e) {
  177. LOGGER.log(Level.SEVERE, e.getMessage(), e);
  178. try {
  179. response.sendError(HttpServletResponse.SC_NOT_FOUND);
  180. } catch (final IOException ex) {
  181. LOGGER.severe(ex.getMessage());
  182. }
  183. }
  184. }
  185. /**
  186. * Shows kill browser page with the specified context.
  187. *
  188. * @param context the specified context
  189. */
  190. @RequestProcessing(value = {"/kill-browser.html"},
  191. method = HTTPRequestMethod.GET)
  192. public void showKillBrowser(final HTTPRequestContext context) {
  193. final AbstractFreeMarkerRenderer renderer = new KillBrowserRenderer();
  194. context.setRenderer(renderer);
  195. final Map<String, Object> dataModel = renderer.getDataModel();
  196. final HttpServletRequest request = context.getRequest();
  197. final HttpServletResponse response = context.getResponse();
  198. try {
  199. final Map<String, String> langs =
  200. langPropsService.getAll(Locales.getLocale(request));
  201. dataModel.putAll(langs);
  202. final JSONObject preference = preferenceQueryService.getPreference();
  203. filler.fillBlogFooter(dataModel, preference);
  204. filler.fillMinified(dataModel);
  205. request.setAttribute(CACHED_OID, "No id");
  206. request.setAttribute(CACHED_TITLE, "Kill Browser Page");
  207. request.setAttribute(CACHED_TYPE,
  208. langs.get(PageTypes.KILL_BROWSER_PAGE));
  209. request.setAttribute(CACHED_LINK, request.getRequestURI());
  210. } catch (final ServiceException e) {
  211. LOGGER.log(Level.SEVERE, e.getMessage(), e);
  212. try {
  213. response.sendError(HttpServletResponse.SC_NOT_FOUND);
  214. } catch (final IOException ex) {
  215. LOGGER.severe(ex.getMessage());
  216. }
  217. }
  218. }
  219. /**
  220. * Gets the request page number from the specified request URI.
  221. *
  222. * @param requestURI the specified request URI
  223. * @return page number, returns {@code -1} if the specified request URI
  224. * can not convert to an number
  225. */
  226. private static int getCurrentPageNum(final String requestURI) {
  227. final String pageNumString = requestURI.substring("/".length());
  228. return Requests.getCurrentPageNum(pageNumString);
  229. }
  230. /**
  231. * Kill browser (kill-browser.ftl) HTTP response renderer.
  232. *
  233. * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
  234. * @version 1.0.0.0, Sep 18, 2011
  235. * @see 0.3.1
  236. */
  237. private static final class KillBrowserRenderer extends AbstractFreeMarkerRenderer {
  238. /**
  239. * Logger.
  240. */
  241. private static final Logger LOGGER =
  242. Logger.getLogger(KillBrowserRenderer.class.getName());
  243. @Override
  244. public void render(final HTTPRequestContext context) {
  245. final HttpServletResponse response = context.getResponse();
  246. response.setContentType("text/html");
  247. response.setCharacterEncoding("UTF-8");
  248. try {
  249. final Template template =
  250. InitProcessor.TEMPLATE_CFG.getTemplate(
  251. "kill-browser.ftl");
  252. final PrintWriter writer = response.getWriter();
  253. final StringWriter stringWriter = new StringWriter();
  254. template.setOutputEncoding("UTF-8");
  255. template.process(getDataModel(), stringWriter);
  256. final String pageContent = stringWriter.toString();
  257. context.getRequest().setAttribute(CACHED_CONTENT, pageContent);
  258. writer.write(pageContent);
  259. writer.flush();
  260. writer.close();
  261. } catch (final Exception e) {
  262. try {
  263. response.sendError(
  264. HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
  265. return;
  266. } catch (final IOException ex) {
  267. LOGGER.log(Level.SEVERE, "Can not sned error 500!", ex);
  268. }
  269. }
  270. }
  271. @Override
  272. protected void afterRender(final HTTPRequestContext context)
  273. throws Exception {
  274. throw new UnsupportedOperationException("Not supported yet.");
  275. }
  276. @Override
  277. protected void beforeRender(final HTTPRequestContext context) throws
  278. Exception {
  279. throw new UnsupportedOperationException("Not supported yet.");
  280. }
  281. }
  282. }