Search in sources :

Example 11 with Template

use of groovy.text.Template in project sling by apache.

the class GSPScriptEngine method eval.

public Object eval(Reader reader, ScriptContext ctx) throws ScriptException {
    Template template = null;
    try {
        template = templateEngine.createTemplate(reader);
    } catch (IOException e) {
        throw new ScriptException("Unable to compile GSP script: " + e.getMessage());
    } catch (ClassNotFoundException e) {
        throw new ScriptException("Unable to compile GSP script: " + e.getMessage());
    }
    Bindings bindings = ctx.getBindings(ScriptContext.ENGINE_SCOPE);
    Writable result = template.make(bindings);
    try {
        result.writeTo(ctx.getWriter());
    } catch (IOException e) {
        throw new ScriptException("Unable to write result of script execution: " + e.getMessage());
    }
    return null;
}
Also used : ScriptException(javax.script.ScriptException) Writable(groovy.lang.Writable) IOException(java.io.IOException) Bindings(javax.script.Bindings) Template(groovy.text.Template)

Example 12 with Template

use of groovy.text.Template in project gradle by gradle.

the class SimpleTemplateOperation method generate.

@Override
public void generate() {
    try {
        target.getParentFile().mkdirs();
        SimpleTemplateEngine templateEngine = new SimpleTemplateEngine();
        String templateText = Resources.asCharSource(templateURL, CharsetToolkit.getDefaultSystemCharset()).read();
        Template template = templateEngine.createTemplate(templateText);
        Writer writer = Files.asCharSink(target, Charsets.UTF_8).openStream();
        try {
            template.make(bindings).writeTo(writer);
        } finally {
            writer.close();
        }
    } catch (Exception ex) {
        throw new GradleException("Could not generate file " + target + ".", ex);
    }
}
Also used : GradleException(org.gradle.api.GradleException) Writer(java.io.Writer) GradleException(org.gradle.api.GradleException) SimpleTemplateEngine(groovy.text.SimpleTemplateEngine) Template(groovy.text.Template)

Example 13 with Template

use of groovy.text.Template in project cuba by cuba-platform.

the class UserManagementServiceBean method changePasswordsAtLogonAndSendEmails.

@Override
public Integer changePasswordsAtLogonAndSendEmails(List<UUID> userIds) {
    checkNotNullArgument(userIds, "Null users list");
    checkUpdatePermission(User.class);
    if (userIds.isEmpty())
        return 0;
    Map<User, String> modifiedUsers = updateUserPasswords(userIds, true);
    // email templates
    String resetPasswordBodyTemplate = serverConfig.getResetPasswordEmailBodyTemplate();
    String resetPasswordSubjectTemplate = serverConfig.getResetPasswordEmailSubjectTemplate();
    SimpleTemplateEngine templateEngine = new SimpleTemplateEngine(scripting.getClassLoader());
    Map<String, Template> localizedBodyTemplates = new HashMap<>();
    Map<String, Template> localizedSubjectTemplates = new HashMap<>();
    // load default
    Template bodyDefaultTemplate = loadDefaultTemplate(resetPasswordBodyTemplate, templateEngine);
    Template subjectDefaultTemplate = loadDefaultTemplate(resetPasswordSubjectTemplate, templateEngine);
    for (Map.Entry<User, String> userPasswordEntry : modifiedUsers.entrySet()) {
        User user = userPasswordEntry.getKey();
        if (StringUtils.isNotEmpty(user.getEmail())) {
            EmailTemplate template = getResetPasswordTemplate(user, templateEngine, resetPasswordSubjectTemplate, resetPasswordBodyTemplate, subjectDefaultTemplate, bodyDefaultTemplate, localizedSubjectTemplates, localizedBodyTemplates);
            String password = userPasswordEntry.getValue();
            sendResetPasswordEmail(user, password, template.getSubjectTemplate(), template.getBodyTemplate());
        }
    }
    return modifiedUsers.size();
}
Also used : SimpleTemplateEngine(groovy.text.SimpleTemplateEngine) Template(groovy.text.Template)

Example 14 with Template

use of groovy.text.Template in project cuba by cuba-platform.

the class CubaApplicationServlet method prepareErrorHtml.

