Java Code Examples for org.springframework.ui.freemarker.FreeMarkerTemplateUtils

The following examples show how to use org.springframework.ui.freemarker.FreeMarkerTemplateUtils. 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: SpringBootLearn   Source File: MailTest.java    License: 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 2
Source Project: SENS   Source File: MailServiceImpl.java    License: 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) {
    //配置邮件服务器
    SensUtils.configMail(
            SensConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_HOST.getProp()),
            SensConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_USERNAME.getProp()),
            SensConst.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(SensConst.OPTIONS.get(BlogPropertiesEnum.MAIL_FROM_NAME.getProp()))
                .to(to)
                .html(text)
                .send();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 3
Source Project: SENS   Source File: MailServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 发送带有附件的邮件
 *
 * @param to           接收者
 * @param subject      主题
 * @param content      内容
 * @param templateName 模板路径
 * @param attachSrc    附件路径
 */
@Override
public void sendAttachMail(String to, String subject, Map<String, Object> content, String templateName, String attachSrc) {
    //配置邮件服务器
    SensUtils.configMail(
            SensConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_HOST.getProp()),
            SensConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_USERNAME.getProp()),
            SensConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_PASSWORD.getProp()));
    File file = new File(attachSrc);
    String text = "";
    try {
        Template template = freeMarker.getConfiguration().getTemplate(templateName);
        text = FreeMarkerTemplateUtils.processTemplateIntoString(template, content);
        OhMyEmail.subject(subject)
                .from(SensConst.OPTIONS.get(BlogPropertiesEnum.MAIL_FROM_NAME.getProp()))
                .to(to)
                .html(text)
                .attach(file, file.getName())
                .send();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 4
Source Project: stone   Source File: MailServiceImpl.java    License: 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 5
Source Project: stone   Source File: MailServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 发送带有附件的邮件
 *
 * @param to           接收者
 * @param subject      主题
 * @param content      内容
 * @param templateName 模板路径
 * @param attachSrc    附件路径
 */
@Override
public void sendAttachMail(String to, String subject, Map<String, Object> content, String templateName, String attachSrc) {
    //配置邮件服务器
    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()));
    File file = new File(attachSrc);
    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)
                .attach(file, file.getName())
                .send();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 6
Source Project: mogu_blog_v2   Source File: FreemarkerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateHtml() throws IOException, TemplateException {
    //创建配置类
    Configuration configuration = new Configuration(Configuration.getVersion());
    String classpath = this.getClass().getResource("/").getPath();
    //设置模板路径
    configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
    //设置字符集
    configuration.setDefaultEncoding("utf-8");
    //加载模板
    Template template = configuration.getTemplate("test1.ftl");
    //数据模型
    Map map = getMap();
    //静态化
    String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
    //静态化内容
    System.out.println(content);
    InputStream inputStream = IOUtils.toInputStream(content);
    //输出文件
    FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.html"));
    int copy = IOUtils.copy(inputStream, fileOutputStream);
}
 
Example 7
Source Project: spring-boot-study   Source File: MailController.java    License: 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 8
Source Project: springboot-learn   Source File: FreeMarkerTemplateUtil.java    License: MIT License 6 votes vote down vote up
public String getEmailHtml(Map map, String templateName) {

        String htmlText = "";
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_27);
        try {
            //加载模板路径,此处对应在resource目录下
            configuration.setClassLoaderForTemplateLoading(ClassLoader.getSystemClassLoader(), "ftl");
            //或者
//            configuration.setClassForTemplateLoading(this.getClass(), "/com/mail/ftl");
            //获取对应名称的模板
            Template template = configuration.getTemplate(templateName);
            //渲染模板为html
            htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return htmlText;
    }
 
Example 9
Source Project: spring-boot-study   Source File: MailController.java    License: 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 10
Source Project: cola-cloud   Source File: MailSender.java    License: MIT License 6 votes vote down vote up
/**
 * 发送模板邮件
 */
public void sendTemplateMail(MailSenderParams params) {
    MimeMessage message = null;
    try {
        message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(new InternetAddress(this.getFrom(), MimeUtility.encodeText(this.name,"UTF-8", "B")));
        helper.setTo(params.getMailTo());
        helper.setSubject(params.getTitle());

        this.addAttachment(helper,params);

        Template template = freeMarkerConfigurer.getConfiguration().getTemplate(params.getTemplateFile());
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, params.getTemplateModels());
        helper.setText(html, true);
    } catch (Exception e) {
        throw new RuntimeException("发送邮件异常! from: " + name + "! to: " + params.getMailTo());
    }
    javaMailSender.send(message);
}
 
