KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > jforum > JForumExecutionContext


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: 29/01/2006 - 12:19:11
40  * The JForum Project
41  * http://www.jforum.net
42  */

43 package net.jforum;
44
45 import java.io.IOException JavaDoc;
46 import java.sql.Connection JavaDoc;
47
48 import javax.servlet.http.HttpServletResponse JavaDoc;
49
50 import net.jforum.util.preferences.ConfigKeys;
51 import net.jforum.util.preferences.SystemGlobals;
52
53 import org.apache.log4j.Logger;
54
55 import freemarker.template.Configuration;
56 import freemarker.template.ObjectWrapper;
57 import freemarker.template.SimpleHash;
58
59 /**
60  * Data execution context.
61  *
62  * @author Rafael Steil
63  * @version $Id: JForumExecutionContext.java,v 1.2 2006/01/29 17:41:45 rafaelsteil Exp $
64  */

65 public class JForumExecutionContext
66 {
67     private static ThreadLocal JavaDoc userData = new ThreadLocal JavaDoc();
68     private static Logger logger = Logger.getLogger(JForumExecutionContext.class);
69     private static Configuration templateConfig;
70     
71     private Connection JavaDoc conn;
72     private ActionServletRequest request;
73     private HttpServletResponse JavaDoc response;
74     private SimpleHash context = new SimpleHash(ObjectWrapper.BEANS_WRAPPER);
75     private String JavaDoc redirectTo;
76     private String JavaDoc contentType;
77     private boolean isCustomContent;
78     private boolean enableRollback;
79     
80     /**
81      * Gets the execution context.
82      * @return
83      */

84     public static JForumExecutionContext get()
85     {
86         JForumExecutionContext ex = (JForumExecutionContext)userData.get();
87
88         if (ex == null) {
89             ex = new JForumExecutionContext();
90             userData.set(ex);
91         }
92         
93         return ex;
94     }
95     
96     /**
97      * Checks if there is an execution context already set
98      * @return <code>true</code> if there is an execution context
99      * @see #get()
100      */

101     public static boolean exists()
102     {
103         return (userData.get() != null);
104     }
105     
106     /**
107      * Sets the default template configuration
108      * @param config The template configuration to set
109      */

110     public static void setTemplateConfig(Configuration config)
111     {
112         templateConfig = config;
113     }
114     
115     /**
116      * Gets a reference to the default template configuration settings.
117      * @return The template configuration instance
118      */

119     public static Configuration templateConfig()
120     {
121         return templateConfig;
122     }
123     
124     /**
125      * Sets the execution context
126      * @param ex
127      */

128     public static void set(JForumExecutionContext ex)
129     {
130         userData.set(ex);
131     }
132     
133     /**
134      * Sets a connection
135      * @param conn The connection to use
136      */

137     public void setConnection(Connection JavaDoc conn)
138     {
139         this.conn = conn;
140     }
141     
142     /**
143      * Gets the current thread's connection
144      * @return
145      */

146     public static Connection JavaDoc getConnection()
147     {
148         return getConnection(true);
149     }
150     
151     public static Connection JavaDoc getConnection(boolean validate)
152     {
153         JForumExecutionContext ex = get();
154         Connection JavaDoc c = ex.conn;
155         
156         if (validate && c == null) {
157             c = DBConnection.getImplementation().getConnection();
158             
159             logger.debug("Getting a connection for the request: " + c);
160             
161             try {
162                 c.setAutoCommit(!SystemGlobals.getBoolValue(ConfigKeys.DATABASE_USE_TRANSACTIONS));
163             }
164             catch (Exception JavaDoc e) {}
165             
166             ex.setConnection(c);
167             set(ex);
168         }
169         
170         return c;
171     }
172     
173     /**
174      * Sets a request to the execution context.
175      * @param request The request to set
176      */

177     public void setRequest(ActionServletRequest request)
178     {
179         this.request = request;
180     }
181
182     /**
183      * Gets the current thread's request
184      * @return
185      */

186     public static ActionServletRequest getRequest() {
187         return ((JForumExecutionContext)userData.get()).request;
188     }
189     
190     /**
191      * Sets the reponse to the execution context.
192      * @param response The response to set
193      */

194     public void setResponse(HttpServletResponse JavaDoc response)
195     {
196         this.response = response;
197     }
198
199     /**
200      * Gets the current thread's response
201      * @return
202      */

203     public static HttpServletResponse JavaDoc getResponse() {
204         return ((JForumExecutionContext)userData.get()).response;
205     }
206
207     /**
208      * Gets the current thread's template context
209      * @return
210      */

211     public static SimpleHash getTemplateContext() {
212         return ((JForumExecutionContext)userData.get()).context;
213     }
214
215     /**
216      * Gets the current thread's <code>DataHolder</code> instance
217      * @return
218      */

219     public static void setRedirect(String JavaDoc redirect) {
220         ((JForumExecutionContext)userData.get()).redirectTo = redirect;
221     }
222
223     /**
224      * Sets the content type for the current http response.
225      * @param contentType
226      */

227     public static void setContentType(String JavaDoc contentType) {
228         ((JForumExecutionContext)userData.get()).contentType = contentType;
229     }
230     
231     /**
232      * Gets the content type for the current request.
233      * @return
234      */

235     public static String JavaDoc getContentType()
236     {
237         return ((JForumExecutionContext)userData.get()).contentType;
238     }
239
240     /**
241      * Gets the URL to redirect to, if any.
242      * @return The URL to redirect, of <code>null</code> if none.
243      */

244     public static String JavaDoc getRedirectTo()
245     {
246         JForumExecutionContext ex = (JForumExecutionContext)userData.get();
247         return (ex != null ? ex.redirectTo : null);
248     }
249
250     /**
251      * Marks the request to use a binary content-type.
252      * @param enable
253      */

254     public static void enableCustomContent(boolean enable) {
255         ((JForumExecutionContext)userData.get()).isCustomContent = enable;
256     }
257     
258     /**
259      * Checks if the current request is binary
260      * @return <code>true</code> if the content tyee for the current request is
261      * any binary data.
262      */

263     public static boolean isCustomContent()
264     {
265         return ((JForumExecutionContext)userData.get()).isCustomContent;
266     }
267
268     /**
269      * Forces the request to not commit the connection.
270      */

271     public static void enableRollback() {
272         ((JForumExecutionContext)userData.get()).enableRollback = true;
273     }
274
275     /**
276      * Check if commit is disabled or not for the current request.
277      * @return <code>true</code> if a commit should NOT be made
278      */

279     public static boolean shouldRollback() {
280         return ((JForumExecutionContext)userData.get()).enableRollback;
281     }
282
283     /**
284      * Send UNAUTHORIZED to the browser and ask user to login via basic authentication
285      *
286      * @throws IOException
287      */

288     public static void requestBasicAuthentication() throws IOException JavaDoc {
289         getResponse().addHeader("WWW-Authenticate", "Basic realm=\"JForum\"");
290         getResponse().sendError(HttpServletResponse.SC_UNAUTHORIZED);
291         enableCustomContent(true);
292     }
293     
294     /**
295      * Finishes the execution context
296      */

297     public static void finish()
298     {
299         Connection JavaDoc conn = JForumExecutionContext.getConnection(false);
300         
301         if (conn != null) {
302             if (SystemGlobals.getBoolValue(ConfigKeys.DATABASE_USE_TRANSACTIONS)) {
303                 if (JForumExecutionContext.shouldRollback()) {
304                     try {
305                         conn.rollback();
306                     }
307                     catch (Exception JavaDoc e) {
308                         logger.error("Error while rolling back a transaction", e);
309                     }
310                 }
311                 else {
312                     try {
313                         conn.commit();
314                     }
315                     catch (Exception JavaDoc e) {
316                         logger.error("Error while commiting a transaction", e);
317                     }
318                 }
319             }
320             
321             try {
322                 DBConnection.getImplementation().releaseConnection(conn);
323             }
324             catch (Exception JavaDoc e) {
325                 logger.error("Error while releasing the connection : " + e, e);
326             }
327         }
328         
329         userData.set(null);
330     }
331 }
332
Popular Tags