KickJava   Java API By Example, From Geeks To Geeks.

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


1 /******************************************************************************
2  * ResponderAPP_CONSOLE.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.net.URLEncoder JavaDoc;
14 import java.util.*;
15 import javax.servlet.ServletConfig JavaDoc;
16 import javax.servlet.ServletException JavaDoc;
17 import javax.servlet.ServletOutputStream JavaDoc;
18 import javax.servlet.http.HttpSession JavaDoc;
19 import javax.servlet.http.HttpServletRequest JavaDoc;
20 import javax.servlet.http.HttpServletResponse JavaDoc;
21 import org.openlaszlo.compiler.Canvas;
22 import org.openlaszlo.compiler.CompilationError;
23 import org.openlaszlo.server.LPS;
24 import org.openlaszlo.utils.*;
25 import org.openlaszlo.xml.internal.XMLUtils;
26 import org.apache.log4j.Logger;
27
28 public final class ResponderAPP_CONSOLE extends ResponderCompile
29 {
30     private static Logger mLogger = Logger.getLogger(ResponderAPP_CONSOLE.class);
31     private static String JavaDoc sStyleSheetPathname =
32         org.openlaszlo.server.LPS.getTemplateDirectory() +
33         File.separator + "app-console.xslt";
34     
35     /*
36      * @param fileName Full pathname to file from request.
37      */

38     protected void respondImpl(String JavaDoc fileName, HttpServletRequest JavaDoc req,
39                                HttpServletResponse JavaDoc res)
40         throws IOException
41     {
42         mLogger.info("Responding with HTML wrapper for " + fileName);
43         res.setContentType("text/html");
44         ServletOutputStream JavaDoc out = res.getOutputStream();
45         try {
46             // Get the canvas first, so that if this fails and we
47
// write the compilation error, nothing has been written
48
// to out yet.
49
// Replace .lzo with .lzx
50
boolean isKranked = false;
51             String JavaDoc orig = fileName;
52             if (fileName.endsWith(".lzo")) {
53                 isKranked = true;
54                 fileName = fileName.substring(0, fileName.length() - 1) + "x";
55             }
56             /* This method doesn't call writeHeader and writeFooter, since
57              * the stylesheet handles the whole HTML generation. */

58             Canvas canvas = getCanvas(fileName, req);
59             writeCanvas(out, req, canvas, orig, isKranked);
60         } finally {
61             FileUtils.close(out);
62         }
63     }
64     
65     static public String JavaDoc getRequestXML(HttpServletRequest JavaDoc req, String JavaDoc fileName)
66         throws IOException
67     {
68         String JavaDoc lps = req.getContextPath();
69         String JavaDoc agent = req.getHeader("user-agent");
70         // MS-specific header
71
String JavaDoc os = req.getHeader("ua-os");
72         String JavaDoc query_args = getQueryArgs(req);
73         String JavaDoc url = req.getRequestURI();
74         int i = url.lastIndexOf("/");
75         url = url.substring(i + 1, url.length() );
76         String JavaDoc unopturl = url.substring(0, url.length() - 4) + ".lzx";
77         String JavaDoc opturl = url.substring(0, url.length() - 4) + ".lzo";
78         boolean isPocketPC = (os != null && os.indexOf("POCKET PC") > -1);
79         boolean isWin = (agent != null && agent.toLowerCase().indexOf("win") > -1);
80
81         Properties props = initCMgrProperties(req);
82
83         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
84         buffer.append(
85             "<request " +
86             "lps=\"" + XMLUtils.escapeXml(lps) + "\" " +
87             "url=\"" + XMLUtils.escapeXml(url) + "\" " +
88             "fullpath=\"" + XMLUtils.escapeXml(req.getRequestURI()) + "\" " +
89             "opt-url=\"" + XMLUtils.escapeXml(opturl) + "\" " +
90             "unopt-url=\"" + XMLUtils.escapeXml(unopturl) + "\" " +
91             "query_args=\"" + XMLUtils.escapeXml(query_args) + "\" " +
92             "pocketpc=\"" + isPocketPC + "\" " +
93             "windows=\"" + isWin + "\" ");
94         if (fileName != null) {
95             String JavaDoc optname = fileName.substring(0, fileName.length() - 4) + ".lzo";
96             buffer.append(
97                 "opt-exists=\"" + new File(optname).exists() + "\" ");
98         }
99         buffer.append(
100             ">\n");
101
102         for (Enumeration e = req.getParameterNames(); e.hasMoreElements(); ) {
103             String JavaDoc name = (String JavaDoc)e.nextElement();
104             String JavaDoc value = req.getParameter(name);
105             buffer.append("<param name=\"" + XMLUtils.escapeXml(name) + "\" ");
106             buffer.append("value=\"" + XMLUtils.escapeXml(value) + "\"/>\n");
107         }
108         buffer.append("</request>");
109
110         String JavaDoc infoXML = "";
111         if (fileName != null) {
112             boolean isOpt = fileName.endsWith(".lzo");
113             if (isOpt) {
114                 infoXML = getInfoXML(fileName, props);
115             } else {
116                 infoXML = getCompilationManager().getInfoXML(fileName, props);
117             }
118         }
119
120         buffer.append(infoXML);
121
122         return buffer.toString();
123     }
124
125     /**
126      * @return info XML string for .lzo files
127      */