Example 11
Source Project: blog-sharon   Source File: MailServiceImpl.java    License: Apache License 2.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 {
        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 12
Source Project: blog-sharon   Source File: MailServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 发送带有附件的邮件
 *
 * @param to           接收者
 * @param subject      主题
 * @param content      内容
 * @param templateName 模板路径
 * @param attachSrc    附件路径
 */
@Override
public void sendAttachMail(String to, String subject, Map<String, Object> content, String templateName, String attachSrc) {
    //配置邮件服务器
    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()));
    File file = new File(attachSrc);
    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)
                .attach(file, file.getName())
                .send();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 13
Source Project: halo   Source File: StaticPageServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generate links/index.html.
 *
 * @throws IOException       IOException
 * @throws TemplateException TemplateException
 */
private void generateLink() throws IOException, TemplateException {
    log.info("Generate links.html");

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

    Template template = freeMarkerConfigurer.getConfiguration().getTemplate(themeService.renderWithSuffix("links"));
    String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, null);
    FileWriter fileWriter = new FileWriter(getPageFile("links/index.html"), "UTF-8");
    fileWriter.write(html);

    log.info("Generate links.html succeed.");
}
 
Example 14
Source Project: halo   Source File: StaticPageServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generate categories/index.html.
 *
 * @throws IOException       IOException
 * @throws TemplateException TemplateException
 */
private void generateCategories() throws IOException, TemplateException {
    log.info("Generate categories.html");

    ModelMap model = new ModelMap();

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

    model.addAttribute("is_categories", true);
    Template template = freeMarkerConfigurer.getConfiguration().getTemplate(themeService.renderWithSuffix("categories"));
    String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    FileWriter fileWriter = new FileWriter(getPageFile("categories/index.html"), "UTF-8");
    fileWriter.write(html);

    List<Category> categories = categoryService.listAll();
    for (Category category : categories) {
        generateCategory(1, category);
    }

    log.info("Generate categories.html succeed.");
}
 
Example 15
Source Project: halo   Source File: StaticPageServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generate tags/index.html.
 *
 * @throws IOException       IOException
 * @throws TemplateException TemplateException
 */
private void generateTags() throws IOException, TemplateException {
    log.info("Generate tags.html");

    ModelMap model = new ModelMap();

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

    model.addAttribute("is_tags", true);
    Template template = freeMarkerConfigurer.getConfiguration().getTemplate(themeService.renderWithSuffix("tags"));
    String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    FileWriter fileWriter = new FileWriter(getPageFile("tags/index.html"), "UTF-8");
    fileWriter.write(html);

    log.info("Generate tags.html succeed.");

    List<Tag> tags = tagService.listAll();
    for (Tag tag : tags) {
        generateTag(1, tag);
    }
}
 
Example 16
Source Project: halo   Source File: StaticPageServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generate rss.xml and feed.xml
 *
 * @throws IOException       IOException
 * @throws TemplateException TemplateException
 */
private void generateRss() throws IOException, TemplateException {
    log.info("Generate rss.xml/feed.xml");

    ModelMap model = new ModelMap();

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

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

    FileWriter feedWriter = new FileWriter(getPageFile("feed.xml"), "UTF-8");
    feedWriter.write(xml);

    log.info("Generate rss.xml/feed.xml succeed.");
}
 
Example 17
Source Project: SpringBootUnity   Source File: MailUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 返回激活链接
 *
 * @param email email
 * @return 有3个参数 email password
 */
