Java Code Examples for org.springframework.ui.freemarker.FreeMarkerTemplateUtils#processTemplateIntoString()

The following examples show how to use org.springframework.ui.freemarker.FreeMarkerTemplateUtils#processTemplateIntoString() . 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 File: EmailNotifierServiceImpl.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private List<String> getMails(final GenericNotificationConfig genericNotificationConfig, final Map<String, Object> params) {
    String[] mails = genericNotificationConfig.getConfig().split(",|;|\\s");
    List<String> result = new ArrayList<>();
    for (String mail : mails) {
        if(!mail.isEmpty()) {
            if(mail.contains("$")) {
                try {
                    final Template template = new Template(mail, mail, freemarkerConfiguration);
                    String tmpMail = FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
                    if(!tmpMail.isEmpty()) {
                        mail = tmpMail;
                    }
                } catch (IOException | TemplateException e) {
                    LOGGER.debug("Email recipient cannot be interpreted {}", mail, e);
                    continue;
                }
            }
            result.add(mail);
        }
    }
    return result;
}
 
Example 2
Source File: MailServiceImpl.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 发送模板邮件
 *
 * @param to           接收者
 * @param subject      主题
 * @param content      内容
 * @param templateName 模板路径
 */
@Override
public void sendTemplateMail(String to, String subject, Map<String, Object> content, String templateName) {
    //配置邮件服务器
    HaloUtils.configMail(
            HaloConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_HOST.getProp()),
            HaloConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_USERNAME.getProp()),
            HaloConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_PASSWORD.getProp()));
    String text = "";
    try {
        final Template template = freeMarker.getConfiguration().getTemplate(templateName);
        text = FreeMarkerTemplateUtils.processTemplateIntoString(template, content);
        OhMyEmail.subject(subject)
                .from(HaloConst.OPTIONS.get(BlogPropertiesEnum.MAIL_FROM_NAME.getProp()))
                .to(to)
                .html(text)
                .send();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 3
Source File: LogViewEndpoint.java    From spring-boot-actuator-logview with MIT License 6 votes vote down vote up
@RequestMapping("/")
@ResponseBody
public String list(Model model, // TODO model should no longer be injected
                   @RequestParam(required = false, defaultValue = "FILENAME") SortBy sortBy,
                   @RequestParam(required = false, defaultValue = "false") boolean desc,
                   @RequestParam(required = false) String base) throws IOException, TemplateException {
    securityCheck(base);

    Path currentFolder = loggingPath(base);

    List<FileEntry> files = getFileProvider(currentFolder).getFileEntries(currentFolder);
    List<FileEntry> sortedFiles = sortFiles(files, sortBy, desc);

    model.addAttribute("sortBy", sortBy);
    model.addAttribute("desc", desc);
    model.addAttribute("files", sortedFiles);
    model.addAttribute("currentFolder", currentFolder.toAbsolutePath().toString());
    model.addAttribute("base", base != null ? URLEncoder.encode(base, "UTF-8") : "");
    model.addAttribute("parent", getParent(currentFolder));
    model.addAttribute("stylesheets", stylesheets);

    return FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfig.getTemplate("logview.ftl"), model);
}
 
Example 4
Source File: MailController.java    From spring-boot-study with Apache License 2.0 6 votes vote down vote up
/**
 * 内联附件的邮件测试
 *
 * @return success
 * @throws MessagingException
 */
@GetMapping("/freemarker")
public String freemarker() throws MessagingException, IOException, TemplateException {
    MimeMessage message = this.javaMailSender.createMimeMessage();
    // 第二个参数表示是否开启multipart模式
    MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
    messageHelper.setFrom(this.mailProperties.getUsername());
    messageHelper.setTo("[email protected]");
    messageHelper.setSubject("基于freemarker模板的邮件测试");

    Map<String, Object> model = new HashMap<>();
    model.put("username", "itmuch");
    model.put("event", "IT牧场大事件");

    String content = FreeMarkerTemplateUtils.processTemplateIntoString(
            this.freemarkerConfiguration.getTemplate("mail.ftl"), model);

    // 第二个参数表示是否html,设为true
    messageHelper.setText(content, true);

    this.javaMailSender.send(message);
    return "success";
}
 
