KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > xsl > transform > TransformServlet


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.xsl.transform;
21
22 import java.io.IOException JavaDoc;
23 import java.io.PrintWriter JavaDoc;
24 import java.net.MalformedURLException JavaDoc;
25 import java.net.URL JavaDoc;
26 import java.net.UnknownHostException JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.Vector JavaDoc;
30 import javax.servlet.ServletConfig JavaDoc;
31 import javax.servlet.ServletException JavaDoc;
32 import javax.servlet.http.HttpServlet JavaDoc;
33 import javax.servlet.http.HttpServletRequest JavaDoc;
34 import javax.servlet.http.HttpServletResponse JavaDoc;
35 import javax.xml.transform.Result JavaDoc;
36 import javax.xml.transform.Source JavaDoc;
37 import javax.xml.transform.TransformerException JavaDoc;
38 import javax.xml.transform.stream.StreamResult JavaDoc;
39 import org.netbeans.api.xml.cookies.CookieMessage;
40 import org.netbeans.api.xml.cookies.CookieObserver;
41 import org.netbeans.api.xml.cookies.TransformableCookie;
42 import org.netbeans.api.xml.cookies.XMLProcessorDetail;
43 import org.netbeans.modules.xsl.utils.TransformUtil;
44 import org.netbeans.spi.xml.cookies.DefaultXMLProcessorDetail;
45 import org.openide.filesystems.FileObject;
46 import org.openide.filesystems.FileSystem;
47 import org.openide.filesystems.Repository;
48 import org.openide.filesystems.URLMapper;
49 import org.xml.sax.SAXParseException JavaDoc;
50
51 /**
52  *
53  * @author Libor Kramolis
54  */

