Search in sources :

Example 1 with Template

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]");
    }
}
Also used : File(java.io.File) URL(java.net.URL) Writer(java.io.Writer) Template(groovy.text.Template)

Example 2 with Template

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

Example 3 with 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);
}
Also used : GroovyPageScriptSource(org.grails.gsp.io.GroovyPageScriptSource) GroovyObject(groovy.lang.GroovyObject) CacheEntry(grails.util.CacheEntry) GrailsTagException(org.grails.taglib.GrailsTagException) IOException(java.io.IOException) Template(groovy.text.Template)

Example 4 with Template

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;
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) Template(groovy.text.Template)

Example 5 with Template

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;
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) 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