Example 5
Source File: MailTest.java    From SpringBootLearn with Apache License 2.0 6 votes vote down vote up
/**
 * 发送模板信息
 * @throws Exception
 */
@Test
public void sendTemplateMail() throws Exception {

    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setFrom(username);
    helper.setTo("[email protected]");
    helper.setSubject("测试主题:模板邮件");
    /**
     * 模板内需要的参数,保持一致
     */
    Map<String, Object> params = new HashMap<>();
    params.put("userName", "lihaodong");
    /**
     * 配置FreeMarker模板路径
     */
    Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
    configuration.setClassForTemplateLoading(this.getClass(), "/templates");
    String html = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("mail.ftl"), params);
    helper.setText(html, true);

    javaMailSender.send(mimeMessage);
}
 
Example 6
Source File: MailController.java    From spring-boot-study with MIT License 6 votes vote down vote up
/**
 * 基于 freemarker 模板发送
 * */
@GetMapping("/sendTemplateMail")
public String sendTemplateMail(){
    MimeMessage message = null;
    try{

        message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true);
        helper.setFrom(sendUser);
        helper.setTo("[email protected]");
        helper.setSubject("主题邮件");
        Map<String,Object> model =new HashMap<>();
        model.put("welcome","欢迎您,hello world template email ");
        //使用 freeMarkerConfigurer 获取模板 index.ftl
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate("index.ftl");
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
        helper.setText(html, true);

    }catch (Exception e){
        e.printStackTrace();
        return "fail";
    }
    mailSender.send(message);
    return "success";
}
 
Example 7
Source File: EmailServiceImpl.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void sendMessageUsingFreemarkerTemplate(
    String to, String subject, Map<String, Object> templateModel)
        throws IOException, TemplateException, MessagingException {

    Template freemarkerTemplate = freemarkerConfigurer.createConfiguration().getTemplate("template-freemarker.ftl");
    String htmlBody = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerTemplate, templateModel);

    sendHtmlMessage(to, subject, htmlBody);
}
 
Example 8
Source File: ContentFeedController.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get category post rss.
 *
 * @param model model
 * @param slug  slug
 * @return rss xml content
 * @throws IOException       throw IOException
 * @throws TemplateException throw TemplateException
 */
@GetMapping(value = {"feed/categories/{slug}", "feed/categories/{slug}.xml"}, produces = XML_MEDIA_TYPE)
@ResponseBody
public String feed(Model model, @PathVariable(name = "slug") String slug) throws IOException, TemplateException {
    Category category = categoryService.getBySlugOfNonNull(slug);
    CategoryDTO categoryDTO = categoryService.convertTo(category);
    model.addAttribute("category", categoryDTO);
    model.addAttribute("posts", buildCategoryPosts(buildPostPageable(optionService.getRssPageSize()), categoryDTO));
    Template template = freeMarker.getConfiguration().getTemplate("common/web/rss.ftl");
    return FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
}
 
Example 9
Source File: MailServiceImpl.java    From blog-sharon with Apache License 2.0 5 votes vote down vote up
/**
 * 发送模板邮件
 *
 * @param to           接收者
 * @param subject      主题
 * @param content      内容
 * @param templateName 模板路径
 */
