Search in sources :

Example 16 with Template

use of groovy.text.Template in project groovy-core by groovy.

the class BaseTemplate method fragment.

/**
 * Renders an embedded template as a fragment. Fragments are cached in a template, meaning that
 * if you use the same fragment in a template, it will only be compiled once, but once <b>per template
 * instance</b>. This is less performant than using {@link #layout(java.util.Map, String)}.
 *
 * @param model model to be passed to the template
 * @param templateText template body
 * @return this template instance
 * @throws IOException
 * @throws ClassNotFoundException
 */
public Object fragment(Map model, String templateText) throws IOException, ClassNotFoundException {
    Template template = cachedFragments.get(templateText);
    if (template == null) {
        template = engine.createTemplate(new StringReader(templateText));
        cachedFragments.put(templateText, template);
    }
    template.make(model).writeTo(out);
    return this;
}
Also used : StringReader(java.io.StringReader) Template(groovy.text.Template)

Example 17 with Template

use of groovy.text.Template in project groovy-core by groovy.

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;
}
Also used : ServletException(javax.servlet.ServletException) FileInputStream(java.io.FileInputStream) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) Template(groovy.text.Template)

Example 18 with Template

use of groovy.text.Template in project groovy-core by groovy.

the class TemplateServlet method createAndStoreTemplate.

/**
 * Compile the template and store it in the cache.
 * @param key a unique key for the template, such as a file's absolutePath or a URL.
 * @param reader a reader for the template's source.
 * @param file a file to be used to determine if the cached template is stale. May be null.
 * @return the created template.
 * @throws Exception Any exception when creating the template.
 */
private Template createAndStoreTemplate(String key, InputStream inputStream, File file) throws Exception {
    if (verbose) {
        log("Creating new template from " + key + "...");
    }
    Reader reader = null;
    try {
        String fileEncoding = (fileEncodingParamVal != null) ? fileEncodingParamVal : System.getProperty(GROOVY_SOURCE_ENCODING);
        reader = fileEncoding == null ? new InputStreamReader(inputStream) : new InputStreamReader(inputStream, fileEncoding);
        Template template = engine.createTemplate(reader);
        cache.put(key, new TemplateCacheEntry(file, template, verbose));
        if (verbose) {
            log("Created and added template to cache. [key=" + key + "] " + cache.get(key));
        }
        // 
        if (template == null) {
            throw new ServletException("Template is null? Should not happen here!");
        }
        return template;
    } finally {
        if (reader != null) {
            reader.close();
        } else if (inputStream != null) {
            inputStream.close();
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) InputStreamReader(java.io.InputStreamReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) Template(groovy.text.Template)

Example 19 with Template

use of groovy.text.Template in project groovy-core by groovy.

the class TemplateServlet method findCachedTemplate.

/**
 * Find a cached template for a given key. If a <code>File</code> is passed then
 * any cached object is validated against the File to determine if it is out of
 * date
 * @param key a unique key for the template, such as a file's absolutePath or a URL.
 * @param file a file to be used to determine if the cached template is stale. May be null.
 * @return The cached template, or null if there was no cached entry, or the entry was stale.
 */
private Template findCachedTemplate(String key, File file) {
    Template template = null;
    /*
         * Test cache for a valid template bound to the key.
         */
    if (verbose) {
        log("Looking for cached template by key \"" + key + "\"");
    }
    TemplateCacheEntry entry = (TemplateCacheEntry) cache.get(key);
    if (entry != null) {
        if (entry.validate(file)) {
            if (verbose) {
                log("Cache hit! " + entry);
            }
            template = entry.template;
        } else {
            if (verbose) {
                log("Cached template " + key + " needs recompiliation! " + entry);
            }
        }
    } else {
        if (verbose) {
            log("Cache miss for " + key);
        }
    }
    return template;
}
Also used : Template(groovy.text.Template)

Example 20 with Template

use of groovy.text.Template in project indy by Commonjava.

the class TemplatingEngine method getTemplate.

// TODO Cache these...though this will hurt hot-reloading. Perhaps a debug mode configuration?
private Template getTemplate(final String acceptHeader, final String templateKey) throws IndyGroovyException {
    final String accept = (acceptHeader == null ? "" : acceptHeader.replace('/', '_') + "/");
    try {
        final String filename = accept + templateKey + ".groovy";
        final DataFile templateFile = manager.getDataFile(TEMPLATES, filename);
        logger.info("Looking for template: {} for ACCEPT header: {} in: {}", templateKey, acceptHeader, templateFile);
        Template template;
        if (templateFile.exists() && !templateFile.isDirectory()) {
            template = engine.createTemplate(templateFile.readString());
        } else {
            final String urlpath = TEMPLATES + "/" + accept + templateKey + ".groovy";
            logger.info("Looking for template: {} for ACCEPT header: {} in: {}", templateKey, acceptHeader, urlpath);
            final URL u = Thread.currentThread().getContextClassLoader().getResource(urlpath);
            template = u == null ? null : engine.createTemplate(u);
        }
        if (template == null) {
            throw new IndyGroovyException("Failed to locate template: %s (with ACCEPT header: %s)", templateKey, acceptHeader);
        }
        return template;
    } catch (final CompilationFailedException e) {
        throw new IndyGroovyException("Failed to compile template: %s. Reason: %s", e, templateKey, e.getMessage());
    } catch (final ClassNotFoundException e) {
        throw new IndyGroovyException("Failed to compile template: %s. Reason: %s", e, templateKey, e.getMessage());
    } catch (final IOException e) {
        throw new IndyGroovyException("Failed to read template: %s. Reason: %s", e, templateKey, e.getMessage());
    }
}
Also used : DataFile(org.commonjava.indy.subsys.datafile.DataFile) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) IOException(java.io.IOException) URL(java.net.URL) Template(groovy.text.Template)

Aggregations

Template (groovy.text.Template)41 IOException (java.io.IOException)19 HashMap (java.util.HashMap)7 ServletException (javax.servlet.ServletException)7 Writable (groovy.lang.Writable)6 SimpleTemplateEngine (groovy.text.SimpleTemplateEngine)6 Writer (java.io.Writer)6 File (java.io.File)5 StringWriter (java.io.StringWriter)3 URL (java.net.URL)3 GroovyObject (groovy.lang.GroovyObject)2 FileInputStream (java.io.FileInputStream)2 InputStreamReader (java.io.InputStreamReader)2 OutputStreamWriter (java.io.OutputStreamWriter)2 Reader (java.io.Reader)2 StringReader (java.io.StringReader)2 GrailsTagException (org.grails.taglib.GrailsTagException)2 Test (org.junit.Test)2 WebConfig (com.haulmont.cuba.web.WebConfig)1 TestExplanation1 (eu.esdihumboldt.hale.common.align.model.impl.mdexpl.test.TestExplanation1)1