Java Code Examples for groovy.text.Template

The following examples show how to use groovy.text.Template. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: pushfish-android   Author: PushFish   File: FilterChain.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void expand(final Map<String, ?> properties) {
    transformers.add(new Transformer<Reader, Reader>() {
        public Reader transform(Reader original) {
            try {
                Template template;
                try {
                    SimpleTemplateEngine engine = new SimpleTemplateEngine();
                    template = engine.createTemplate(original);
                } finally {
                    original.close();
                }
                StringWriter writer = new StringWriter();
                template.make(properties).writeTo(writer);
                return new StringReader(writer.toString());
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    });
}
 
Example #2
Source Project: pushfish-android   Author: PushFish   File: FilterChain.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void expand(final Map<String, ?> properties) {
    transformers.add(new Transformer<Reader, Reader>() {
        public Reader transform(Reader original) {
            try {
                Template template;
                try {
                    SimpleTemplateEngine engine = new SimpleTemplateEngine();
                    template = engine.createTemplate(original);
                } finally {
                    original.close();
                }
                StringWriter writer = new StringWriter();
                template.make(properties).writeTo(writer);
                return new StringReader(writer.toString());
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    });
}
 
Example #3
Source Project: cuba   Author: cuba-platform   File: UserManagementServiceBean.java    License: Apache License 2.0 6 votes vote down vote up
protected void sendResetPasswordEmail(User user, String password, Template subjectTemplate, Template bodyTemplate) {
    String emailBody;
    String emailSubject;
    try (Transaction tx = persistence.createTransaction()) {
        Map<String, Object> binding = new HashMap<>();
        binding.put("user", user);
        binding.put("password", password);
        binding.put("persistence", persistence);

        emailBody = bodyTemplate.make(binding).writeTo(new StringWriter(0)).toString();
        emailSubject = subjectTemplate.make(binding).writeTo(new StringWriter(0)).toString();

        tx.commit();
    } catch (IOException e) {
        throw new RuntimeException("Unable to write Groovy template content", e);
    }

    EmailInfo emailInfo = EmailInfoBuilder.create()
            .setAddresses(user.getEmail())
            .setCaption(emailSubject)
            .setBody(emailBody)
            .build();
    emailerAPI.sendEmailAsync(emailInfo);
}
 
Example #4
Source Project: groovy   Author: apache   File: GroovyDocTemplateEngine.java    License: Apache License 2.0 6 votes vote down vote up
public GroovyDocTemplateEngine(GroovyDocTool tool, ResourceManager resourceManager,
                               String[] docTemplates,
                               String[] packageTemplates,
                               String[] classTemplates,
                               Properties properties) {
    this.resourceManager = resourceManager;
    this.properties = properties;
    this.docTemplatePaths = Arrays.asList(docTemplates);
    this.packageTemplatePaths = Arrays.asList(packageTemplates);
    this.classTemplatePaths = Arrays.asList(classTemplates);
    this.docTemplates = new LinkedHashMap<String, Template>();
    this.packageTemplates = new LinkedHashMap<String, Template>();
    this.classTemplates = new LinkedHashMap<String, Template>();
    engine = new GStringTemplateEngine();

}
 
Example #5
Source Project: groovy   Author: apache   File: GroovyDocTemplateEngine.java    License: Apache License 2.0 6 votes vote down vote up
String applyClassTemplates(GroovyClassDoc classDoc) {
    String templatePath = classTemplatePaths.get(0); // todo (iterate)
    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 LinkedHashMap<String, Object>();
        binding.put("classDoc", classDoc);
        binding.put("props", properties);
        templateWithBindingApplied = t.make(binding).writeTo(reasonableSizeWriter()).toString();
    } catch (Exception e) {
        System.out.println("Error processing class template for: " + classDoc.getFullPathName());
        e.printStackTrace();
    }
    return templateWithBindingApplied;
}
 
Example #6
Source Project: groovy   Author: apache   File: GroovyDocTemplateEngine.java    License: Apache License 2.0 6 votes vote down vote up
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 LinkedHashMap<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;
}
 
Example #7
Source Project: groovy   Author: apache   File: GroovyDocTemplateEngine.java    License: Apache License 2.0 6 votes vote down vote up
String applyRootDocTemplate(String template, GroovyRootDoc rootDoc) {
    String templateWithBindingApplied = "";
    try {
        Template t = docTemplates.get(template);
        if (t == null) {
            t = engine.createTemplate(resourceManager.getReader(template));
            docTemplates.put(template, t);
        }
        Map<String, Object> binding = new LinkedHashMap<String, Object>();
        binding.put("rootDoc", rootDoc);
        binding.put("props", properties);
        templateWithBindingApplied = t.make(binding).toString();
    } catch (Exception e) {
        System.out.println("Error processing root doc template");
        e.printStackTrace();
    }
    return templateWithBindingApplied;
}
 
Example #8
Source Project: groovy   Author: apache   File: TemplateServlet.java    License: Apache License 2.0 6 votes vote down vote up
public TemplateCacheEntry(File file, Template template, boolean timestamp) {
    if (template == null) {
        throw new NullPointerException("template");
    }
    if (timestamp) {
        this.date = new Date(System.currentTimeMillis());
    } else {
        this.date = null;
    }
    this.hit = 0;
    if (file != null) {
        this.lastModified = file.lastModified();
        this.length = file.length();
    }
    this.template = template;
}
 
Example #9
Source Project: groovy   Author: apache   File: TemplateServlet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);

    //
    // Template not cached or the source file changed - compile new template!
    //
    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;
}
 
