KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > module > core > MMBaseContext


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10 package org.mmbase.module.core;
11
12 import java.util.*;
13 import java.io.*;
14 import javax.servlet.*;
15 import java.text.DateFormat JavaDoc;
16
17 import org.mmbase.core.util.DaemonTask;
18 import org.mmbase.core.util.DaemonThread;
19 import org.mmbase.util.ResourceLoader;
20 import org.mmbase.util.logging.Logger;
21 import org.mmbase.util.logging.Logging;
22
23 /**
24  * Using MMBaseContext class you can retrieve the servletContext from anywhere
25  * using the get method.
26  *
27  * @author Daniel Ockeloen
28  * @author David van Zeventer
29  * @author Jaco de Groot
30  * @version $Id: MMBaseContext.java,v 1.52 2006/04/01 09:14:19 michiel Exp $
31  */

32 public class MMBaseContext {
33     private static final Logger log = Logging.getLoggerInstance(MMBaseContext.class);
34     private static boolean initialized = false;
35     private static boolean htmlRootInitialized = false;
36     private static ServletContext sx;
37     private static String JavaDoc userDir;
38     private static String JavaDoc javaVersion;
39
40     private static String JavaDoc htmlRoot;
41     private static String JavaDoc htmlRootUrlPath = "/";
42     private static boolean htmlRootUrlPathInitialized = false;
43     private static String JavaDoc outputFile;
44     private static ThreadGroup JavaDoc threadGroup;
45
46     /**
47      * Initialize MMBase using a <code>ServletContext</code>. This method will
48      * check the servlet configuration for context parameters mmbase.outputfile
49      * and mmbase.config. If not found it will look for system properties.
50      *
51      * @throws ServletException if mmbase.config is not set or is not a
52      * directory or doesn't contain the expected
53      * config files.
54      *
55      */

56     public synchronized static void init(ServletContext servletContext) {
57         if (!initialized) {
58         // get the java version we are running
59
javaVersion = System.getProperty("java.version");
60             // store the current context
61
sx = servletContext;
62             // Get the user directory using the user.dir property.
63
// default set to the startdir of the appserver
64
userDir = sx.getInitParameter("user.dir");
65             if (userDir == null) {
66                 userDir = System.getProperty("user.dir");
67             }
68             // take into account userdir can start at webrootdir
69
if (userDir != null && userDir.indexOf("$WEBROOT") == 0) {
70                 userDir = servletContext.getRealPath(userDir.substring(8));
71             }
72             // Init outputfile.
73
String JavaDoc outputFile = sx.getInitParameter("mmbase.outputfile");
74             if (outputFile == null) {
75                 outputFile = System.getProperty("mmbase.outputfile");
76             }
77             // take into account configpath can start at webrootdir
78
if (outputFile != null && outputFile.indexOf("$WEBROOT") == 0) {
79                 outputFile = servletContext.getRealPath(outputFile.substring(8));
80             }
81             initOutputfile(outputFile);
82
83             ResourceLoader.init(sx);
84
85             // Init logging.
86
initLogging();
87             initialized = true;
88         }
89     }
90
91     /**
92      * Initialize MMBase using a config path. Useful when testing
93      * MMBase classes with a main. You can also configure to init
94      * logging or not.
95      *
96      * @throws Exception if mmbase.config is not set or is not a
97      * directory or doesn't contain the expected
98      * config files.
99      *
100      */

101     public synchronized static void init(String JavaDoc configPath, boolean initLogging) throws Exception JavaDoc {
102         if (!initialized) {
103             // Get the current directory using the user.dir property.
104
userDir = System.getProperty("user.dir");
105
106             // Init outputfile. // use of mmbase.outputfile is deprecated!
107
initOutputfile(System.getProperty("mmbase.outputfile"));
108
109             // Init logging.
110
if (initLogging) {
111                 initLogging();
112             }
113             initialized = true;
114        }
115     }
116
117     /**
118      * Initialize MMBase using system properties only. This may be useful in
119      * cases where MMBase is used without a servlet. For example when running
120      * JUnit tests.
121      *
122      * @throws Exception if mmbase.config is not set or is not a
123      * directory or doesn't contain the expected
124      * config files.
125      */

126     public synchronized static void init() throws Exception JavaDoc {
127         init(System.getProperty("mmbase.config"), true);
128     }
129
130     /**
131      * Returns the MMBase thread group.
132      * @since MMBase-1.8
133      */

134     public synchronized static ThreadGroup JavaDoc getThreadGroup() {
135         if (threadGroup == null) {
136             String JavaDoc groupName = org.mmbase.Version.get();
137             log.service("Creating threadGroup: " + groupName);
138             threadGroup = new ThreadGroup JavaDoc(groupName);
139         }
140         return threadGroup;
141     }
142
143     /**
144      * Starts a daemon thread using the MMBase thread group.
145      * @param task the task to run as a thread
146      * @param name the thread's name
147      * @since MMBase-1.8
148      */

149     public static Thread JavaDoc startThread(Runnable JavaDoc task, String JavaDoc name) {
150         DaemonThread kicker = new DaemonThread(task, name);
151         kicker.start();
152         return kicker;
153     }
154     /**
155      * Starts a daemon thread using the MMBase thread group.
156      * @param task the task to run as a thread
157      * @param name the thread's name
158      * @since MMBase-1.8
159      */

160     public static Thread JavaDoc startThread(DaemonTask task, String JavaDoc name) {
161         DaemonThread kicker = new DaemonThread(name);
162         kicker.setTask(task);
163         kicker.start();
164         return kicker;
165     }
166
167     private static void initOutputfile(String JavaDoc o) {
168         outputFile = o;
169         if (outputFile != null) {
170             if (!new File(outputFile).isAbsolute()) {
171                 outputFile = userDir + File.separator + outputFile;
172             }
173             try {
174                  PrintStream stream = new PrintStream(new FileOutputStream(outputFile, true));
175                  System.setOut(stream);
176                  System.setErr(stream);
177             } catch (IOException e) {
178                  outputFile = null;
179                  log.error("Failed to set mmbase.outputfile to '" + outputFile + "'.");
180                  log.error(Logging.stackTrace(e));
181             }
182         }
183     }
184
185     private static void initLogging() {
186         // Starting the logger
187
Logging.configure(ResourceLoader.getConfigurationRoot().getChildResourceLoader("log"), "log.xml");
188         log.info("===========================");
189         log.info("MMBase logging initialized.");
190         log.info("===========================");
191         log.info("java.version : " + javaVersion);
192         log.info("user.dir : " + userDir);
193         String JavaDoc configPath = ResourceLoader.getConfigurationRoot().toString();
194         log.info("configuration : " + configPath);
195         log.info("webroot : " + ResourceLoader.getWebRoot());
196         String JavaDoc version = org.mmbase.Version.get();
197         log.info("version : " + version);
198         Runtime JavaDoc rt = Runtime.getRuntime();
199         log.info("total memory : " + rt.totalMemory() / (1024 * 1024) + " Mbyte");
200         log.info("free memory : " + rt.freeMemory() / (1024 * 1024) + " Mbyte");
201         log.info("system locale : " + Locale.getDefault());
202         log.info("start time : " + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date(1000 * (long) MMBase.startTime)));
203     }
204
205     /**
206      * Initialize mmbase.htmlroot parameter. This method is only needed for
207      * SCAN related servlets and should be called after the init(ServletContext)
208      * method. If the mmbase.htmlroot parameter is not found in the servlet
209      * context or system properties this method will try to set it to the
210      * root directory of the webapp.
211      *
212      * @throws ServletException if mmbase.htmlroot is not set or is not a
213      * directory
214      *
215      */