protected String prepareErrorHtml(HttpServletRequest req, Throwable exception) {
    Messages messages = AppBeans.get(Messages.NAME);
    Configuration configuration = AppBeans.get(Configuration.NAME);
    WebConfig webConfig = configuration.getConfig(WebConfig.class);
    GlobalConfig globalConfig = configuration.getConfig(GlobalConfig.class);
    // SimpleTemplateEngine requires mutable map
    Map<String, Object> binding = new HashMap<>();
    binding.put("tryAgainUrl", "?restartApp");
    binding.put("productionMode", webConfig.getProductionMode());
    binding.put("messages", messages);
    binding.put("exception", exception);
    binding.put("exceptionName", exception.getClass().getName());
    binding.put("exceptionMessage", exception.getMessage());
    binding.put("exceptionStackTrace", ExceptionUtils.getStackTrace(exception));
    Locale locale = resolveLocale(req, messages, globalConfig);
    String serverErrorPageTemplatePath = webConfig.getServerErrorPageTemplate();
    String localeString = messages.getTools().localeToString(locale);
    String templateContent = getLocalizedTemplateContent(resources, serverErrorPageTemplatePath, localeString);
    if (templateContent == null) {
        templateContent = resources.getResourceAsString(serverErrorPageTemplatePath);
        if (templateContent == null) {
            throw new IllegalStateException("Unable to find server error page template " + serverErrorPageTemplatePath);
        }
    }
    SimpleTemplateEngine templateEngine = new SimpleTemplateEngine(getServletContext().getClassLoader());
    Template template = getTemplate(templateEngine, templateContent);
    Writable writable = template.make(binding);
    String html;
    try {
        html = writable.writeTo(new StringWriter()).toString();
    } catch (IOException e) {
        throw new RuntimeException("Unable to write server error page", e);
    }
    return html;
}
Also used : WebConfig(com.haulmont.cuba.web.WebConfig) Writable(groovy.lang.Writable) Template(groovy.text.Template) SimpleTemplateEngine(groovy.text.SimpleTemplateEngine)

Example 15 with Template

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

the class DefaultTemplateVisitor method doPlainOutput.

public void doPlainOutput(String templateResult, VisitorContext context) throws Exception {
    WriterConfig writerConfig = context.getArchitectureConfig().getWriterConfig();
    ChainWriter chainWriter = writerConfig.getModelWriter();
    if (output == null) {
        String fileName = currentTemplate.getName();
        if (context.containsKey(AbstractWalker.ORIGINAL_FILE_KEY)) {
            log.debug("Original file path found");
            File originalFile = (File) context.get(AbstractWalker.ORIGINAL_FILE_KEY);
            String fullPath = originalFile.getPath();
            String readerPath = context.getArchitectureConfig().getReaderConfig().getPath();
            fileName = fullPath.substring(readerPath.length());
            if (fileName.startsWith(File.separator)) {
                fileName = fileName.substring(1);
            }
        } else {
            log.debug("working with the template name");
        }
        int pos = fileName.lastIndexOf(".");
        if (pos != -1) {
            log.debug("Removing the existing suffix");
            fileName = fileName.substring(0, pos);
        }
        log.warn("Setting a default output file! [" + fileName + ".result]");
        VisitorContext auxCtxt = new VisitorContext();
        File defaultOutputFile = new File(writerConfig.getPath(), fileName + "." + suffix);
        if (!defaultOutputFile.exists()) {
            log.info("++" + defaultOutputFile.getAbsolutePath());
            defaultOutputFile.getParentFile().mkdirs();
            defaultOutputFile.createNewFile();
        }
        auxCtxt.put(AbstractWalker.ORIGINAL_FILE_KEY, defaultOutputFile);
        chainWriter.write(templateResult, auxCtxt);
    } else {
        String outputFile = output;
        // validates if it is a template name to reduce
        // computation
        char[] chars = outputFile.toCharArray();
        boolean isGString = false;
        for (int i = 0; i < chars.length && !isGString; i++) {
            isGString = chars[i] == '$' || chars[i] == '<';
        }
        if (isGString) {
            GStringTemplateEngine engine = new GStringTemplateEngine();
            Template templateName = engine.createTemplate(output);
            StringWriter stringWriter = new StringWriter();
            Writer platformWriter = new PlatformLineWriter(stringWriter);
            templateName.make(context).writeTo(platformWriter);
            outputFile = platformWriter.toString();
        }
        File file = new File(outputFile);
        VisitorContext auxCtxt = new VisitorContext();
        auxCtxt.put(AbstractWalker.ORIGINAL_FILE_KEY, file);
        auxCtxt.put("append", Boolean.TRUE);
        if (!file.exists()) {
            log.info("++" + file.getAbsolutePath());
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        chainWriter.write(templateResult, auxCtxt);
    }
}
Also used : ChainWriter(org.walkmod.ChainWriter) VisitorContext(org.walkmod.walkers.VisitorContext) PlatformLineWriter(groovy.io.PlatformLineWriter) GStringTemplateEngine(groovy.text.GStringTemplateEngine) WriterConfig(org.walkmod.conf.entities.WriterConfig) Template(groovy.text.Template) StringWriter(java.io.StringWriter) File(java.io.File) StringWriter(java.io.StringWriter) PlatformLineWriter(groovy.io.PlatformLineWriter) Writer(java.io.Writer) ChainWriter(org.walkmod.ChainWriter)

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