use of groovy.text.Template in project groovy by apache.
the class TemplateServlet method service.
/**
* Services the request with a response.
* <p>
* First the request is parsed for the source file uri. If the specified file
* could not be found or can not be read an error message is sent as response.
*
* @param request The http request.
* @param response The http response.
* @throws IOException if an input or output error occurs while the servlet is handling the HTTP request
* @throws ServletException if the HTTP request cannot be handled
*/
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (verbose) {
log("Creating/getting cached template...");
}
//
// Get the template source file handle.
//
Template template;
long getMillis;
String name;
File file = getScriptUriAsFile(request);
if (file != null) {
name = file.getName();
if (!file.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
// throw new IOException(file.getAbsolutePath());
return;
}
if (!file.canRead()) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Can not read \"" + name + "\"!");
// throw new IOException(file.getAbsolutePath());
return;
}
getMillis = System.currentTimeMillis();
template = getTemplate(file);
getMillis = System.currentTimeMillis() - getMillis;
} else {
name = getScriptUri(request);
URL url = servletContext.getResource(name);
getMillis = System.currentTimeMillis();
template = getTemplate(url);
getMillis = System.currentTimeMillis() - getMillis;
}
//
// Create new binding for the current request.
//
ServletBinding binding = new ServletBinding(request, response, servletContext);
setVariables(binding);
//
// Prepare the response buffer content type _before_ getting the writer.
// and set status code to ok
//
response.setContentType(CONTENT_TYPE_TEXT_HTML + "; charset=" + encoding);
response.setStatus(HttpServletResponse.SC_OK);
//
// Get the output stream writer from the binding.
//
Writer out = (Writer) binding.getVariable("out");
if (out == null) {
out = response.getWriter();
}
//
if (verbose) {
log("Making template \"" + name + "\"...");
}
// String made = template.make(binding.getVariables()).toString();
// log(" = " + made);
long makeMillis = System.currentTimeMillis();
template.make(binding.getVariables()).writeTo(out);
makeMillis = System.currentTimeMillis() - makeMillis;
if (generateBy) {
StringBuilder sb = new StringBuilder(100);
sb.append("\n<!-- Generated by Groovy TemplateServlet [create/get=");
sb.append(Long.toString(getMillis));
sb.append(" ms, make=");
sb.append(Long.toString(makeMillis));
sb.append(" ms] -->\n");
out.write(sb.toString());
}
//
// flush the response buffer.
//
response.flushBuffer();
if (verbose) {
log("Template \"" + name + "\" request responded. [create/get=" + getMillis + " ms, make=" + makeMillis + " ms]");
}
}
use of groovy.text.Template in project groovy by apache.
the class TemplateServlet method getTemplate.
/**
* 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 file. If the source file didn't change in
* length and its last modified stamp hasn't changed compared to a precompiled
* template object, this template is used. Otherwise, there is no or an
* invalid template object 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 file The file containing the template source.
* @throws ServletException If the request specified an invalid template source file
*/
protected Template getTemplate(File file) throws ServletException {
String key = file.getAbsolutePath();
Template template = findCachedTemplate(key, file);
//
if (template == null) {
try {
template = createAndStoreTemplate(key, new FileInputStream(file), file);
} catch (Exception e) {
throw new ServletException("Creation of template failed: " + e, e);
}
}
return template;
}
use of groovy.text.Template in project grails-core by grails.
the class GroovyPagesTemplateRenderer method findAndCacheTemplate.
private Template findAndCacheTemplate(Object controller, TemplateVariableBinding pageScope, String templateName, String contextPath, String pluginName, final String uri) throws IOException {
String templatePath = GrailsStringUtils.isNotEmpty(contextPath) ? GrailsResourceUtils.appendPiecesForUri(contextPath, templateName) : templateName;
final GroovyPageScriptSource scriptSource;
if (pluginName == null) {
scriptSource = groovyPageLocator.findTemplateInBinding(controller, templatePath, pageScope);
} else {
scriptSource = groovyPageLocator.findTemplateInBinding(controller, pluginName, templatePath, pageScope);
}
String cacheKey;
if (scriptSource == null) {
cacheKey = contextPath + pluginName + uri;
} else {
if (pluginName != null) {
cacheKey = contextPath + pluginName + scriptSource.getURI();
} else {
cacheKey = scriptSource.getURI();
}
}
return CacheEntry.getValue(templateCache, cacheKey, reloadEnabled ? GroovyPageMetaInfo.LASTMODIFIED_CHECK_INTERVAL : -1, null, new Callable<CacheEntry<Template>>() {
public CacheEntry<Template> call() {
return new CacheEntry<Template>() {
boolean allowCaching = cacheEnabled;
boolean neverExpire = false;
@Override
protected boolean hasExpired(long timeout, Object cacheRequestObject) {
return neverExpire ? false : (allowCaching ? super.hasExpired(timeout, cacheRequestObject) : true);
}
@Override
public boolean isInitialized() {
return allowCaching ? super.isInitialized() : false;
}
@Override
public void setValue(Template val) {
if (allowCaching) {
super.setValue(val);
}
}
@Override
protected Template updateValue(Template oldValue, Callable<Template> updater, Object cacheRequestObject) throws Exception {
Template t = null;
if (scriptSource != null) {
t = groovyPagesTemplateEngine.createTemplate(scriptSource);
}
if (t == null && scaffoldingTemplateGenerator != null) {
t = generateScaffoldedTemplate(GrailsWebRequest.lookup(), uri);
// always enable caching for generated
// scaffolded template
allowCaching = true;
// never expire scaffolded entry since scaffolding plugin flushes the whole cache on any change
neverExpire = true;
}
return t;
}
};
}
}, true, null);
}
use of groovy.text.Template in project groovy by apache.
the class GroovyDocTemplateEngine method applyClassTemplates.
String applyClassTemplates(GroovyClassDoc classDoc) {
// todo (iterate)
String templatePath = classTemplatePaths.get(0);
String templateWithBindingApplied = "";
try {
Template t = classTemplates.get(templatePath);
if (t == null) {
t = engine.createTemplate(resourceManager.getReader(templatePath));
classTemplates.put(templatePath, t);
}
Map<String, Object> binding = new HashMap<String, Object>();
binding.put("classDoc", classDoc);
binding.put("props", properties);
templateWithBindingApplied = t.make(binding).toString();
} catch (Exception e) {
System.out.println("Error processing class template for: " + classDoc.getFullPathName());
e.printStackTrace();
}
return templateWithBindingApplied;
}
use of groovy.text.Template in project groovy by apache.
the class GroovyDocTemplateEngine method applyPackageTemplate.
String applyPackageTemplate(String template, GroovyPackageDoc packageDoc) {
String templateWithBindingApplied = "";
try {
Template t = packageTemplates.get(template);
if (t == null) {
t = engine.createTemplate(resourceManager.getReader(template));
packageTemplates.put(template, t);
}
Map<String, Object> binding = new HashMap<String, Object>();
binding.put("packageDoc", packageDoc);
binding.put("props", properties);
templateWithBindingApplied = t.make(binding).toString();
} catch (Exception e) {
System.out.println("Error processing package template for: " + packageDoc.name());
e.printStackTrace();
}
return templateWithBindingApplied;
}
Aggregations