216     public synchronized static void initHtmlRoot() throws ServletException {
217         if (!initialized || sx == null) {
218             String JavaDoc message = "The init(ServletContext) method should be called first.";
219             log.error(message);
220             throw new RuntimeException JavaDoc(message);
221         }
222         if (!htmlRootInitialized) {
223             // Init htmlroot.
224
htmlRoot = sx.getInitParameter("mmbase.htmlroot");
225             if (htmlRoot == null) {
226                 htmlRoot = System.getProperty("mmbase.htmlroot");
227             }
228             if (htmlRoot == null) {
229                 htmlRoot = sx.getRealPath("");
230             }
231             if (htmlRoot == null){
232                 log.error("Parameter mmbase.htmlroot not set.");
233             } else {
234                 if (userDir != null && !new File(htmlRoot).isAbsolute()) {
235                     htmlRoot = userDir + File.separator + htmlRoot;
236                 }
237                 if (!new File(htmlRoot).isDirectory()) {
238                     userDir = null;
239                     htmlRoot = null;
240                     throw new ServletException("Parameter mmbase.htmlroot is not pointing to a directory.");
241                 } else {
242                     if (htmlRoot.endsWith(File.separator)) {
243                         htmlRoot = htmlRoot.substring(0, htmlRoot.length() - 1);
244                     }
245                 }
246             }
247             htmlRootInitialized = true;
248             log.info("mmbase.htmlroot : " + htmlRoot);
249             log.info("context : " + getHtmlRootUrlPath());
250         }
251     }
252
253     /**
254      * Returns the <code>ServletContext</code> used to initialize MMBase.
255      * Before calling this method the init method should be called.
256      *
257      * @return the <code>ServletContext</code> used to initialize MMBase or
258      * <code>null</code> if MMBase was initialized without
259      * <code>ServletContext</code>
260      */

