KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > jforum > JForum


1 /*
2  * Copyright (c) Rafael Steil
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
45 import java.io.BufferedWriter JavaDoc;
46 import java.io.IOException JavaDoc;
47 import java.io.OutputStreamWriter JavaDoc;
48 import java.io.Writer JavaDoc;
49 import java.sql.Connection JavaDoc;
50
51 import javax.servlet.ServletConfig JavaDoc;
52 import javax.servlet.ServletException JavaDoc;
53 import javax.servlet.http.HttpServletRequest JavaDoc;
54 import javax.servlet.http.HttpServletResponse JavaDoc;
55
56 import net.jforum.dao.DatabaseWorkarounder;
57 import net.jforum.exceptions.ExceptionWriter;
58 import net.jforum.exceptions.ForumStartupException;
59 import net.jforum.repository.ModulesRepository;
60 import net.jforum.repository.RankingRepository;
61 import net.jforum.repository.SecurityRepository;
62 import net.jforum.repository.SmiliesRepository;
63 import net.jforum.util.I18n;
64 import net.jforum.util.MD5;
65 import net.jforum.util.preferences.ConfigKeys;
66 import net.jforum.util.preferences.SystemGlobals;
67
68 import org.apache.log4j.Logger;
69
70 import freemarker.template.SimpleHash;
71 import freemarker.template.Template;
72
73 /**
74  * Front Controller.
75  *
76  * @author Rafael Steil
77  * @version $Id: JForum.java,v 1.90 2006/01/29 17:41:45 rafaelsteil Exp $
78  */

79 public class JForum extends JForumBaseServlet
80 {
81     private static boolean isDatabaseUp;
82     private static Logger logger = Logger.getLogger(JForum.class);
83     
84     /**
85      * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
86      */

87     public void init(ServletConfig JavaDoc config) throws ServletException JavaDoc
88     {
89         super.init(config);
90         super.startFrontController();
91         
92         // Start database
93
isDatabaseUp = ForumStartup.startDatabase();
94         
95         try {
96             Connection JavaDoc conn = DBConnection.getImplementation().getConnection();
97             conn.setAutoCommit(!SystemGlobals.getBoolValue(ConfigKeys.DATABASE_USE_TRANSACTIONS));
98             
99             // Try to fix some MySQL problems
100
DatabaseWorkarounder dw = new DatabaseWorkarounder();
101             dw.handleWorkarounds(conn);
102             
103             // Continues loading the forum
104
JForumExecutionContext ex = JForumExecutionContext.get();
105             ex.setConnection(conn);
106             JForumExecutionContext.set(ex);
107             
108             // Init general forum stuff
109
ForumStartup.startForumRepository();
110             RankingRepository.loadRanks();
111             SmiliesRepository.loadSmilies();
112         }
113         catch (Exception JavaDoc e) {
114             throw new ForumStartupException("Error while starting jforum", e);
115         }
116         finally {
117             JForumExecutionContext.finish();
118         }
119     }
120     
121     /**
122      * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
123      */

124     public void service(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc response) throws IOException JavaDoc, ServletException JavaDoc
125     {
126         Writer JavaDoc out = null;
127         ActionServletRequest request = null;
128         String JavaDoc encoding = SystemGlobals.getValue(ConfigKeys.ENCODING);
129
130         try {
131             // Request
132
request = new ActionServletRequest(req);
133
134             // Initializes the execution context
135
JForumExecutionContext ex = JForumExecutionContext.get();
136             ex.setRequest(request);
137             ex.setResponse(response);
138
139             if (!isDatabaseUp) {
140                 ForumStartup.startDatabase();
141             }
142             
143             JForumExecutionContext.set(ex);
144             
145             // Setup stuff
146
SimpleHash context = JForumExecutionContext.getTemplateContext();
147             
148             ControllerUtils utils = new ControllerUtils();
149             utils.refreshSession();
150             
151             context.put("logged", SessionFacade.isLogged());
152             
153             // Process security data
154
SecurityRepository.load(SessionFacade.getUserSession().getUserId());
155             
156             request.setJForumContext(new JForumContext(request.getContextPath(),
157                     SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION),
158                     request,
159                     response,
160                     SessionFacade.getUserSession().isBot()));
161             
162             utils.prepareTemplateContext(context, request.getJForumContext());
163
164             String JavaDoc module = request.getModule();
165             
166             // Gets the module class name
167
String JavaDoc moduleClass = module != null
168                 ? ModulesRepository.getModuleClass(module)
169                 : null;
170             
171             context.put("moduleName", module);
172             context.put("action", request.getAction());
173             context.put("language", I18n.getUserLanguage());
174             context.put("securityHash", MD5.crypt(request.getSession().getId()));
175             context.put("session", SessionFacade.getUserSession());
176             context.put("request", req);
177             context.put("response", response);
178         
179             if (moduleClass != null) {
180                 // Here we go, baby
181
Command c = (Command)Class.forName(moduleClass).newInstance();
182                 Template template = c.process(request, response, context);
183
184                 if (JForumExecutionContext.getRedirectTo() == null) {
185                     String JavaDoc contentType = JForumExecutionContext.getContentType();
186                     
187                     if (contentType == null) {
188                         contentType = "text/html; charset=" + encoding;
189                     }
190                     
191                     response.setContentType(contentType);
192                     
193                     // Binary content are expected to be fully
194
// handled in the action, including outputstream
195
// manipulation
196
if (!JForumExecutionContext.isCustomContent()) {
197                         out = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(response.getOutputStream(), encoding));
198                         template.process(JForumExecutionContext.getTemplateContext(), out);
199                         out.flush();
200                     }
201                 }
202             }
203             else {
204                 // Module not found, send 404 not found response
205
response.sendError(HttpServletResponse.SC_NOT_FOUND);
206             }
207         }
208         catch (Exception JavaDoc e) {
209             JForumExecutionContext.enableRollback();
210             
211             if (e.toString().indexOf("ClientAbortException") == -1) {
212                 response.setContentType("text/html; charset=" + encoding);
213                 if (out != null) {
214                     new ExceptionWriter().handleExceptionData(e, out);
215                 }
216                 else {
217                     new ExceptionWriter().handleExceptionData(e, new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(response.getOutputStream())));
218                 }
219             }
220         }
221         finally {
222             try {
223                 if (out != null) { out.close(); }
224             }
225             catch (Exception JavaDoc e) {}
226             
227             String JavaDoc redirectTo = JForumExecutionContext.getRedirectTo();
228             JForumExecutionContext.finish();
229             
230             if (redirectTo != null) {
231                 if(request.getJForumContext().isEncodingDisabled()) {
232                     response.sendRedirect(redirectTo);
233                 }
234                 else {
235                     response.sendRedirect(response.encodeRedirectURL(redirectTo));
236                 }
237             }
238         }
239     }
240     
241     /**
242      * @see javax.servlet.GenericServlet#destroy()
243      */

244     public void destroy() {
245         super.destroy();
246         System.out.println("Destroying JForum...");
247         
248         try {
249             DBConnection.getImplementation().realReleaseAllConnections();
250             ConfigLoader.stopCacheEngine();
251         }
252         catch (Exception JavaDoc e) {}
253     }
254 }
255
Popular Tags