@Override
public void sendTemplateMail(String to, String subject, Map<String, Object> content, String templateName) {
    //配置邮件服务器
    HaloUtils.configMail(
            HaloConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_HOST.getProp()),
            HaloConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_USERNAME.getProp()),
            HaloConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_PASSWORD.getProp()));
    String text = "";
    try {
        Template template = freeMarker.getConfiguration().getTemplate(templateName);
        text = FreeMarkerTemplateUtils.processTemplateIntoString(template, content);
        OhMyEmail.subject(subject)
                .from(HaloConst.OPTIONS.get(BlogPropertiesEnum.MAIL_FROM_NAME.getProp()))
                .to(to)
                .html(text)
                .send();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 10
Source File: StaticPageServiceImpl.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generate s/{slug}/index.html.
 *
 * @throws IOException       IOException
 * @throws TemplateException TemplateException
 */
private void generateSheet() throws IOException, TemplateException {
    if (!themeService.templateExists("sheet.ftl")) {
        log.warn("sheet.ftl not found,skip!");
        return;
    }

    List<Sheet> sheets = sheetService.listAllBy(PostStatus.PUBLISHED);
    for (Sheet sheet : sheets) {
        log.info("Generate s/{}/index.html", sheet.getSlug());
        ModelMap model = new ModelMap();

        SheetDetailVO sheetDetailVO = sheetService.convertToDetailVo(sheet);
        model.addAttribute("sheet", sheetDetailVO);
        model.addAttribute("post", sheetDetailVO);
        model.addAttribute("is_sheet", true);

        String templateName = "sheet";

        if (themeService.templateExists(ThemeService.CUSTOM_SHEET_PREFIX + sheet.getTemplate() + HaloConst.SUFFIX_FTL)) {
            templateName = ThemeService.CUSTOM_SHEET_PREFIX + sheet.getTemplate();
        }

        Template template = freeMarkerConfigurer.getConfiguration().getTemplate(themeService.renderWithSuffix(templateName));
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

        FileWriter fileWriter = new FileWriter(getPageFile("s/" + sheet.getSlug() + "/index.html"), "UTF-8");
        fileWriter.write(html);

        log.info("Generate s/{}/index.html succeed.", sheet.getSlug());
    }
}
 
Example 11
Source File: SendingMailService.java    From hellokoding-courses with MIT License 5 votes vote down vote up
public boolean sendVerificationMail(String toEmail, String verificationCode) {
    String subject = "Please verify your email";
    String body = "";
    try {
        Template t = templates.getTemplate("email-verification.ftl");
        Map<String, String> map = new HashMap<>();
        map.put("VERIFICATION_URL", mailProperties.getVerificationapi() + verificationCode);
        body = FreeMarkerTemplateUtils.processTemplateIntoString(t, map);
    } catch (Exception ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex);
    }
    return sendMail(toEmail, subject, body);
}
 
Example 12
Source File: MailServiceImpl.java    From mblog with GNU General Public License v3.0 5 votes vote down vote up
private String render(String templateName, Map<String, Object> model) {
    try {
        Template t = freeMarkerConfigurer.getConfiguration().getTemplate(templateName, "UTF-8");
        t.setOutputEncoding("UTF-8");
        return FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
    } catch (Exception e) {
        throw new MtonsException(e.getMessage(), e);
    }
}
 
Example 13
Source File: StaticPageServiceImpl.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generate robots.txt
 *
 * @throws IOException       IOException
 * @throws TemplateException TemplateException
 */
private void generateRobots() throws IOException, TemplateException {
    log.info("Generate robots.txt");

    Template template = freeMarkerConfigurer.getConfiguration().getTemplate("common/web/robots.ftl");
    String txt = FreeMarkerTemplateUtils.processTemplateIntoString(template, null);
    FileWriter fileWriter = new FileWriter(getPageFile("robots.txt"), "UTF-8");
    fileWriter.write(txt);

    log.info("Generate robots.txt succeed.");
}
 
Example 14
Source File: StaticPageServiceImpl.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generate archives/{slug}/index.html.
 *
 * @throws IOException       IOException
 * @throws TemplateException TemplateException
 */
private void generatePost() throws IOException, TemplateException {

    if (!themeService.templateExists("post.ftl")) {
        log.warn("post.ftl not found,skip!");
        return;
    }

    List<Post> posts = postService.listAllBy(PostStatus.PUBLISHED);

    for (Post post : posts) {
        log.info("Generate archives/{}/index.html", post.getSlug());
        ModelMap model = new ModelMap();

        AdjacentPostVO adjacentPostVO = postService.getAdjacentPosts(post);
        adjacentPostVO.getOptionalPrevPost().ifPresent(prevPost -> model.addAttribute("prevPost", prevPost));
        adjacentPostVO.getOptionalNextPost().ifPresent(nextPost -> model.addAttribute("nextPost", nextPost));

        List<Category> categories = postCategoryService.listCategoriesBy(post.getId());
        List<Tag> tags = postTagService.listTagsBy(post.getId());
        List<PostMeta> metas = postMetaService.listBy(post.getId());

        model.addAttribute("is_post", true);
        model.addAttribute("post", postService.convertToDetailVo(post));
        model.addAttribute("categories", categories);
        model.addAttribute("tags", tags);
        model.addAttribute("metas", postMetaService.convertToMap(metas));

        Template template = freeMarkerConfigurer.getConfiguration().getTemplate(themeService.renderWithSuffix("post"));
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

        FileWriter fileWriter = new FileWriter(getPageFile("archives/" + post.getSlug() + "/index.html"), "UTF-8");
        fileWriter.write(html);
        log.info("Generate archives/{}/index.html succeed.", post.getSlug());
    }
}
 