128     private static String JavaDoc getInfoXML(String JavaDoc fileName, Properties props)
129         throws IOException
130     {
131         String JavaDoc enc = props.getProperty(LZHttpUtils.CONTENT_ENCODING);
132         String JavaDoc zippedSize = null;
133         String JavaDoc unzippedSize = null;
134         String JavaDoc size = null;
135         
136         try {
137             unzippedSize = "" + FileUtils.fileSize(new File(fileName));
138         } catch (FileNotFoundException e) {
139             mLogger.error(e.getMessage());
140         }
141         
142         {
143             String JavaDoc gzName = fileName + ".gz";
144             File f = new File(gzName);
145             // Handle case where .lzo exists but not .gz yet or
146
// gz out of date
147
File nongz = new File(fileName);
148             if (nongz.exists()) {
149                 if (!f.exists() || f.lastModified() < nongz.lastModified()) {
150                     FileUtils.encode(nongz, f, "gzip");
151                     f = new File(gzName);
152                 }
153             }
154             try {
155                 zippedSize = "" + FileUtils.fileSize(f);
156             } catch (FileNotFoundException e) {
157                 mLogger.error(e.getMessage());
158             }
159         }
160         
161         size = ("gzip".equals(enc)) ? zippedSize : unzippedSize;
162         
163         return "<info size=\"" + size +
164             "\" zipped-size=\"" + zippedSize +
165             "\" unzipped-size=\"" + unzippedSize +
166             "\" encoding=\"" + enc +
167             "\" />";
168     }
169     
170     protected void handleCompilationError(CompilationError e,
171                                           HttpServletRequest JavaDoc req,
172                                           HttpServletResponse JavaDoc res)
173         throws IOException
174     {
175         respondCompilationError(e, req, res);
176     }
177
178     public static void respondCompilationError(CompilationError e,
179                                                HttpServletRequest JavaDoc req,
180                                                HttpServletResponse JavaDoc res)
181         throws IOException
182     {
183         res.setContentType("text/html");
184         ServletOutputStream JavaDoc out = res.getOutputStream();
185         String JavaDoc xmlString =
186             "<errors>" +
187             getRequestXML(req, null) +
188             e.toXML() +
189             "</errors>";
190         try {
191             TransformUtils.applyTransform(sStyleSheetPathname, xmlString, out);
192         } catch (Exception JavaDoc ex) {
193             reportTransformException(req, sStyleSheetPathname, ex, out);
194         }
195     }
196     
197     /**
198      * Writes the canvas html. The canvas is the area in which the
199      * Laszlo application is rendered.
200      * @param out <tt>ServletOutputStream</tt> to write on
201      * @param req request to retrieve scheme, server name, server port and
202      * requested url
203      * @param canvas the canvas for the given request
204      */

205     private void writeCanvas(ServletOutputStream JavaDoc out, HttpServletRequest JavaDoc req,
206                              Canvas canvas, String JavaDoc fileName, boolean isKranked)
207         throws IOException
208     {
209         String JavaDoc xmlString = canvas.getXML(getRequestXML(req, fileName));
210         mLogger.debug(xmlString);
211         Properties properties = new Properties();
212         if (isKranked)
213             properties.setProperty("isKranked", "true");
214         try {
215             TransformUtils.applyTransform(sStyleSheetPathname, properties,
216                                           xmlString, out);
217         } catch (Exception JavaDoc e) {
218             reportTransformException(req, sStyleSheetPathname, e, out);
219         }
220     }
221     
222     /** Report the exception to output as an internal server error,
223      * rendered in HTML, with instructions for bug reporting and with
224      * a solution message if one is available.
225      */

