KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openlaszlo > servlets > responders > ResponderLOGCONFIG


1 /******************************************************************************
2  * ResponderLOGCONFIG.java
3  * ****************************************************************************/

4
5 /* J_LZ_COPYRIGHT_BEGIN *******************************************************
6 * Copyright 2001-2004 Laszlo Systems, Inc. All Rights Reserved. *
7 * Use is subject to license terms. *
8 * J_LZ_COPYRIGHT_END *********************************************************/

9
10 package org.openlaszlo.servlets.responders;
11
12 import java.io.*;
13 import java.util.Properties JavaDoc;
14 import javax.servlet.ServletConfig JavaDoc;
15 import javax.servlet.ServletException JavaDoc;
16 import javax.servlet.ServletOutputStream JavaDoc;
17 import javax.servlet.http.HttpServletRequest JavaDoc;
18 import javax.servlet.http.HttpServletResponse JavaDoc;
19 import org.openlaszlo.utils.FileUtils;
20 import org.openlaszlo.utils.StringUtils;
21 import org.openlaszlo.server.ConfigDir;
22 import org.openlaszlo.server.LPS;
23
24 import org.xml.sax.*;
25 import org.apache.log4j.*;
26 import org.apache.log4j.xml.*;
27 import org.w3c.dom.*;
28 import javax.xml.parsers.*;
29 import javax.servlet.http.HttpServlet JavaDoc;
30 import org.apache.xml.utils.*;
31
32 public final class ResponderLOGCONFIG extends ResponderAdmin
33 {
34     private static HttpServlet JavaDoc mServlet = null;
35     private static boolean mIsInitialized = false;
36     private static DocumentBuilder mBuilder = null;
37     private static Document mDocument = null;
38     private static boolean mSaveConfig = false;
39     private static File mLogFile = null;
40     /** Servlet who we're logging on behalf of */
41     private static HttpServlet JavaDoc servlet = null;
42
43
44     private static class SaveConfigException extends IOException {
45         public SaveConfigException() {
46             super();
47         }
48         public SaveConfigException(String JavaDoc s) {
49             super(s);
50         }
51     }
52
53     public static File getLogFile()
54     {
55         return mLogFile;
56     }
57
58     synchronized protected
59         void respondAdmin(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res)
60         throws IOException
61     {
62         res.setContentType("text/xml");
63
64         String JavaDoc reread = req.getParameter("reread");
65         String JavaDoc xml = req.getParameter("xml");
66         String JavaDoc save = req.getParameter("save");
67
68         mSaveConfig = (save != null && save.equals("1"));
69
70         try {
71             if (xml != null) {
72                 configure(xml);
73             } else if (reread != null && reread.equals("1")) {
74                 configure(mServlet);
75             }
76         } catch (ParserConfigurationException e) {
77             respondWithException(res, e);
78             return;
79         } catch (SAXException e) {
80             respondWithException(res, e);
81             return;
82         } catch (SaveConfigException e) {
83             respondWithException(res, e);
84             return;
85         }
86
87         if (mDocument == null) {
88             respondWithErrorXML(res, "LPS log not configured");
89             return;
90         }
91
92         printNode(new PrintStream(res.getOutputStream()), mDocument, "");
93     }
94
95
96     /**
97      * Configure log4j with xml configuration file. Also sets the servlet we're logging for.
98      * @param servlet servlet to log configured info. Pass null if you don't want loginfo.
99      */

100     synchronized public static void configure(HttpServlet JavaDoc servlet)
101         throws IOException, SecurityException JavaDoc,
102                ParserConfigurationException, SAXException {
103
104         if (mBuilder == null)
105             mBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
106         String JavaDoc logfile = null;
107         String JavaDoc configFile = getConfigurationFile();
108         if (configFile != null) {
109             String JavaDoc uri = "file:///" + configFile;
110             logfile = configure(mBuilder.parse(uri), null);
111         } else {
112             configFile = LPS.getConfigDirectory() + File.separator + "lps.xml";
113             logfile = configureWithLPSConfig(configFile);
114         }
115
116         if (servlet != null) {
117             mServlet = servlet;
118         }
119
120         if (mServlet != null) {
121             servlet.log("Detailed LPS log is at " + logfile);
122             servlet.log("LPS log configured with " + configFile);
123         }
124     }
125
126
127     /**
128      * Configure using lps.xml
129      */

130     synchronized public static
131         String JavaDoc configureWithLPSConfig(String JavaDoc lpsConfigFile)
132         throws SAXException, IOException {
133
134         String JavaDoc logfile = null;
135         String JavaDoc uri = "file:///" + lpsConfigFile;
136         Document doc = mBuilder.parse(uri);
137         NodeList nl = doc.getElementsByTagName("log4j:configuration");
138
139         if (0 < nl.getLength()) {
140             Document tmpdoc = mBuilder.newDocument();
141             Node node = tmpdoc.importNode( nl.item(0) , true );
142             tmpdoc.appendChild(node);
143             logfile = configure(tmpdoc, null);
144         }
145
146         return logfile;
147     }
148
149
150     /**
151      * Configure log4j with xml.
152      */

153     synchronized public static void configure(String JavaDoc xml)
154         throws IOException, SecurityException JavaDoc,
155                ParserConfigurationException, SAXException
156     {
157         if (mBuilder == null)
158             mBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
159         configure(mBuilder.parse(new InputSource(new StringReader(xml))), null);
160     }
161
162
163     /**
164      * Configure log4j with DOM. Create lps.log, if File param has not be
165      * configured.
166      */

167     synchronized private static String JavaDoc configure(Document doc,
168                                                  String JavaDoc replaceFileName)
169         throws IOException, SecurityException JavaDoc
170     {
171         String JavaDoc logFileName = null;
172
173         Element root = doc.getDocumentElement();
174         NodeList appenderList = root.getElementsByTagName("appender");
175         for (int i=0; i < appenderList.getLength(); i++) {
176
177             Element appender = (Element) appenderList.item(i);
178             String JavaDoc appenderName = appender.getAttribute("name");
179             if (appenderName.equals("lps")) {
180                 NodeList paramList = appender.getElementsByTagName("param");
181                 for (int j=0; j < paramList.getLength(); j++) {
182
183                     // Look for File param in lps appender.
184
Element param = (Element) paramList.item(j);
185                     String JavaDoc paramName = param.getAttribute("name");
186                     if (paramName.equals("File")) {
187                         if (replaceFileName != null) {
188                             replaceFileName =
189                                 StringUtils.replace(replaceFileName, '\\', "/");
190                             param.setAttribute("value", replaceFileName);
191                         }
192                         logFileName = param.getAttribute("value");
193                         break;
194                     }
195                 }
196
197                 // Create lps.log file iff File param does not exist. Also,
198
// replace File option if replaceFileName is passed in.
199
if (logFileName == null) {
200
201                     logFileName = LPS.getWorkDirectory() +
202                         File.separator + "logs" +
203                         File.separator + "lps.log";
204
205                     // Seems as if we have to escape back-slashes in log4j.xml
206
// strings.
207
logFileName = StringUtils.replace(logFileName, '\\', "/");
208                     try {
209                         Element p = doc.createElement("param");
210                         p.setAttribute("name", "File");
211                         p.setAttribute("value", logFileName);
212
213                         // param must come after errorHandler, if it exists. See
214
// log4j.dtd for more info.
215
NodeList nodes = appender.getChildNodes();
216                         for (int k=0; k < nodes.getLength(); k++) {
217                             Node n = nodes.item(k);
218                             if (n.getNodeType() == Node.ELEMENT_NODE) {
219                                 Element e = (Element) n;
220                                 if (e.getTagName().equals("errorHandler"))
221                                     n = e.getNextSibling();
222                                 appender.insertBefore(p, n);
223                                 break;
224                             }
225                         }
226                     } catch (DOMException e) {
227                         Logger.getLogger(ResponderLOGCONFIG.class).debug("DOMException: " , e);
228                         logFileName = null;
229                     }
230                 }
231
232                 if (! logFileName.equals("")) {
233                     // Sanity check for logfile as configured
234
mLogFile = new File(logFileName);
235                     File logFileDir = mLogFile.getParentFile();
236                     if (logFileDir != null)
237                         logFileDir.mkdirs();
238                     mLogFile.createNewFile();
239                 }
240                 break;
241             }
242         }
243             
244         DOMConfigurator.configure(root);
245         mDocument = doc;
246
247         if (servlet != null) {
248             servlet.log("LPS log file is now " + logFileName);
249         }
250
251         try {
252             if (mSaveConfig) {
253                 String JavaDoc configDir = LPS.getConfigDirectory();
254                 FileOutputStream out = new FileOutputStream
255                     (new File(configDir + File.separator + "log4j.xml"));
256                 printNode(new PrintStream(out), mDocument, "");
257                 out.close();
258             }
259         } catch (IOException e) {
260             throw new SaveConfigException("server configured but could not write out configuration.");
261         }
262
263         return logFileName;
264     }
265
266
267     /**
268      * Prety much ripped from:
269      *
270      * http://www-106.ibm.com/developerworks/java/library/x-jaxp/TestDOMParsing.java
271      */

272     synchronized private static void printNode(PrintStream out, Node node, String JavaDoc indent)
273         throws IOException
274     {
275         switch (node.getNodeType()) {
276         case Node.DOCUMENT_NODE:
277             // recurse on each child
278
NodeList nodes = node.getChildNodes();
279             if (nodes != null) {
280                 for (int i=0; i<nodes.getLength(); i++) {
281                     printNode(out, nodes.item(i), "");
282                 }
283             }
284             break;
285                 
286         case Node.ELEMENT_NODE:
287             String JavaDoc name = node.getNodeName();
288             out.print(indent + "<" + name);
289             NamedNodeMap attributes = node.getAttributes();
290             for (int i=0; i<attributes.getLength(); i++) {
291                 Node current = attributes.item(i);
292                 out.print(" " + current.getNodeName() +
293                           "=\"" + current.getNodeValue() + "\"");
294             }
295             out.print(">\n\n");
296                 
297             // recurse on each child
298
NodeList children = node.getChildNodes();
299             if (children != null) {
300                 for (int i=0; i<children.getLength(); i++) {
301                     printNode(out, children.item(i), indent + " ");
302                 }
303             }
304                 
305             out.print(indent + "</" + name + ">\n\n");
306             break;
307
308         case Node.COMMENT_NODE:
309         case Node.TEXT_NODE:
310             break;
311         }
312     }
313
314     /**
315      * Clear the log file.
316      * @param status clear log status. Log can be cleared, but state can be bad
317      * if log file can't be reset.
318      */

319     synchronized public static boolean clearLog(String JavaDoc[] status)
320     {
321         String JavaDoc path = mLogFile.getAbsolutePath();
322         boolean cleared = false;
323
324
325         try {
326             // Let go of log handle
327
configure(mDocument, "");
328         } catch (Exception JavaDoc e) {
329             if (status != null)
330                 status[0] = "can't reconfigure log";
331             Logger.getLogger(ResponderLOGCONFIG.class).info("can't reconfigure log");
332             return cleared;
333         }
334
335         try {
336             cleared = new File(path).delete();
337         } catch (SecurityException JavaDoc e) {
338             Logger.getLogger(ResponderLOGCONFIG.class).info("can't clear log: ", e);
339         }
340
341         try {
342             // Reset log handle
343
configure(mDocument, path);
344         } catch (Exception JavaDoc e) {
345             if (status != null)
346                 status[0] = "can't reset log";
347             Logger.getLogger(ResponderLOGCONFIG.class).info("can't reset log");
348         }
349
350         return cleared;
351     }
352
353
354     /**
355      * Find log4j.xml configuration file.
356      */

357     private static String JavaDoc getConfigurationFile()
358         throws FileNotFoundException
359     {
360         String JavaDoc configDir = LPS.getConfigDirectory();
361         String JavaDoc filename = configDir + File.separator + "log4j.xml";
362         if (! new File(filename).isFile()) {
363             filename = null;
364         }
365         return filename;
366     }
367
368     public int getMimeType()
369     {
370         return MIME_TYPE_XML;
371     }
372 }
373
Popular Tags