/** * Initialize the GroovyServlet. * * @throws ServletException * if this method encountered difficulties */ public void init(ServletConfig config) throws ServletException { super.init(config); // Set up the scripting engine gse = createGroovyScriptEngine(); servletContext.log("Groovy servlet initialized on " + gse + "."); }
@Override public void setVariable(String name, Object value) { lazyInit(); validateArgs(name, "Can't bind variable to"); excludeReservedName(name, "out"); excludeReservedName(name, "sout"); excludeReservedName(name, "html"); excludeReservedName(name, "json"); excludeReservedName(name, "forward"); excludeReservedName(name, "include"); excludeReservedName(name, "redirect"); super.setVariable(name, value); }
log("Creating/getting cached template..."); File file = super.getScriptUriAsFile(request); if (file != null) { name = file.getName(); template = getTemplate(file); getMillis = System.currentTimeMillis() - getMillis; } else { name = super.getScriptUri(request); URL url = servletContext.getResource(name); getMillis = System.currentTimeMillis(); template = getTemplate(url); getMillis = System.currentTimeMillis() - getMillis; ServletBinding binding = new ServletBinding(request, response, servletContext); setVariables(binding); Writer out = (Writer) binding.getVariable("out"); if (out == null) { out = response.getWriter(); log("Making template \"" + name + "\"..."); template.make(binding.getVariables()).writeTo(out); makeMillis = System.currentTimeMillis() - makeMillis; log("Template \"" + name + "\" request responded. [create/get=" + getMillis + " ms, make=" + makeMillis + " ms]");
/** * Initializes the servlet from hints the container passes. * <p> * Delegates to sub-init methods and parses the following parameters: * <ul> * <li> <tt>"generatedBy"</tt> : boolean, appends "Generated by ..." to the * HTML response text generated by this servlet. * </li> * </ul> * * @param config Passed by the servlet container. * @throws ServletException if this method encountered difficulties * @see TemplateServlet#initTemplateEngine(ServletConfig) */ public void init(ServletConfig config) throws ServletException { super.init(config); this.engine = initTemplateEngine(config); if (engine == null) { throw new ServletException("Template engine not instantiated."); } String value = config.getInitParameter("generated.by"); if (value != null) { this.generateBy = Boolean.valueOf(value); } value = config.getInitParameter(GROOVY_SOURCE_ENCODING); if (value != null) { this.fileEncodingParamVal = value; } log("Servlet " + getClass().getName() + " initialized on " + engine.getClass()); }
/** * @return a writer, an output stream, a markup builder or another requested object */ @Override public Object getVariable(String name) { lazyInit(); validateArgs(name, "No variable with"); return super.getVariable(name); }
log("Creating new template from " + key + "..."); Template template = engine.createTemplate(reader); cache.put(key, new TemplateCacheEntry(file, template, verbose)); log("Created and added template to cache. [key=" + key + "] " + cache.get(key));
log("Logging request class and its class loader:"); log(" c = request.getClass() :\"" + request.getClass() + "\""); log(" l = c.getClassLoader() :\"" + request.getClass().getClassLoader() + "\""); log(" l.getClass() :\"" + request.getClass().getClassLoader().getClass() + "\""); uri += info; return applyResourceNameMatcher(uri); return applyResourceNameMatcher(uri);
protected String applyResourceNameMatcher (String uri) { if (resourceNamePattern != null) {// mangle resource name with the compiled pattern. Matcher matcher = resourceNamePattern.matcher(uri); String replaced; if (resourceNameReplaceAll) { replaced = matcher.replaceAll(resourceNameReplacement); } else { replaced = matcher.replaceFirst(resourceNameReplacement); } if (!uri.equals(replaced)) { if (verbose) { log("Replaced resource name \"" + uri + "\" with \"" + replaced + "\"."); } return replaced; } } return uri; }
/** * Gets the template created by the underlying engine parsing the request. * * <p> * This method looks up a simple (weak) hash map for an existing template * object that matches the source URL. If there is no cache entry, a new one is * created by the underlying template engine. This new instance is put * to the cache for consecutive calls. * * @return The template that will produce the response text. * @param url The URL containing the template source.. * @throws ServletException If the request specified an invalid template source URL */ protected Template getTemplate(URL url) throws ServletException { String key = url.toString(); Template template = findCachedTemplate(key, null); // Template not cached or the source file changed - compile new template! if (template == null) { try { template = createAndStoreTemplate(key, url.openConnection().getInputStream(), null); } catch (Exception e) { throw new ServletException("Creation of template failed: " + e, e); } } return template; }
public PrintWriter getWriter() { return new PrintWriter(new InvalidOutputStream()) { public boolean checkError() { return getResponseWriter().checkError();
@Override public Map getVariables() { lazyInit(); return super.getVariables(); }
/** * Parses the http request for the real script or template source file. * * @param request * the http request to analyze * @return a file object using an absolute file path name, or <code>null</code> if the * servlet container cannot translate the virtual path to a real * path for any reason (such as when the content is being made * available from a .war archive). */ protected File getScriptUriAsFile(HttpServletRequest request) { String uri = getScriptUri(request); String real = servletContext.getRealPath(uri); if (real == null) { return null; } return new File(real).getAbsoluteFile(); }
public Object call() { try { return ((GroovyScriptEngine) getDelegate()).run(scriptUri, binding); } catch (ResourceException e) { throw new RuntimeException(e); } catch (ScriptException e) { throw new RuntimeException(e); } }
/** * Creates the template engine. * <p> * Called by {@link TemplateServlet#init(ServletConfig)} and returns just * <code>new groovy.text.SimpleTemplateEngine()</code> if the init parameter * <code>template.engine</code> is not set by the container configuration. * * @param config Current servlet configuration passed by the container. * @return The underlying template engine or <code>null</code> on error. */ protected TemplateEngine initTemplateEngine(ServletConfig config) { String name = config.getInitParameter("template.engine"); if (name == null) { return new SimpleTemplateEngine(); } try { return (TemplateEngine) Class.forName(name).newInstance(); } catch (InstantiationException e) { log("Could not instantiate template engine: " + name, e); } catch (IllegalAccessException e) { log("Could not access template engine class: " + name, e); } catch (ClassNotFoundException e) { log("Could not find template engine class: " + name, e); } return null; }
public void testRequestGetCommandOK() { Mock requestMock = mock(HttpServletRequest.class); requestMock.expects(once()).method("getParameter").with(eq("command")).will(returnValue("SELECT...")); HttpServletRequest request = (HttpServletRequest) requestMock.proxy(); String command = request.getParameter("command"); assertEquals("SELECT...", command); } }
/** * Interface method for ResourceContainer. This is used by the GroovyScriptEngine. */ public URLConnection getResourceConnection (String name) throws ResourceException { name = removeNamePrefix(name).replace('\\', '/'); //remove the leading / as we are trying with a leading / now if (name.startsWith("WEB-INF/groovy/")) { name = name.substring(15);//just for uniformity } else if (name.startsWith("/")) { name = name.substring(1); } /* * Try to locate the resource and return an opened connection to it. */ try { URL url = servletContext.getResource('/' + name); if (url == null) { url = servletContext.getResource("/WEB-INF/groovy/" + name); } if (url == null) { throw new ResourceException("Resource \"" + name + "\" not found!"); } return url.openConnection(); } catch (IOException e) { throw new ResourceException("Problems getting resource named \"" + name + "\"!", e); } }
protected String removeNamePrefix(String name) throws ResourceException { if (namePrefix == null) { generateNamePrefixOnce(); } if (name.startsWith(namePrefix)) {//usualy name has text return name.substring(namePrefix.length()); } return name; }
protected void generateNamePrefixOnce () { URI uri = null; String realPath = servletContext.getRealPath("/"); if (realPath != null) { uri = new File(realPath).toURI();}//prevent NPE if in .war try { URL res = servletContext.getResource("/"); if (res != null) { uri = res.toURI(); } } catch (MalformedURLException ignore) { } catch (URISyntaxException ignore) { } if (uri != null) { try { namePrefix = uri.toURL().toExternalForm(); return; } catch (MalformedURLException e) { log("generateNamePrefixOnce [ERROR] Malformed URL for base path / == '"+ uri +'\'', e); } } namePrefix = ""; }
Template template = findCachedTemplate(key, file); template = createAndStoreTemplate(key, new FileInputStream(file), file); } catch (Exception e) { throw new ServletException("Creation of template failed: " + e, e);