226     protected static void reportTransformException(
227         HttpServletRequest JavaDoc req,
228         String JavaDoc styleSheetPathname,
229         Exception JavaDoc e,
230         OutputStream JavaDoc out)
231         throws IOException
232     {
233         // Note that the following doesn't quote HTML in the filename,
234
// message, and stacktrace. This is to make it as likely as
235
// possible that this will succeed, since it's typically
236
// called when the system is having trouble calling external
237
// functions or libraries. The failure mode is that under
238
// rare cases the display could be messed up, but it will
239
// still have enough information and the page source will have
240
// everything.
241

242         // Special solution message if the error contains this string:
243
final String JavaDoc XALAN_ERR_MSG =
244             "output format must have a '{http://xml.apache.org/xalan}content-handler' property";
245         
246         Writer writer = new OutputStreamWriter(out);
247         try {
248             String JavaDoc title = "500 Internal Server Error";
249             writer.write("<html><title>");
250             writer.write(title);
251             writer.write("</title>");
252             writer.write("<style type='text/css'>");
253             writer.write("table th {text-align: right; vertical-align: top; padding-right: 10pt}");
254             writer.write("</style>");
255             writer.write("</head><body><h1>");
256             writer.write(title);
257             writer.write("</h1>");
258             writer.write("<p>An internal server error occurred. ");
259             // Use toString() instead of getMessage(), since for chained
260
// exceptions it's possible for the original message to
261
// get buried where the latter doesn't retrieve it.
262
if (e.toString().indexOf(XALAN_ERR_MSG) >= 0) {
263                 writer.write("If you are running Tomcat, please verify that ");
264                 writer.write("that the <code>xalan.jar</code> file from the ");
265                 writer.write("LPS distribution has been installed in the ");
266                 writer.write("Tomcat <code>/common/endorsed</code> directory. ");
267                 writer.write("Otherwise, please check the ");
268                 writer.write("<a HREF='http://www.laszlosystems.com/developers/learn/documentation/faq/'>");
269                 writer.write("LPS Developer FAQ</a> for additional ");
270                 writer.write("instructions. If that does not work, please ");
271             } else {
272                 writer.write("Please ");
273             }
274             writer.write("send a copy of this web page and a ");
275             writer.write("description of your server environment (operating ");
276             writer.write("system, JRE version, servlet container and ");
277             writer.write("version) to ");
278             writer.write("<a HREF='mailto:bugs@laszlosystems.com'>");
279             writer.write("bugs@laszlosystems.com</a>.</p>");
280             writer.write("<hr /><table border='0'>");
281             // TODO [2004-04-29 ows]: Eric says the following LPS call
282
// should work, but it returns an empty string
283
//writer.write("<tr><th>Server Info</th>");
284
//writer.write("<td>" + LPS.getInfo(req, mContext, "lps-server-info") + "</td></tr>");
285
writer.write("<tr><th>Version</th>");
286             writer.write("<td>" + LPS.getShortVersion() + "</td></tr>");
287             writer.write("<tr><th>Build</th>");
288             writer.write("<td>" + LPS.getBuildDate() + "</td></tr>");
289             writer.write("<tr><th>Stylesheet</th>");
290             writer.write("<td>" + new File(styleSheetPathname).getName() + "</td></tr>");
291             writer.write("<tr><th>Message</th>");
292             writer.write("<td>" + e.getMessage() + "</td></tr>");
293             writer.write("</table><pre>");
294             writer.flush();
295             PrintStream ps = new PrintStream(out);
296             try {
297                 e.printStackTrace(ps);
298             } finally {
299                 ps.flush();
300             }
301             writer.write("</pre></body></html>");
302         } finally {
303             writer.close();
304         }
305     }
306     
307     /**
308      * Return all query args except for "lzt"
309      */

310     private static String JavaDoc getQueryArgs(HttpServletRequest JavaDoc req) {
311         StringBuffer JavaDoc query = new StringBuffer JavaDoc();
312         Enumeration e = req.getParameterNames();
313         while (e.hasMoreElements()) {
314             String JavaDoc name = (String JavaDoc)e.nextElement();
315             String JavaDoc val = req.getParameter(name);
316             if (!name.equals("lzt")) {
317                 query.append("&"+name+"="+URLEncoder.encode(val));
318             }
319         }
320         return query.toString();
321     }
322
323     public int getMimeType()
324     {
325         return MIME_TYPE_HTML;
326     }
327 }
328
Popular Tags