]> matita.cs.unibo.it Git - helm.git/blob - helm/uwobo/src/it/unibo/cs/helm/uwobo/Servlet.java
Initial revision
[helm.git] / helm / uwobo / src / it / unibo / cs / helm / uwobo / Servlet.java
1 /* Copyright (C) 2001, HELM Team
2  *
3  * This file is part of UWOBO, developed at the Computer Science
4  * Department, University of Bologna, Italy.
5  * 
6  * UWOBO is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * UWOBO is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with UWOBO; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
19  * MA  02111-1307, USA.
20  *
21  * For details, see the UWOBO World-Wide-Web page,
22  * http://cs.unibo.it/helm/uwobo
23  */
24
25 package it.unibo.cs.helm.uwobo;
26
27 import java.io.*;
28 import java.util.*;
29 import javax.servlet.*;
30 import javax.servlet.http.*;
31 import javax.xml.transform.*;
32 import org.xml.sax.*;
33
34 // WARNING: next comment is obsolete!!!!!
35 /*
36 *
37 * usage:
38 *   http://hostname/helm/servlet/uwobo/help
39 *   http://hostname/helm/servlet/uwobo/add?bind=key,stylesheet[&bind=key,stylesheet]*
40 *   http://hostname/helm/servlet/uwobo/remove[?keys=key_1,...,key_n]
41 *   http://hostname/helm/servlet/uwobo/list
42 *   http://hostname/helm/servlet/uwobo/reload[?keys=key_1,...,key_n]
43 *   http://hostname/helm/servlet/uwobo/apply?xmluri=xmldata&keys=key_1,...,key_n[&param.name=value]*[&param.key.name=value]*[&prop.name=[value]]*
44 *
45 * example:
46 *   http://aristotele/helm/servlet/uwobo/add?bind=foo1,file:///D:/Archivio/Progetti/helm/resources/xsl/foo1.xsl
47 *   http://aristotele/helm/servlet/uwobo/add?bind=foo2,file:///D:/Archivio/Progetti/helm/resources/xsl/foo2.xsl
48 *   http://aristotele/helm/servlet/uwobo/apply?xmluri=file:///D:/Archivio/Progetti/helm/resources/xsl/foo.xml&keys=foo1,foo2
49 *
50 * installation notes (Tomcat):
51 *       replace parser.jar and jaxp.jar from /lib with xerces.jar and add xalan.jar
52 *
53 *       add in conf/server.xml
54 *               <Context path="/helm" 
55 *                       docBase="webapps/helm" 
56 *                       crossContext="false"
57 *                       debug="0" 
58 *                       reloadable="true" > 
59 *               </Context>
60 *
61 *       add in uriworkermap.properties
62 *               /helm/*=ajp12
63 *
64 *
65 * @author The HELM team
66 */
67 public class Servlet extends HttpServlet {
68    
69    public static final String[] usage = {
70       "http://<i>hostname</i>/helm/servlet/uwobo/help",
71       "http://<i>hostname</i>/helm/servlet/uwobo/add?bind=<i>key</i>,<i>stylesheet</i>[&bind=<i>key</i>,<i>stylesheet</i>]*",
72       "http://<i>hostname</i>/helm/servlet/uwobo/remove[?keys=<i>key_1,...,key_n</i>]",
73       "http://<i>hostname</i>/helm/servlet/uwobo/list",
74       "http://<i>hostname</i>/helm/servlet/uwobo/reload[?keys=<i>key_1,...,key_n</i>]",
75       "http://<i>hostname</i>/helm/servlet/uwobo/apply?xmluri=<i>xmldata</i>&keys=<i>key_1,...,key_n</i>[&param.<i>name</i>=<i>value</i>]*[&param.<i>key</i>.<i>name</i>=<i>value</i>]*[&prop.<i>name</i>=[<i>value</i>]]*"
76    };
77    public static final String help;
78            
79    static {
80       StringBuffer sb = new StringBuffer();
81       sb.append("<ul>");
82       for (int i=0; i<usage.length; i++)
83          sb.append("<li>").append(usage[i]).append("</li>");
84       sb.append("</ul>");
85       help = sb.toString();
86    }
87
88    private Server server;
89
90    public void init(ServletConfig config)
91    throws ServletException
92    {
93       super.init(config);
94
95       System.out.println("UWOBO init");
96       server = new Server();
97    }
98
99    private static String[] split(final String s, final String delim)
100    {
101       String[] res = {null}; 
102       if (s == null) return res;
103       StringTokenizer st = new StringTokenizer(s, delim);
104       res = new String[st.countTokens()];
105       for (int i = 0; i < res.length; i++) res[i] = st.nextToken();
106       return res;
107    }
108         
109    private static String[] split2(final String s, final String delim)
110    {
111       String[] res = new String[2];
112       StringTokenizer st = new StringTokenizer(s);
113       res[0] = st.nextToken(delim); res[1] = st.nextToken("").substring(1);
114       return res;
115    }
116
117    private void html_open(HttpServletResponse resp, ServletOutputStream out)
118    throws IOException
119    {  
120       resp.setContentType("text/html");
121       out.println("<html><body bgcolor=\"#ffffff\"><h1>" + server.PACKAGE + " servlet</h1>");
122    }
123    
124    private void html_close(ServletOutputStream out)
125    throws IOException
126    {
127       out.println("<p>done</p></body></html>");
128       out.close();
129    }
130
131    private String msg_out(String message)
132    {
133       return message+"<br />";
134    }
135    
136    private String exc_out(String message, Exception e)
137    {
138       if (message == null)
139       {
140          message = e.getClass().getName();
141          message = message.substring(message.lastIndexOf('.')+1);
142       }
143       String local = e.getLocalizedMessage();
144       local = local.substring(local.lastIndexOf(':')+1);
145       return "<b style=\"color: red\">"+message+": "+local+"</b><br />";
146    }
147    
148    public void doGet(HttpServletRequest request, HttpServletResponse response)
149    throws ServletException, IOException
150    {
151       ServletOutputStream out = response.getOutputStream();
152       String log = "";
153       
154       response.setHeader("Cache-Control", "no-cache");
155       response.setHeader("Pragma", "no-cache");
156       response.setHeader("Expires", "0");
157       System.out.println("UWOBO "+request.getPathInfo());
158                 
159       try { 
160          final String cmd = request.getPathInfo();
161          if (cmd == null) { 
162             sendError(response, out, "unknown command", help); return;
163          } 
164          if (cmd.equals("/add")) {
165             final String[] xslkey = request.getParameterValues("bind");
166             if (xslkey == null) {
167                sendError(response, out, "bad parameters", usage[1]); return;
168             } 
169             html_open(response, out);
170             for (int i = 0; i < xslkey.length; i++) {
171                final String data[] = split2(xslkey[i], ",");
172                out.println(msg_out("adding stylesheet "+data[0]+" ("+data[1]+")"));
173                try {
174                   log = server.add(data[1], data[0]);
175                   if(!log.equals(""))
176                      out.println(msg_out(log));
177                 } catch (TransformerConfigurationException tce) {
178                   out.println(exc_out("Stylesheet Error", tce));
179                } catch (Exception e) {
180                   out.println(exc_out(null, e));
181                }
182             }
183             html_close(out); return;
184          }
185          if (cmd.equals("/apply")) {
186             final String infile = request.getParameter("xmluri");
187             final String keys = request.getParameter("keys");
188
189             if (infile == null || keys == null) {
190                sendError(response, out, "bad parameters", usage[6]); return;
191             } 
192
193             final String[] keyName = split(keys, ",");
194             final Key[] keySeq = new Key[keyName.length];
195             for (int i = 0; i < keySeq.length; i++) {
196                keySeq[i] = new Key();
197                keySeq[i].name = keyName[i];
198                keySeq[i].params = new HashMap();
199             }
200
201             final Properties props = new Properties();
202             final Enumeration e = request.getParameterNames();
203             while (e.hasMoreElements()) {
204                String param = (String) e.nextElement();
205                if (param.startsWith("param.")) {
206                   final String name = param.substring(6);
207                   final String value = request.getParameter(param);
208                   final String[] keyParam = split(name, ".");
209                   if (keyParam.length == 1) {
210                      // this is a global parameter
211                      Server.log("global parameter: " + keyParam[0] + " = " + value);
212                      for (int i = 0; i < keySeq.length; i++)
213                         // we add the global parameter only if there is no
214                         // local parameter with the same name
215                         if (!keySeq[i].params.containsKey(keyParam[0]))
216                            keySeq[i].params.put(keyParam[0], value);
217                   } else
218                   if (keyParam.length == 2) {
219                      // this is a local parameter
220                      Server.log("local parameter: " + keyParam[0] + "." + keyParam[1] + " = " + value);
221                      for (int i = 0; i < keySeq.length; i++) {
222                         if (keySeq[i].name.equals(keyParam[0]))
223                            keySeq[i].params.put(keyParam[1], value);
224                      }
225                   } else { 
226                      sendError(response, out, "bad parameters", usage[6]); return;
227                   }
228                } else
229                if (param.startsWith("prop.")) {
230                   final String name = param.substring(5);
231                   final String value = request.getParameter(param);
232                   Server.log("property: " + name + " = " + value);
233                   props.setProperty(name, value);
234                }
235             }
236                                         
237             String contentType = props.getProperty(OutputKeys.MEDIA_TYPE);
238             if (contentType == null && keySeq.length > 0) 
239                contentType = server.getContentType(keySeq[keySeq.length - 1].name);
240             else if (contentType == null)
241                contentType = "text/xml";
242             response.setContentType(contentType);
243             Server.log("content type: " + contentType);
244
245             try {
246                out = response.getOutputStream(); 
247                server.apply(infile, out, keySeq, props);
248                out.close();
249             } catch (TransformerConfigurationException tce) {
250                sendError(response, out, exc_out("stylesheet error", tce), "");
251             } catch (Exception ee) {
252                sendError(response, out, exc_out(null, ee), "");
253             }
254             return;
255          }
256          if (cmd.equals("/remove")) {
257             final String key = request.getParameter("keys");
258             final String [] data = split(key, ",");
259             html_open(response, out);
260             for (int i = 0; i < data.length; i++) { 
261                if (data[i] == null) {
262                   out.println(msg_out("removing all keys"));
263                   ArrayList res;
264                   res = server.removeAll();
265                   Iterator j = res.iterator();
266                   while (j.hasNext())
267                      out.println(msg_out((String)j.next()));
268                } else {
269                   out.println(msg_out("removing key "+data[i]));
270                   out.println(msg_out(server.remove(data[i])));
271                }
272             }
273             html_close(out); return;
274          }
275          if (cmd.equals("/list")) {
276             html_open(response, out);
277             out.println("<p>stylesheet list:</p><ul>");
278             
279             Iterator i = server.list().iterator();
280             while (i.hasNext())
281                out.println("<li>"+i.next()+"</li>");
282             out.println("</ul>"); html_close(out); return;
283          }
284          if (cmd.equals("/reload")) {
285             final String key = request.getParameter("keys");
286             final String [] data = split(key, ",");
287             html_open(response, out);
288             for (int i = 0; i < data.length; i++) {
289                try {
290                   if (data[i] == null) {
291                      out.println(msg_out("reloading all keys"));
292                      ArrayList res;
293                      res = server.reloadAll();
294                      Iterator j = res.iterator();
295                      while(j.hasNext())
296                         out.println(msg_out((String)j.next()));
297                   } else {
298                      out.println(msg_out("reloading key "+data[i]));
299                      out.println(msg_out(server.reload(data[i])));
300                   }
301                } catch (TransformerConfigurationException tce) {
302                   out.println(exc_out("Stylesheet Error", tce));
303                } catch (Exception e) {
304                   out.println(exc_out(null, e));
305                }
306             }
307             html_close(out); return;
308          }
309          if (cmd.equals("/help")) {
310             html_open(response, out);
311             out.println("<h2>Version "+server.VERSION+"</h1>");
312             out.println("<b>compiled "+server.DATE+" at "+server.TIME.substring(0,2)+":"+server.TIME.substring(2)+"</b>");
313             if(Server.SERIALIZATION_DIR.equals("")) {
314                out.println("<p><b>Stylesheet serialization is off.</b>");
315                out.println("(To turn it on, choose a non-empty value for the " +
316                   "SERIALIZATION_DIR property.)</p>");
317             } else
318                out.println("<p><b>Serialized stylesheed are stored in &quot;" +
319                   Server.SERIALIZATION_DIR + "&quot;.</b></p>");
320             out.println("<p>usage:</p>"+help+"</body></html>");
321             html_close(out); return;
322          }
323          sendError(response, out, "unknown command", help); return;
324       } catch (Exception e) {
325          sendError(response, out, exc_out(null, e),"");
326          return;
327       }
328    }
329
330    private void sendError(HttpServletResponse resp, ServletOutputStream out, 
331                           String msg, String usage)
332    throws IOException 
333    {
334       html_open(resp, out);
335       out.println("<p>"+msg+"</p>usage: "+usage);
336       html_close(out);
337    }
338         
339    public String getServletInfo()
340    {
341       return "The UWOBO servlet";
342    }
343 }