KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snipsnap > net > PluginServlet


1 /*
2  * This file is part of "SnipSnap Wiki/Weblog".
3  *
4  * Copyright (c) 2002 Stephan J. Schmidt, Matthias L. Jugel
5  * All Rights Reserved.
6  *
7  * Please visit http://snipsnap.org/ for updates and contact.
8  *
9  * --LICENSE NOTICE--
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  * --LICENSE NOTICE--
24  */

25 package org.snipsnap.net;
26
27 import groovy.text.SimpleTemplateEngine;
28 import groovy.text.Template;
29 import org.radeox.util.logging.Logger;
30 import org.snipsnap.app.Application;
31 import org.snipsnap.container.Components;
32 import org.snipsnap.snip.Snip;
33 import org.snipsnap.snip.SnipSpace;
34 import org.snipsnap.snip.label.TypeLabel;
35 import org.snipsnap.user.Permissions;
36 import org.snipsnap.user.Roles;
37 import org.snipsnap.user.Security;
38
39 import javax.servlet.RequestDispatcher JavaDoc;
40 import javax.servlet.ServletException JavaDoc;
41 import javax.servlet.http.HttpServlet JavaDoc;
42 import javax.servlet.http.HttpServletRequest JavaDoc;
43 import javax.servlet.http.HttpServletResponse JavaDoc;
44 import java.io.BufferedReader JavaDoc;
45 import java.io.BufferedWriter JavaDoc;
46 import java.io.IOException JavaDoc;
47 import java.io.InputStream JavaDoc;
48 import java.io.InputStreamReader JavaDoc;
49 import java.io.OutputStream JavaDoc;
50 import java.io.Writer JavaDoc;
51 import java.util.Collection JavaDoc;
52 import java.util.HashMap JavaDoc;
53 import java.util.Iterator JavaDoc;
54 import java.util.Map JavaDoc;
55
56 public class PluginServlet extends HttpServlet JavaDoc {
57   private Map JavaDoc extTypeMap = new HashMap JavaDoc();
58   private Map JavaDoc servletCache = new HashMap JavaDoc();
59
60   private final static Roles EXEC_ROLES = new Roles(Roles.ADMIN);
61
62   SimpleTemplateEngine templateEngine = new SimpleTemplateEngine();
63
64   public void init() throws ServletException JavaDoc {
65     super.init();
66
67     // currently supported script types (with extensions)
68
extTypeMap.put(".gsp", "text/gsp");
69     extTypeMap.put(".groovy", "text/groovy");
70   }
71
72   protected void service(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
73     // get actual name of the plugin to call
74
String JavaDoc pluginName = (String JavaDoc) request.getAttribute("javax.servlet.include.path_info");
75     if (null == pluginName) {
76       pluginName = request.getPathInfo();
77     }
78
79     if (pluginName.startsWith("/")) {
80       pluginName = pluginName.substring(1);
81     }
82
83     // check for the plugin in the snip space which overrides other plugins
84
SnipSpace space = (SnipSpace) Components.getComponent(SnipSpace.class);
85     if (space.exists(pluginName)) {
86       Snip snip = space.load(pluginName);
87       // only execute plugins who are locked by an Admin
88
if (Security.existsPermission(Permissions.EDIT_SNIP, snip, EXEC_ROLES)) {
89         String JavaDoc mimeType = getMIMEType(snip);
90         if ("text/gsp".equalsIgnoreCase(mimeType)) {
91           BufferedWriter JavaDoc writer = new BufferedWriter JavaDoc(response.getWriter());
92           try {
93             handleGroovyTemplate(snip.getContent(), writer);
94           } catch (Exception JavaDoc e) {
95             writer.write("<span class=\"error\">" + e.getLocalizedMessage() + "</span>");
96           }
97           writer.flush();
98         } else {
99           // plugins of types other than text/gsp are included into the response
100
RequestDispatcher JavaDoc dispatcher = request.getRequestDispatcher("/raw/" + pluginName);
101           dispatcher.include(request, response);
102         }
103         return;
104       }
105     }
106
107     // check for registered plugins
108
Map JavaDoc plugins = ServletPluginLoader.getPlugins();
109     if (plugins.containsKey(pluginName)) {
110       String JavaDoc handlerMIMEType = (String JavaDoc) plugins.get(pluginName);
111
112       // try to find a mime type for the requested plugin
113
if (null == handlerMIMEType) {
114         int extIndex = pluginName.indexOf(".");
115         if (extIndex != -1) {
116           handlerMIMEType = (String JavaDoc) extTypeMap.get(pluginName.substring(extIndex));
117         }
118       }
119
120       if ("text/gsp".equalsIgnoreCase(handlerMIMEType)) {
121         BufferedWriter JavaDoc writer = new BufferedWriter JavaDoc(response.getWriter());
122         try {
123           handleGroovyTemplate(getTemplateSource(pluginName), writer);
124         } catch (Exception JavaDoc e) {
125           e.printStackTrace();
126           writer.write("<span class=\"error\">" + e.getLocalizedMessage() + "</span>");
127         }
128         writer.flush();
129         return;
130       } else {
131         // a non-script plugin (i.e. servlet or simply a file)
132
ServletPlugin servletPlugin = (ServletPlugin) servletCache.get(pluginName);
133         if (null == servletPlugin) {
134           try {
135             servletPlugin = getServletPlugin(pluginName);
136             servletCache.put(pluginName, servletPlugin);
137           } catch (Exception JavaDoc e) {
138             // ignore plugins not found ...
139
}
140         }
141
142         // a servlet plugin is executed, everything else is included into the response
143
if (null != servletPlugin) {
144           try {
145             servletPlugin.service(request, response);
146           } catch (Exception JavaDoc e) {
147             Logger.warn("error while executing servlet plugin", e);
148             throw new ServletException JavaDoc("error while executing servlet plugin", e);
149           }
150         } else {
151           if (null != handlerMIMEType) {
152             response.setContentType(handlerMIMEType);
153           }
154           OutputStream JavaDoc out = response.getOutputStream();
155           InputStream JavaDoc fileIs = PluginServlet.class.getResourceAsStream("/" + pluginName);
156           if (null != fileIs) {
157             byte[] buffer = new byte[1024];
158             int bytes = 0;
159             while ((bytes = fileIs.read(buffer)) != -1) {
160               out.write(buffer, 0, bytes);
161             }
162             out.flush();
163           } else {
164             throw new ServletException JavaDoc("unable to load servlet plugin: not found");
165           }
166         }
167         return;
168       }
169     }
170
171     response.sendError(HttpServletResponse.SC_FORBIDDEN);
172   }
173
174   private ServletPlugin getServletPlugin(String JavaDoc pluginName) throws Exception JavaDoc {
175     Class JavaDoc pluginClass = Class.forName(pluginName);
176     return (ServletPlugin) pluginClass.newInstance();
177   }
178
179   private String JavaDoc getMIMEType(Snip snip) {
180     Collection JavaDoc mimeTypes = snip.getLabels().getLabels("TypeLabel");
181     if (!mimeTypes.isEmpty()) {
182       Iterator JavaDoc handlerIt = mimeTypes.iterator();
183       while (handlerIt.hasNext()) {
184         TypeLabel mimeType = (TypeLabel) handlerIt.next();
185         return mimeType.getTypeValue();
186       }
187     }
188     return null;
189   }
190
191   private void handleGroovyTemplate(String JavaDoc source, Writer JavaDoc out) throws Exception JavaDoc {
192     try {
193       Template groovyTemplate = templateEngine.createTemplate(source);
194       groovyTemplate.make(Application.get().getParameters()).writeTo(out);
195     } catch (Error JavaDoc e) {
196       e.printStackTrace();
197       throw new ServletException JavaDoc("groovy error", e);
198     }
199   }
200
201   /**
202    * Read the template source from either a snip or if not existent try the
203    * jar/classpath based file read.
204    *
205    * @param name the name of the resource to load
206    * @return a string with the template source
207    * @throws IOException
208    */

209   private String JavaDoc getTemplateSource(String JavaDoc name) throws IOException JavaDoc {
210     InputStream JavaDoc resource = getClass().getResourceAsStream("/" + name);
211     if (null != resource) {
212       // if there is no snip to load, try jar/classpath based file read
213
BufferedReader JavaDoc reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(resource));
214       StringBuffer JavaDoc content = new StringBuffer JavaDoc();
215       char buffer[] = new char[1024];
216       int length = 0;
217       while ((length = reader.read(buffer)) != -1) {
218         content.append(buffer, 0, length);
219       }
220       return content.toString();
221     }
222
223     throw new IOException JavaDoc("unable to load template source: '" + name + "'");
224   }
225 }
226
Popular Tags