55 public class TransformServlet extends HttpServlet JavaDoc {
56     private static final long serialVersionUID = 1632869007241230624L;
57
58     private static TransformableCookie transformable;
59     /** Last cached XML Source. */
60     private static Source JavaDoc xmlSource;
61     /** Last cached XSL Script. */
62     private static Source JavaDoc xslSource;
63     
64     
65     public static void prepare (TransformableCookie trans, Source JavaDoc xml, Source JavaDoc xsl) {
66         transformable = trans;
67         xmlSource = xml;
68         xslSource = xsl;
69     }
70
71     /** Initializes the servlet.
72      */

73     public void init (ServletConfig JavaDoc config) throws ServletException JavaDoc {
74         super.init (config);
75     }
76     
77     /** Destroys the servlet.
78      */

79     public void destroy () {
80         xmlSource = null;
81         xslSource = null;
82     }
83     
84     /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
85      * @param request servlet request
86      * @param response servlet response
87      */

88     protected void processRequest (HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
89         PrintWriter JavaDoc out = response.getWriter();
90         Result JavaDoc outputResult = new StreamResult JavaDoc (out);
91
92         Observer notifier = new Observer();
93         try {
94             String JavaDoc guessOutputExt = TransformUtil.guessOutputExt (xslSource);
95             String JavaDoc mimeType;
96             if (guessOutputExt.equals("txt")) { // NOI18N
97
mimeType = "text/plain"; // NOI18N
98
} else if (guessOutputExt.equals("xml")) { // NOI18N
99
mimeType = "text/xml"; // NOI18N
100
} else if (guessOutputExt.equals("html")) { // NOI18N
101
mimeType = "text/html"; // NOI18N
102
} else {
103                 mimeType = null;
104             }
105
106             if ( mimeType != null ) {
107                 response.setContentType (mimeType);
108             }
109
110             if ( Util.THIS.isLoggable() ) /* then */ {
111                 Util.THIS.debug ("[TransformServlet] Response MIME Type: '" + mimeType + "'");
112                 Util.THIS.debug (" xmlSource.getSystemId() = " + xmlSource.getSystemId());
113                 Util.THIS.debug (" transformable = " + transformable);
114                 Util.THIS.debug (" xslSource.getSystemId() = " + xslSource.getSystemId());
115             }
116
117             TransformUtil.transform (xmlSource, transformable, xslSource, outputResult, notifier);
118         } catch (Exception JavaDoc exc) {
119             if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug (" EXCEPTION!!!: " + exc.getClass().getName(), exc);
120
121             // thrown if error in style sheet
122
CookieMessage message = null;
123             
124             if ( exc instanceof TransformerException JavaDoc ) {
125                 // do not log again TransformerException, it is already done by ErrorListener
126
} else if ( exc instanceof SAXParseException JavaDoc ) {
127                 message = new CookieMessage
128                     (TransformUtil.unwrapException (exc).getLocalizedMessage(),
129                      CookieMessage.FATAL_ERROR_LEVEL,
130                      new DefaultXMLProcessorDetail ((SAXParseException JavaDoc) exc)
131                      );
132             } else {
133                 message = new CookieMessage
134                     (exc.getLocalizedMessage(),
135                      CookieMessage.FATAL_ERROR_LEVEL
136                      );
137             }
138
139             if ( Util.THIS.isLoggable() ) /* then */ {
140                 Util.THIS.debug (" message = " + message);
141                 Util.THIS.debug (" notifier = " + notifier);
142             }
143
144             if ( message != null ) {
145                 notifier.receive (message);
146             }
147
148             // create warning page
149
response.setContentType ("text/html");
150
151             out.println ("<html><head>");
152             out.println (" <title>" + Util.THIS.getString ("MSG_error_html_title") + "</title>");
153             out.println (" <style>" + Util.THIS.getString ("MSG_error_html_style") + "</style>");
154             out.println ("</head><body>");
155             out.println (" <h2>" + Util.THIS.getString ("MSG_error_page_title") + "</h2>");
156             out.println (" <p>" + Util.THIS.getString ("MSG_error_page_message") + "</p>");
157             out.println (" <hr size=\"1\" noshade=\"\" />\n" + generateReport (notifier.getList()) + "<hr size=\"1\" noshade=\"\" />");
158             out.println (" <p>" + Util.THIS.getString ("MSG_error_bottom_message") + "</p>");
159             out.println ("</body></html>");
160         } finally {
161             out.close();
162         }
163     }
164     
165     /** Handles the HTTP <code>GET</code> method.
166      * @param request servlet request
167      * @param response servlet response
168      */

169     protected void doGet (HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
170         processRequest (request, response);
171     }
172     
173     /** Handles the HTTP <code>POST</code> method.
174      * @param request servlet request
175      * @param response servlet response
176      */

177     protected void doPost (HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
178         processRequest (request, response);
179     }
180     
181     /** Returns a short description of the servlet.
182      */

183     public String JavaDoc getServletInfo () {
184         return "XSL Transformation Preview Servlet";
185     }
186
187     public static URL JavaDoc getServletURL () throws MalformedURLException JavaDoc, UnknownHostException JavaDoc {
188         
189         URL JavaDoc base = getSampleHTTPServerURL();
190         // XXX hack: assume that the path /servlet/CLASSNAME works on this server.
191
URL JavaDoc root = new URL JavaDoc (base.getProtocol(), base.getHost(), base.getPort(), "/servlet/" + TransformServlet.class.getName() + "/");
192         
193         return root;
194     }
195
196     private static URL JavaDoc getSampleHTTPServerURL() {
197         FileSystem fs = Repository.getDefault().getDefaultFileSystem();
198         FileObject fo = fs.findResource("HTTPServer_DUMMY");
199         if (fo == null) {
200             return null;
201         }
202         URL JavaDoc u = URLMapper.findURL(fo, URLMapper.NETWORK);
203         return u;
204     }
205
206     private String JavaDoc generateReport (List JavaDoc msgList) {
207         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
208
209         try {
210
211         Iterator JavaDoc it = msgList.iterator();
212         while ( it.hasNext() ) {
213             CookieMessage msg = (CookieMessage) it.next();
214             XMLProcessorDetail detail = (XMLProcessorDetail) msg.getDetail (XMLProcessorDetail.class);
215
216             // Message
217
sb.append (" &nbsp;&nbsp;&nbsp;&nbsp;<font class=\"").append (levelName (msg.getLevel())).append ("\">").append (msg.getMessage()).append ("</font>"); // NOI18N
218

219             if ( detail != null ) {
220                 // SystemId
221
String JavaDoc systemId = preferFileName (detail.getSystemId());
222                 if ( systemId != null ) {
223                     sb.append ("&nbsp;(<font class=\"system-id\">");
224                     boolean isFile = systemId.startsWith ("file:");
225                     if ( isFile ) {
226                         sb.append ("<a HREF=\"").append (systemId).append ("\">");
227                     }
228                     sb.append (systemId);
229                     if ( isFile ) {
230                         sb.append ("</a>");
231                     }
232                     sb.append ("</font>\n"); // NOI18N
233
// LineNumber
234
sb.append ("&nbsp;[<font class=\"line-number\">").append (detail.getLineNumber()).append ("</font>])<br>"); // NOI18N
235
}
236             }
237         }
238
239         } catch (Exception JavaDoc exc) {
240             if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug (exc);
241         }
242
243         return sb.toString();
244     }
245
246
247     private String JavaDoc preferFileName (String JavaDoc systemId) {
248         String JavaDoc name = systemId;
249
250         try {
251             URL JavaDoc url = new URL JavaDoc (systemId);
252             FileObject fo = URLMapper.findFileObject(url);
253             if (fo != null) {
254                 name = TransformUtil.getURLName (fo);
255             }
256         } catch (Exception JavaDoc exc) {
257             // ignore it -> use systemId
258

259             if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug (exc);
260         }
261
262         return name;
263     }
264
265     private String JavaDoc levelName (int level) {
266         if ( level == CookieMessage.FATAL_ERROR_LEVEL ) {
267             return "fatal-error"; // NOI18N
268
} else if ( level == CookieMessage.ERROR_LEVEL ) {
269             return "error"; // NOI18N
270
} else if ( level == CookieMessage.WARNING_LEVEL ) {
271             return "warning"; // NOI18N
272
} else { // CookieMessage.INFORMATIONAL_LEVEL
273
return "informational"; // NOI18N
274
}
275     }
276
277
278     //
279
// class Observer
280
//
281

282     private static class Observer implements CookieObserver {
283
284         private final List JavaDoc msgList;
285         
286         public Observer () {
287             msgList = new Vector JavaDoc();
288         }
289
290         public void receive (CookieMessage msg) {
291             msgList.add (msg);
292         }
293
294         public List JavaDoc getList () {
295             return msgList;
296         }
297     }
298 }
299
Popular Tags