Example #10
Source Project: groovy   Author: apache   File: TemplateServlet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source Project: Pushjet-Android   Author: Pushjet   File: FilterChain.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void expand(final Map<String, ?> properties) {
    transformers.add(new Transformer<Reader, Reader>() {
        public Reader transform(Reader original) {
            try {
                Template template;
                try {
                    SimpleTemplateEngine engine = new SimpleTemplateEngine();
                    template = engine.createTemplate(original);
                } finally {
                    original.close();
                }
                StringWriter writer = new StringWriter();
                template.make(properties).writeTo(writer);
                return new StringReader(writer.toString());
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    });
}
 
Example #12
Source Project: Pushjet-Android   Author: Pushjet   File: FilterChain.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void expand(final Map<String, ?> properties) {
    transformers.add(new Transformer<Reader, Reader>() {
        public Reader transform(Reader original) {
            try {
                Template template;
                try {
                    SimpleTemplateEngine engine = new SimpleTemplateEngine();
                    template = engine.createTemplate(original);
                } finally {
                    original.close();
                }
                StringWriter writer = new StringWriter();
                template.make(properties).writeTo(writer);
                return new StringReader(writer.toString());
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    });
}
 
Example #13
Source Project: spring-analysis-note   Author: Vip-Augus   File: GroovyMarkupView.java    License: MIT License 5 votes vote down vote up
@Override
protected void renderMergedTemplateModel(Map<String, Object> model,
		HttpServletRequest request, HttpServletResponse response) throws Exception {

	String url = getUrl();
	Assert.state(url != null, "'url' not set");

	Template template = getTemplate(url);
	template.make(model).writeTo(new BufferedWriter(response.getWriter()));
}
 
Example #14
Source Project: spring-analysis-note   Author: Vip-Augus   File: GroovyMarkupView.java    License: MIT License 5 votes vote down vote up
/**
 * Return a template compiled by the configured Groovy Markup template engine
 * for the given view URL.
 */
protected Template getTemplate(String viewUrl) throws Exception {
	Assert.state(this.engine != null, "No MarkupTemplateEngine set");
	try {
		return this.engine.createTemplateByPath(viewUrl);
	}
	catch (ClassNotFoundException ex) {
		Throwable cause = (ex.getCause() != null ? ex.getCause() : ex);
		throw new NestedServletException(
				"Could not find class while rendering Groovy Markup view with name '" +
				getUrl() + "': " + ex.getMessage() + "'", cause);
	}
}
 
Example #15
Source Project: java-technology-stack   Author: codeEngraver   File: GroovyMarkupView.java    License: MIT License 5 votes vote down vote up
@Override
protected void renderMergedTemplateModel(Map<String, Object> model,
		HttpServletRequest request, HttpServletResponse response) throws Exception {

	String url = getUrl();
	Assert.state(url != null, "'url' not set");

	Template template = getTemplate(url);
	template.make(model).writeTo(new BufferedWriter(response.getWriter()));
}
 
Example #16
Source Project: java-technology-stack   Author: codeEngraver   File: GroovyMarkupView.java    License: MIT License 5 votes vote down vote up
/**
 * Return a template compiled by the configured Groovy Markup template engine
 * for the given view URL.
 */
protected Template getTemplate(String viewUrl) throws Exception {
	Assert.state(this.engine != null, "No MarkupTemplateEngine set");
	try {
		return this.engine.createTemplateByPath(viewUrl);
	}
	catch (ClassNotFoundException ex) {
		Throwable cause = (ex.getCause() != null ? ex.getCause() : ex);
		throw new NestedServletException(
				"Could not find class while rendering Groovy Markup view with name '" +
				getUrl() + "': " + ex.getMessage() + "'", cause);
	}
}
 
Example #17
Source Project: lams   Author: lamsfoundation   File: GroovyMarkupView.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void renderMergedTemplateModel(Map<String, Object> model,
		HttpServletRequest request, HttpServletResponse response) throws Exception {

	Template template = getTemplate(getUrl());
	template.make(model).writeTo(new BufferedWriter(response.getWriter()));
}
 
Example #18
Source Project: lams   Author: lamsfoundation   File: GroovyMarkupView.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return a template compiled by the configured Groovy Markup template engine
 * for the given view URL.
 */
protected Template getTemplate(String viewUrl) throws Exception {
	try {
		return this.engine.createTemplateByPath(viewUrl);
	}
	catch (ClassNotFoundException ex) {
		Throwable cause = (ex.getCause() != null ? ex.getCause() : ex);
		throw new NestedServletException(
				"Could not find class while rendering Groovy Markup view with name '" +
				getUrl() + "': " + ex.getMessage() + "'", cause);
	}
}
 
Example #19
Source Project: jira-groovioli   Author: AndreyVMarkelov   File: ScriptTemplateManagerImpl.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public String renderTemplate(String groovyTemplate, Map<String, Object> parameters) throws TemplateException {
    try (StringWriter stringWriter = new StringWriter()) {
        Template template = templateCache.get(groovyTemplate);
        template.make(fromMap(parameters)).writeTo(stringWriter);
        return stringWriter.toString();
    } catch (Exception ex) {
        throw new TemplateException("Error executing groovy template", ex);
    }
}
 
Example #20
Source Project: spring4-understanding   Author: langtianya   File: GroovyMarkupView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void renderMergedTemplateModel(Map<String, Object> model,
		HttpServletRequest request, HttpServletResponse response) throws Exception {

	Template template = getTemplate(getUrl());
	template.make(model).writeTo(new BufferedWriter(response.getWriter()));
}
 
Example #21
Source Project: spring4-understanding   Author: langtianya   File: GroovyMarkupView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return a template compiled by the configured Groovy Markup template engine
 * for the given view URL.
 */
protected Template getTemplate(String viewUrl) throws Exception {
	try {
		return this.engine.createTemplateByPath(viewUrl);
	}
	catch (ClassNotFoundException ex) {
		Throwable cause = (ex.getCause() != null ? ex.getCause() : ex);
		throw new NestedServletException("Could not find class while rendering Groovy Markup view with name '" +
				getUrl() + "': " + ex.getMessage() +  "'", cause);
	}
}
 
Example #22
Source Project: ozark   Author: mvc-spec   File: GroovyViewEngine.java    License: Apache License 2.0 5 votes vote down vote up
public void processView(ViewEngineContext context) throws ViewEngineException {

        Map<String, Object> model = new HashMap<>(context.getModels().asMap());
        model.put("request", context.getRequest(HttpServletRequest.class));
        Charset charset = resolveCharsetAndSetContentType(context);
        try (Writer writer = new OutputStreamWriter(context.getOutputStream(), charset);
            InputStream resourceAsStream = servletContext.getResourceAsStream(resolveView(context));
            InputStreamReader in = new InputStreamReader(resourceAsStream, "UTF-8");) {
            Template template = markupTemplateEngine.createTemplate(in);
            Writable output = template.make(model);
            output.writeTo(writer);
        } catch (IOException | CompilationFailedException | ClassNotFoundException e) {
            throw new ViewEngineException(e);
        }
    }
 
Example #23
Source Project: cuba   Author: cuba-platform   File: CubaApplicationServlet.java    License: Apache License 2.0 5 votes vote down vote up
protected Template getTemplate(SimpleTemplateEngine templateEngine, String templateString) {
    Template bodyTemplate;
    try {
        bodyTemplate = templateEngine.createTemplate(templateString);
    } catch (Exception e) {
        throw new RuntimeException("Unable to compile Groovy template", e);
    }
    return bodyTemplate;
}
 
Example #24
Source Project: cuba   Author: cuba-platform   File: UserManagementServiceBean.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #25
Source Project: cuba   Author: cuba-platform   File: UserManagementServiceBean.java    License: Apache License 2.0 5 votes vote down vote up
protected Template getTemplate(SimpleTemplateEngine templateEngine, String templateString) {
    Template bodyTemplate;
    try {
        bodyTemplate = templateEngine.createTemplate(templateString);
    } catch (Exception e) {
        throw new RuntimeException("Unable to compile Groovy template", e);
    }
    return bodyTemplate;
}
 
Example #26
Source Project: cuba   Author: cuba-platform   File: UserManagementServiceBean.java    License: Apache License 2.0 5 votes vote down vote up
protected Template loadDefaultTemplate(String templatePath, SimpleTemplateEngine templateEngine) {
    String defaultTemplateContent = resources.getResourceAsString(templatePath);
    if (defaultTemplateContent == null) {
        throw new IllegalStateException("Not found default email template for reset passwords operation");
    }

    //noinspection UnnecessaryLocalVariable
    Template template = getTemplate(templateEngine, defaultTemplateContent);
    return template;
}
 
Example #27
Source Project: groovy   Author: apache   File: BaseTemplate.java    License: Apache License 2.0 5 votes vote down vote up
public BaseTemplate(final MarkupTemplateEngine templateEngine, final Map model, final Map<String,String> modelTypes, final TemplateConfiguration configuration) {
    this.model = model==null?EMPTY_MODEL:model;
    this.engine = templateEngine;
    this.configuration = configuration;
    this.modelTypes = modelTypes;
    this.cachedFragments = new LinkedHashMap<String, Template>();
}
 
Example #28
Source Project: groovy   Author: apache   File: TemplateServlet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 recompilation! " + entry);
            }
        }
    } else {
        if (verbose) {
            log("Cache miss for " + key);
        }
    }

    return template;
}
 
Example #29
Source Project: groovy   Author: apache   File: TemplateServlet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 inputStream an InputStream 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));
        }

        //
        // Last sanity check.
        //
        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();
        }
    }
}
 
Example #30
Source Project: pippo   Author: pippo-java   File: GroovyTemplateEngine.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void renderString(String templateContent, Map<String, Object> model, Writer writer) {
    try {
        Template groovyTemplate = engine.createTemplate(templateContent);
        PippoGroovyTemplate gt = (PippoGroovyTemplate) groovyTemplate.make(model);
        gt.setup(getLanguages(), getMessages(), getRouter());
        gt.writeTo(writer);
    } catch (Exception e) {
        log.error("Error processing Groovy template {} ", templateContent, e);
        throw new PippoRuntimeException(e);
    }
}