1 25 package org.snipsnap.net; 26 27 import groovy.text.SimpleTemplateEngine; 28 import groovy.text.Template; 29 import org.snipsnap.app.Application; 30 import org.snipsnap.container.Components; 31 import org.snipsnap.snip.SnipSpace; 32 33 import javax.servlet.ServletException ; 34 import javax.servlet.http.HttpServlet ; 35 import javax.servlet.http.HttpServletRequest ; 36 import javax.servlet.http.HttpServletResponse ; 37 import java.io.BufferedReader ; 38 import java.io.IOException ; 39 import java.io.InputStream ; 40 import java.io.InputStreamReader ; 41 42 public class GroovyTemplateServlet extends HttpServlet { 43 44 SimpleTemplateEngine templateEngine = new SimpleTemplateEngine(); 45 46 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException { 47 48 String groovyFile = (String ) request.getAttribute("javax.servlet.include.path_info"); 49 if (null == groovyFile) { 50 groovyFile = request.getPathInfo(); 51 } 52 53 if (groovyFile.startsWith("/")) { 54 groovyFile = groovyFile.substring(1); 55 } 56 57 String templateSource = getTemplateSource(groovyFile); 58 try { 59 Template groovyTemplate = templateEngine.createTemplate(templateSource); 60 groovyTemplate.make(Application.get().getParameters()).writeTo(response.getWriter()); 61 } catch (Exception e) { 62 e.printStackTrace(); 63 } 64 } 65 66 74 private String getTemplateSource(String name) throws IOException { 75 SnipSpace space = (SnipSpace) Components.getComponent(SnipSpace.class); 76 if (space.exists(name)) { 77 return space.load(name).getContent(); 78 } 79 80 InputStream resource = getClass().getResourceAsStream(name); 81 if (null != resource) { 82 BufferedReader reader = new BufferedReader (new InputStreamReader (resource)); 84 StringBuffer content = new StringBuffer (); 85 char buffer[] = new char[1024]; 86 int length = 0; 87 while ((length = reader.read(buffer)) != -1) { 88 content.append(buffer, 0, length); 89 } 90 return content.toString(); 91 } 92 93 throw new IOException ("unable to load template source: '" + name + "'"); 94 } 95 } 96 | Popular Tags |