261     public synchronized static ServletContext getServletContext() {
262         if (!initialized) {
263             throw new RuntimeException JavaDoc("The init method should be called first.");
264         }
265         return sx;
266     }
267
268     /**
269      * Returns a string representing the mmbase.config parameter without a
270      * final <code>File.separator</code>. Before calling this method the
271      * init method should be called to make sure this parameter is set.
272      *
273      * @return the mmbase.config parameter or WEB-INF/config
274      * @deprecated use {@link org.mmbase.util.ResourceLoader#getConfigurationRoot} with relative path
275      */

276     public synchronized static String JavaDoc getConfigPath() {
277         List files = ResourceLoader.getConfigurationRoot().getFiles("");
278         if (files.size() == 0) {
279             return null;
280         } else {
281             return ((File) files.get(0)).getAbsolutePath();
282         }
283     }
284
285     /**
286      * Returns a string representing the mmbase.htmlroot parameter without a
287      * final <code>File.separator</code>. Before calling this method the
288      * initHtmlRoot method should be called to make sure this parameter is set.
289      *
290      * @return the mmbase.htmlroot parameter or <code>null</code> if not
291      * initialized
292      */

293     public synchronized static String JavaDoc getHtmlRoot() {
294         if (!htmlRootInitialized) {
295             String JavaDoc message = "The initHtmlRoot method should be called first.";
296             log.error(message);
297             throw new RuntimeException JavaDoc();
298         }
299        return htmlRoot;
300     }
301
302     /**
303      * Returns a string representing the mmbase.outputfile parameter. If set,
304      * this is the file to wich all <code>System.out</code> and
305      * <code>System.err</code> output is redirected. Before calling this method
306      * the init method should be called.
307      *
308      * @return the mmbase.outputFile parameter or <code>null</code> if not set
309      * @deprecated use logging system
310      */

311     public synchronized static String JavaDoc getOutputFile() {
312         if (!initialized) {
313             String JavaDoc message = "The init method should be called first.";
314             log.error(message);
315             throw new RuntimeException JavaDoc(message);
316         }
317         return outputFile;
318     }
319
320     /**
321      * Returns a string representing the HtmlRootUrlPath, this is the path under
322      * the webserver, what is the root for this instance.
323      * this will return '/' or something like '/mmbase/' or so...
324      * @return the HtmlRootUrlPath
325      * @deprecated should not be needed, and this information should be requested from the ServletRequest
326      */

327     public synchronized static String JavaDoc getHtmlRootUrlPath() {
328         if (! htmlRootUrlPathInitialized) {
329             log.info("Finding root url");
330             if (! initialized) {
331                 String JavaDoc message = "The init method should be called first.";
332                 log.error(message);
333                 throw new RuntimeException JavaDoc(message);
334             }
335             if (sx == null) { // no serlvetContext -> no htmlRootUrlPath
336
htmlRootUrlPathInitialized = true;
337                 return htmlRootUrlPath;
338             }
339             String JavaDoc initPath = sx.getInitParameter("mmbase.htmlrooturlpath");
340             if (initPath != null) {
341                 log.debug("Found mmbase.htmlrooturlpath explicitely configured");
342                 htmlRootUrlPath = initPath;
343             } else {
344                 // init the htmlRootUrlPath
345
try {
346                     log.debug("Autodetecting htmlrooturlpath ");
347                     // fetch resource path for the root servletcontext root...
348
// check wether this is root
349
if (sx.equals(sx.getContext("/"))) {
350                         htmlRootUrlPath = "/";
351                     } else {
352                         String JavaDoc url = sx.getResource("/").toString();
353                         // MM: simply hope that it is the last part of that URL.
354
// I do not think it is garantueed. Used mmbase.htmlrooturlpath in web.xml if it doesn't work.
355
int length = url.length();
356                         int lastSlash = url.substring(0, length - 1).lastIndexOf('/');
357                         if (lastSlash > 0) {
358                             htmlRootUrlPath = url.substring(lastSlash);
359                         } else {
360                             log.warn("Could not determine htmlRootUrlPath. Using default " + htmlRootUrlPath + "(contextUrl :" + url + ")");
361                         }
362                     }
363                 } catch (Exception JavaDoc e) {
364                     log.error(e);
365                 }
366                 try {
367                     if (!sx.equals(sx.getContext(htmlRootUrlPath))) {
368                         log.warn("Probably did not succeed in determining htmlRootUrlPath ('" + htmlRootUrlPath + "'). Consider using the mmbase.htmlrooturlpath context-param in web.xml");
369                     }
370                 } catch (Exception JavaDoc e2) {
371                     log.error(e2);
372                 }
373             }
374             htmlRootUrlPathInitialized = true;
375         }
376         return htmlRootUrlPath;
377     }
378
379     /**
380      * Returns whether this class has been initialized.
381      * This can be used to determine whether MMBase specific configuration data is accessible.
382      */

383     public static boolean isInitialized() {
384         return initialized;
385     }
386 }
387
Popular Tags