Example 15
Source File: StaticPageServiceImpl.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generate sitemap.html
 *
 * @throws IOException       IOException
 * @throws TemplateException TemplateException
 */
private void generateSiteMapHtml() throws IOException, TemplateException {
    log.info("Generate sitemap.html");

    ModelMap model = new ModelMap();

    model.addAttribute("posts", buildPosts(buildPostPageable(optionService.getRssPageSize())));

    Template template = freeMarkerConfigurer.getConfiguration().getTemplate("common/web/sitemap_html.ftl");
    String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    FileWriter fileWriter = new FileWriter(getPageFile("sitemap.html"), "UTF-8");
    fileWriter.write(html);

    log.info("Generate sitemap.html succeed.");
}
 
Example 16
Source File: StaticPageServiceImpl.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generate atom.xml
 *
 * @throws IOException       IOException
 * @throws TemplateException TemplateException
 */
private void generateAtom() throws IOException, TemplateException {
    log.info("Generate atom.xml");

    ModelMap model = new ModelMap();

    model.addAttribute("posts", buildPosts(buildPostPageable(optionService.getRssPageSize())));

    Template template = freeMarkerConfigurer.getConfiguration().getTemplate("common/web/atom.ftl");
    String xml = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    FileWriter fileWriter = new FileWriter(getPageFile("atom.xml"), "UTF-8");
    fileWriter.write(xml);

    log.info("Generate atom.xml succeed.");
}
 
Example 17
Source File: EmailTemplateService.java    From Spring-Boot-2.0-Projects with MIT License 4 votes vote down vote up
public String getResetPasswordEmail(Map<String, Object> data, String templateName) throws IOException, TemplateException {
    Template template = configuration.getTemplate(templateName);
    return FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
}
 
Example 18
Source File: OptFreeMarkerServiceImpl.java    From paascloud-master with Apache License 2.0 4 votes vote down vote up
@Override
public String getTemplate(Map<String, Object> map, String templateLocation) throws IOException, TemplateException {
	Preconditions.checkArgument(PublicUtil.isNotEmpty(templateLocation), "模板不能为空");
	Template t = configuration.getTemplate(templateLocation, "UTF-8");
	return FreeMarkerTemplateUtils.processTemplateIntoString(t, map);
}
 
Example 19
Source File: XmlIngester.java    From rice with Educational Community License v2.0 3 votes vote down vote up
/**
 * writes processed template  to file
 *
 * @param file
 * @param template
 * @param props
 * @return
 * @throws IOException
 * @throws TemplateException
 */
private File writeTemplateToFile(File file, Template template, Properties props) throws IOException, TemplateException {
    String output = FreeMarkerTemplateUtils.processTemplateIntoString(template, props);
    LOG.debug("Generated File Output: " + output);
    FileUtils.writeStringToFile(file, output);
    return file;
}
 
Example 20
Source File: JavaMailService.java    From base-framework with Apache License 2.0 2 votes vote down vote up
/**
 * 获取freemarker模板的内容
 * 
 * @param templateName 模板名称
 * @param model freemarker模板里要取值的el名称
 * 
 * @return String
 * 
 * @throws IOException
 * @throws TemplateException
 */
private String getTemplateString(String templateName,Map<String, ?> model) throws IOException, TemplateException {
	Template template = freemarkerConfiguration.getTemplate(templateName, encoding);
	return FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
}