public static String getContent(String email, String password, Configuration configuration) {
    Long now = TimeUtil.getNowOfMills();
    Map<String, Object> data = new HashMap<>(10);
    StringBuilder sb = new StringBuilder("http://localhost:8080/user/validate?email=");
    sb.append(email);
    sb.append("&password=");
    sb.append(password);
    sb.append("&time=");
    sb.append(now);
    data.put("email", email);
    data.put("url", sb.toString());
    data.put("now", TimeUtil.getFormatDate(now, TimeUtil.DEFAULT_FORMAT));
    Template template;
    String readyParsedTemplate = null;
    try {
        template = configuration.getTemplate("email.ftl");
        readyParsedTemplate = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return readyParsedTemplate;
}
 
Example 18
Source Project: jandy   Source File: ProjectController.java    License: GNU General Public License v3.0 6 votes vote down vote up
@RequestMapping(value = "/{account}/{projectName}/{branchName}.svg")
public ResponseEntity<String> getBadge(@PathVariable String account, @PathVariable String projectName, @PathVariable String branchName) throws Exception {
  QBuild b = QBuild.build;
  Page<Build> buildPage = buildRepository.findAll(b.branch.name.eq(branchName).and(b.branch.project.account.eq(account)).and(b.branch.project.name.eq(projectName)), new QPageRequest(0, 2, b.number.desc()));
  if (buildPage.getTotalPages() == 0)
    throw new BadgeUnknownException();
  Build latest = buildPage.getContent().get(0);

  long current = System.currentTimeMillis();
  HttpHeaders headers = new HttpHeaders(); // see #7
  headers.setExpires(current);
  headers.setDate(current);

  return ResponseEntity
      .ok()
      .headers(headers)
      .cacheControl(CacheControl.noCache())
      .lastModified(current)
      .eTag(Long.toString(latest.getId()))
      .body(FreeMarkerTemplateUtils.processTemplateIntoString(configurer.getConfiguration().getTemplate("badge/mybadge.ftl"), latest));
}
 
Example 19
Source Project: jandy   Source File: Reporter.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Async
public void sendMail(User user, Build current) throws MessagingException {
  mailSender.send(msg -> {
    GHUser ghUser = null;
    if (current.getCommit() != null)
      ghUser = github.getUser(current.getCommit().getCommitterName());

    PrettyTime p = new PrettyTime(Locale.ENGLISH);
    if (current.getFinishedAt() != null)
      current.setBuildAt(p.format(DatatypeConverter.parseDateTime(current.getFinishedAt())));

    HashMap<String, Object> model = new HashMap<>();
    model.put("project", current.getBranch().getProject());
    model.put("build", current);
    model.put("committerAvatarUrl", ghUser == null ? null : user.getAvatarUrl());

    MimeMessageHelper h = new MimeMessageHelper(msg, false, "UTF-8");
    h.setFrom("[email protected]");
    h.setTo(user.getEmail());
    h.setSubject("Jandy Performance Report");
    h.setText(FreeMarkerTemplateUtils.processTemplateIntoString(freeMarkerConfigurer.getConfiguration().getTemplate("email.ftl"), model), true);


  });
}
 
Example 20
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 21
private String getPostMessage(Api api, MessageEntity message) {
    if (message.getText() == null || api == null) {
        return message.getText();
    }
    try {
        Template template = new Template(new Date().toString(), message.getText(), freemarkerConfiguration);

        ApiModelEntity apiEntity = apiService.findByIdForTemplates(api.getId());
        Map<String, Object> model = new HashMap<>();
        model.put("api", apiEntity);

        return FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    } catch (IOException | TemplateException e) {
        LOGGER.error("Unable to apply templating on the message", e);
        throw new TechnicalManagementException("Unable to apply templating on the message", e);
    }
}
 
Example 22
@Override
public List<ApiHeaderEntity> getPortalHeaders(String apiId) {
    List<ApiHeaderEntity> entities = apiHeaderService.findAll();
    ApiModelEntity apiEntity = this.findByIdForTemplates(apiId);
    Map<String, Object> model = new HashMap<>();
    model.put("api", apiEntity);
    entities.forEach(entity -> {
        if (entity.getValue().contains("${")) {
            try {
                Template template = new Template(entity.getId() + entity.getUpdatedAt().toString(), entity.getValue(), freemarkerConfiguration);
                entity.setValue(FreeMarkerTemplateUtils.processTemplateIntoString(template, model));
            } catch (IOException | TemplateException e) {
                LOGGER.error("Unable to apply templating on api headers ", e);
                throw new TechnicalManagementException("Unable to apply templating on api headers", e);
            }
        }
    });
    return entities.stream()
            .filter(apiHeaderEntity -> apiHeaderEntity.getValue() != null && !apiHeaderEntity.getValue().isEmpty())
            .collect(Collectors.toList());
}
 
Example 23
@Override
@NonNull
public String mergeTemplateIntoString(final @NonNull String templateReference,
                                      final @NonNull Map<String, Object> model)
        throws IOException, TemplateException {
    final String trimmedTemplateReference = templateReference.trim();
    checkArgument(!isNullOrEmpty(trimmedTemplateReference), "The given template is null, empty or blank");
    if (trimmedTemplateReference.contains("."))
        checkArgument(Objects.equals(getFileExtension(trimmedTemplateReference), expectedTemplateExtension()),
                "Expected a Freemarker template file with extension 'ftl', while '%s' was given",
                getFileExtension(trimmedTemplateReference));

    try {
        final String normalizedTemplateReference = trimmedTemplateReference.endsWith(expectedTemplateExtension()) ?
                trimmedTemplateReference : trimmedTemplateReference + '.' + expectedTemplateExtension();
        return FreeMarkerTemplateUtils.processTemplateIntoString(
                freemarkerConfiguration.getTemplate(normalizedTemplateReference, Charset.forName("UTF-8").name()), model);
    } catch (Exception e) {
        throw new TemplateException(e);
    }
}
 
Example 24
Source Project: spring-boot-actuator-logview   Source File: LogViewEndpoint.java    License: 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 25
Source Project: spring-analysis-note   Source File: FreeMarkerConfigurerTests.java    License: MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void freeMarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath() throws Exception {
	FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
	fcfb.setTemplateLoaderPath("file:/mydir");
	Properties settings = new Properties();
	settings.setProperty("localized_lookup", "false");
	fcfb.setFreemarkerSettings(settings);
	fcfb.setResourceLoader(new ResourceLoader() {
		@Override
		public Resource getResource(String location) {
			if (!("file:/mydir".equals(location) || "file:/mydir/test".equals(location))) {
				throw new IllegalArgumentException(location);
			}
			return new ByteArrayResource("test".getBytes(), "test");
		}
		@Override
		public ClassLoader getClassLoader() {
			return getClass().getClassLoader();
		}
	});
	fcfb.afterPropertiesSet();
	assertThat(fcfb.getObject(), instanceOf(Configuration.class));
	Configuration fc = fcfb.getObject();
	Template ft = fc.getTemplate("test");
	assertEquals("test", FreeMarkerTemplateUtils.processTemplateIntoString(ft, new HashMap()));
}
 
Example 26
Source Project: mogu_blog_v2   Source File: FreemarkerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateHtmlByString() throws IOException, TemplateException {
    //创建配置类
    Configuration configuration = new Configuration(Configuration.getVersion());
    //获取模板内容
    //模板内容,这里测试时使用简单的字符串作为模板
    String templateString = "" +
            "<html>\n" +
            "    <head></head>\n" +
            "    <body>\n" +
            "    名称:${name}\n" +
            "    </body>\n" +
            "</html>";

    //加载模板
    //模板加载器
    StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
    stringTemplateLoader.putTemplate("template", templateString);
    configuration.setTemplateLoader(stringTemplateLoader);
    Template template = configuration.getTemplate("template", "utf-8");

    //数据模型
    Map map = getMap();
    //静态化
    String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
    //静态化内容
    System.out.println(content);
    InputStream inputStream = IOUtils.toInputStream(content);
    //输出文件
    FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.html"));
    IOUtils.copy(inputStream, fileOutputStream);
}
 
Example 27
Source Project: hellokoding-courses   Source File: SendingMailService.java    License: 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 28
Source Project: java-technology-stack   Source File: FreeMarkerConfigurerTests.java    License: MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void freeMarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath() throws Exception {
	FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
	fcfb.setTemplateLoaderPath("file:/mydir");
	Properties settings = new Properties();
	settings.setProperty("localized_lookup", "false");
	fcfb.setFreemarkerSettings(settings);
	fcfb.setResourceLoader(new ResourceLoader() {
		@Override
		public Resource getResource(String location) {
			if (!("file:/mydir".equals(location) || "file:/mydir/test".equals(location))) {
				throw new IllegalArgumentException(location);
			}
			return new ByteArrayResource("test".getBytes(), "test");
		}
		@Override
		public ClassLoader getClassLoader() {
			return getClass().getClassLoader();
		}
	});
	fcfb.afterPropertiesSet();
	assertThat(fcfb.getObject(), instanceOf(Configuration.class));
	Configuration fc = fcfb.getObject();
	Template ft = fc.getTemplate("test");
	assertEquals("test", FreeMarkerTemplateUtils.processTemplateIntoString(ft, new HashMap()));
}
 
Example 29
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 30
Source Project: paascloud-master   Source File: UacFreeMarkerServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
	public String getTemplate(Map<String, Object> map, String templateLocation) throws IOException, TemplateException {
		Preconditions.checkArgument(StringUtils.isNotEmpty(templateLocation), "模板不能为空");

		Template t = configuration.getTemplate(templateLocation, "UTF-8");
		return FreeMarkerTemplateUtils.processTemplateIntoString(t, map);

//        return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateLocation, "UTF-8", map);
	}