JForum.java
Upload User: gdxydsw
Upload Date: 2019-01-29
Package Size: 16721k
Code Size: 10k
Category:

Java Develop

Development Platform:

Java

  1. /*
  2.  * Copyright (c) JForum Team
  3.  * All rights reserved.
  4.  * 
  5.  * Redistribution and use in source and binary forms, 
  6.  * with or without modification, are permitted provided 
  7.  * that the following conditions are met:
  8.  * 
  9.  * 1) Redistributions of source code must retain the above 
  10.  * copyright notice, this list of conditions and the 
  11.  * following  disclaimer.
  12.  * 2)  Redistributions in binary form must reproduce the 
  13.  * above copyright notice, this list of conditions and 
  14.  * the following disclaimer in the documentation and/or 
  15.  * other materials provided with the distribution.
  16.  * 3) Neither the name of "Rafael Steil" nor 
  17.  * the names of its contributors may be used to endorse 
  18.  * or promote products derived from this software without 
  19.  * specific prior written permission.
  20.  * 
  21.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 
  22.  * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
  23.  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
  24.  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
  25.  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
  26.  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
  27.  * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 
  28.  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
  29.  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
  30.  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
  31.  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
  32.  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
  33.  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
  34.  * IN CONTRACT, STRICT LIABILITY, OR TORT 
  35.  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
  36.  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
  37.  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
  38.  * 
  39.  * This file creation date: Mar 3, 2003 / 11:43:35 AM
  40.  * The JForum Project
  41.  * http://www.jforum.net
  42.  */
  43. package net.jforum;
  44. import java.io.BufferedWriter;
  45. import java.io.IOException;
  46. import java.io.OutputStreamWriter;
  47. import java.io.Writer;
  48. import java.sql.Connection;
  49. import javax.servlet.ServletConfig;
  50. import javax.servlet.ServletException;
  51. import javax.servlet.http.HttpServletRequest;
  52. import javax.servlet.http.HttpServletResponse;
  53. import net.jforum.context.JForumContext;
  54. import net.jforum.context.RequestContext;
  55. import net.jforum.context.ResponseContext;
  56. import net.jforum.context.web.WebRequestContext;
  57. import net.jforum.context.web.WebResponseContext;
  58. import net.jforum.dao.MySQLVersionWorkarounder;
  59. import net.jforum.entities.Banlist;
  60. import net.jforum.exceptions.ExceptionWriter;
  61. import net.jforum.exceptions.ForumStartupException;
  62. import net.jforum.repository.BanlistRepository;
  63. import net.jforum.repository.ModulesRepository;
  64. import net.jforum.repository.RankingRepository;
  65. import net.jforum.repository.SecurityRepository;
  66. import net.jforum.repository.SmiliesRepository;
  67. import net.jforum.util.I18n;
  68. import net.jforum.util.preferences.ConfigKeys;
  69. import net.jforum.util.preferences.SystemGlobals;
  70. import freemarker.template.SimpleHash;
  71. import freemarker.template.Template;
  72. /**
  73.  * Front Controller.
  74.  * 
  75.  * @author Rafael Steil
  76.  * @version $Id: JForum.java,v 1.116 2007/10/10 04:54:20 rafaelsteil Exp $
  77.  */
  78. public class JForum extends JForumBaseServlet 
  79. {
  80. private static boolean isDatabaseUp;
  81. /**
  82.  * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
  83.  */
  84. public void init(ServletConfig config) throws ServletException
  85. {
  86. super.init(config);
  87. super.startApplication();
  88. // Start database
  89. isDatabaseUp = ForumStartup.startDatabase();
  90. try {
  91. Connection conn = DBConnection.getImplementation().getConnection();
  92. conn.setAutoCommit(!SystemGlobals.getBoolValue(ConfigKeys.DATABASE_USE_TRANSACTIONS));
  93. // Try to fix some MySQL problems
  94. MySQLVersionWorkarounder dw = new MySQLVersionWorkarounder();
  95. dw.handleWorkarounds(conn);
  96. // Continues loading the forum
  97. JForumExecutionContext ex = JForumExecutionContext.get();
  98. ex.setConnection(conn);
  99. JForumExecutionContext.set(ex);
  100. // Init general forum stuff
  101. ForumStartup.startForumRepository();
  102. RankingRepository.loadRanks();
  103. SmiliesRepository.loadSmilies();
  104. BanlistRepository.loadBanlist();
  105. }
  106. catch (Throwable e) {
  107.             e.printStackTrace();
  108.             throw new ForumStartupException("Error while starting jforum", e);
  109. }
  110. finally {
  111. JForumExecutionContext.finish();
  112. }
  113. }
  114. /**
  115.  * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
  116.  */
  117. public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
  118. {
  119. Writer out = null;
  120. JForumContext forumContext = null;
  121. RequestContext request = null;
  122. ResponseContext response = null;
  123. String encoding = SystemGlobals.getValue(ConfigKeys.ENCODING);
  124. try {
  125. // Initializes the execution context
  126. JForumExecutionContext ex = JForumExecutionContext.get();
  127. request = new WebRequestContext(req);
  128.             response = new WebResponseContext(res);
  129. this.checkDatabaseStatus();
  130.             forumContext = new JForumContext(request.getContextPath(),
  131.                 SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION),
  132.                 request,
  133.                 response
  134.             );
  135.             ex.setForumContext(forumContext);
  136.             JForumExecutionContext.set(ex);
  137. // Setup stuff
  138. SimpleHash context = JForumExecutionContext.getTemplateContext();
  139. ControllerUtils utils = new ControllerUtils();
  140. utils.refreshSession();
  141. context.put("logged", SessionFacade.isLogged());
  142. // Process security data
  143. SecurityRepository.load(SessionFacade.getUserSession().getUserId());
  144. utils.prepareTemplateContext(context, forumContext);
  145. String module = request.getModule();
  146. // Gets the module class name
  147. String moduleClass = module != null 
  148. ? ModulesRepository.getModuleClass(module) 
  149. : null;
  150. if (moduleClass == null) {
  151. // Module not found, send 404 not found response
  152. response.sendError(HttpServletResponse.SC_NOT_FOUND);
  153. }
  154. else {
  155. boolean shouldBan = this.shouldBan(request.getRemoteAddr());
  156. if (!shouldBan) {
  157. context.put("moduleName", module);
  158. context.put("action", request.getAction());
  159. }
  160. else {
  161. moduleClass = ModulesRepository.getModuleClass("forums");
  162. context.put("moduleName", "forums");
  163. ((WebRequestContext)request).changeAction("banned");
  164. }
  165. if (shouldBan && SystemGlobals.getBoolValue(ConfigKeys.BANLIST_SEND_403FORBIDDEN)) {
  166. response.sendError(HttpServletResponse.SC_FORBIDDEN);
  167. }
  168. else {
  169. context.put("language", I18n.getUserLanguage());
  170. context.put("session", SessionFacade.getUserSession());
  171. context.put("request", req);
  172. context.put("response", response);
  173. out = this.processCommand(out, request, response, encoding, context, moduleClass);
  174. }
  175. }
  176. }
  177. catch (Exception e) {
  178. this.handleException(out, response, encoding, e, request);
  179. }
  180. finally {
  181. this.handleFinally(out, forumContext, response);
  182. }
  183. }
  184. private Writer processCommand(Writer out, RequestContext request, ResponseContext response, 
  185. String encoding, SimpleHash context, String moduleClass) throws Exception
  186. {
  187. // Here we go, baby
  188. Command c = this.retrieveCommand(moduleClass);
  189. Template template = c.process(request, response, context);
  190. if (JForumExecutionContext.getRedirectTo() == null) {
  191. String contentType = JForumExecutionContext.getContentType();
  192. if (contentType == null) {
  193. contentType = "text/html; charset=" + encoding;
  194. }
  195. response.setContentType(contentType);
  196. // Binary content are expected to be fully 
  197. // handled in the action, including outputstream
  198. // manipulation
  199. if (!JForumExecutionContext.isCustomContent()) {
  200. out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), encoding));
  201. template.process(JForumExecutionContext.getTemplateContext(), out);
  202. out.flush();
  203. }
  204. }
  205. return out;
  206. }
  207. private void checkDatabaseStatus()
  208. {
  209. if (!isDatabaseUp) {
  210. synchronized (this) {
  211. if (!isDatabaseUp) {
  212. isDatabaseUp = ForumStartup.startDatabase();
  213. }
  214. }
  215. }
  216. }
  217. private void handleFinally(Writer out, JForumContext forumContext, ResponseContext response) throws IOException
  218. {
  219. try {
  220. if (out != null) { out.close(); }
  221. }
  222. catch (Exception e) {
  223.     // catch close error 
  224. }
  225. String redirectTo = JForumExecutionContext.getRedirectTo();
  226. JForumExecutionContext.finish();
  227. if (redirectTo != null) {
  228. if (forumContext != null && forumContext.isEncodingDisabled()) {
  229. response.sendRedirect(redirectTo);
  230. else {
  231. response.sendRedirect(response.encodeRedirectURL(redirectTo));
  232. }
  233. }
  234. }
  235. private void handleException(Writer out, ResponseContext response, String encoding, 
  236. Exception e, RequestContext request) throws IOException
  237. {
  238. JForumExecutionContext.enableRollback();
  239. if (e.toString().indexOf("ClientAbortException") == -1) {
  240. response.setContentType("text/html; charset=" + encoding);
  241. if (out != null) {
  242. new ExceptionWriter().handleExceptionData(e, out, request);
  243. }
  244. else {
  245. new ExceptionWriter().handleExceptionData(e, new BufferedWriter(new OutputStreamWriter(response.getOutputStream())), request);
  246. }
  247. }
  248. }
  249. private boolean shouldBan(String ip)
  250. {
  251. Banlist b = new Banlist();
  252. b.setUserId(SessionFacade.getUserSession().getUserId());
  253. b.setIp(ip);
  254. return BanlistRepository.shouldBan(b);
  255. }
  256. private Command retrieveCommand(String moduleClass) throws Exception
  257. {
  258. return (Command)Class.forName(moduleClass).newInstance();
  259. }
  260. /** 
  261.  * @see javax.servlet.GenericServlet#destroy()
  262.  */
  263. public void destroy() {
  264. super.destroy();
  265. System.out.println("Destroying JForum...");
  266. try {
  267. DBConnection.getImplementation().realReleaseAllConnections();
  268. ConfigLoader.stopCacheEngine();
  269. }
  270. catch (Exception e) { }
  271. }
  272. }