@Override protected Configuration getFreemarkerConfiguration(RepoCtx ctx) { if (useRemoteCallbacks) { // as per 3.0, 3.1 return super.getFreemarkerConfiguration(ctx); } else { Configuration cfg = new Configuration(); cfg.setObjectWrapper(new DefaultObjectWrapper()); cfg.setTemplateLoader(new ClassPathRepoTemplateLoader(nodeService, contentService, defaultEncoding)); // TODO review i18n cfg.setLocalizedLookup(false); cfg.setIncompatibleImprovements(new Version(2, 3, 20)); cfg.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER); return cfg; } }
@Override protected ObjectWrapper initialValue() { return new DefaultObjectWrapper() { /* (non-Javadoc) * @see freemarker.template.DefaultObjectWrapper#wrap(java.lang.Object) */ @Override public TemplateModel wrap(Object obj) throws TemplateModelException { if (obj instanceof QNameMap) { return new QNameHash((QNameMap)obj, this); } else { return super.wrap(obj); } } }; }
public ValidatableFormAdapter(Validatable form, DefaultObjectWrapper ow) { super(form, ow); this.hasErrors = arguments -> { if (arguments.size() == 0) { return Boolean.valueOf(form.hasErrors()); } else if (arguments.size() == 1) { return Boolean.valueOf(form.hasErrors(arguments.get(0).toString())); } else { return null; } }; this.getErrors = arguments -> { if (arguments.size() == 0) { return form.getErrors(); } else if (arguments.size() == 1) { return form.getErrors(arguments.get(0).toString()); } else { return null; } }; }
/** * 根据根路径的类,获取配置文件 * @author nan.li * @param paramClass * @param prefix * @return */ public static Configuration getConfigurationByClass(Class<?> paramClass, String prefix) { try { Configuration configuration = new Configuration(Configuration.VERSION_2_3_25); configuration.setClassForTemplateLoading(paramClass, prefix); //等价于下面这种方法 // configuration.setTemplateLoader( new ClassTemplateLoader(paramClass,prefix)); configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_25)); configuration.setDefaultEncoding(CharEncoding.UTF_8); configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); configuration.setObjectWrapper(new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25).build()); return configuration; } catch (Exception e) { e.printStackTrace(); } return null; }
public static Configuration getConfigurationByClassLoader(ClassLoader classLoader, String prefix) { try { Configuration configuration = new Configuration(Configuration.VERSION_2_3_25); configuration.setClassLoaderForTemplateLoading(classLoader, prefix); //等价于下面这种方法 // configuration.setTemplateLoader( new ClassTemplateLoader(paramClass,prefix)); configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_25)); configuration.setDefaultEncoding(CharEncoding.UTF_8); configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); configuration.setObjectWrapper(new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25).build()); return configuration; } catch (Exception e) { e.printStackTrace(); } return null; }
@SuppressWarnings("rawtypes") @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { SimpleScalar pVar = (SimpleScalar) params.get("var"); List<RetailStore> retailStoreList = retailStores.enabledRetailStores(); if (pVar != null) { // Sets the result into the current template as if using <#assign // name=model>. env.setVariable(pVar.getAsString(), DefaultObjectWrapper.getDefaultInstance().wrap(retailStoreList)); } else { // Sets the result into the current template as if using <#assign // name=model>. env.setVariable("retailStores", DefaultObjectWrapper.getDefaultInstance().wrap(retailStoreList)); } }
/** * 获取模板 * * @param templateName * 模板名称(含后缀名) * @return Template * @throws IOException */ public static Template getTemplate(String templateName) throws IOException { Configuration cfg = new Configuration(); Template temp = null; File tmpRootFile = getResource(templateName).getFile().getParentFile(); if (tmpRootFile == null) { throw new RuntimeException("无法取得模板根路径!"); } try { cfg.setDefaultEncoding("utf-8"); cfg.setOutputEncoding("utf-8"); cfg.setDirectoryForTemplateLoading(tmpRootFile); /* cfg.setDirectoryForTemplateLoading(getResourceURL()); */ cfg.setObjectWrapper(new DefaultObjectWrapper()); temp = cfg.getTemplate(templateName); } catch (IOException e) { e.printStackTrace(); } return temp; }
protected List<File> buildUserFileUploadList() throws Exception { List<File> fileUploadList = new ArrayList<File>(); try { Properties props = loadProperties(PROPS_LOCATION, DEFAULT_PROPS_LOCATION); String usersArg = System.getProperty("xmlingester.user.list").replace(".", "").replace("-", "").toLowerCase(); List<XmlIngesterUser> xmlIngesterUsers = new LinkedList<XmlIngesterUser>(); StringTokenizer token = new StringTokenizer(usersArg, ","); while (token.hasMoreTokens()) { xmlIngesterUsers.add(new XmlIngesterUser(token.nextToken())); } props.put("xmlIngesterUsers", xmlIngesterUsers); cfg.setObjectWrapper(new DefaultObjectWrapper()); // build files and add to array fileUploadList.add( writeTemplateToFile(newTempFile("userlist-users.xml"), cfg.getTemplate("UserListIngestion.ftl"), props)); } catch( Exception e) { throw new Exception("Unable to generate files for upload " + e.getMessage(), e); } return fileUploadList; }
public void init() { // 初始化FreeMarker配置 // 创建一个Configuration实例 cfg = new Configuration(); // 设置FreeMarker的模版文件位置 cfg.setServletContextForTemplateLoading(getServletContext(), "template"); // 设置包装器,并将对象包装为数据模型 cfg.setObjectWrapper(new DefaultObjectWrapper()); try { fr = FisRewrite.getInstance(); } catch (FisException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * 获取模板 * * @param templatePath * 模板文件存放目录 * @param templateName * 模板文件名称 * @param templateEncoding * 模板文件的编码方式 * @throws IOException */ public static Template getTemplate(String templatePath, String templateName, String templateEncoding) throws IOException { Configuration config = new Configuration(); File file = new File(templatePath); // 设置要解析的模板所在的目录,并加载模板文件 config.setDirectoryForTemplateLoading(file); // 设置包装器,并将对象包装为数据模型 config.setObjectWrapper(new DefaultObjectWrapper()); // 获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致 Template template = config.getTemplate(templateName, templateEncoding); return template; }
/** * 获取模板 * * @param context * ServletContext * @param templatePath * 模板文件存放目录 * @param templateName * 模板文件名称 * @param templateEncoding * 模板文件的编码方式 * @throws IOException */ public static Template getTemplate(ServletContext context, String templatePath, String templateName, String templateEncoding) throws IOException { Configuration config = new Configuration(); File file = new File(templatePath); // 设置要解析的模板所在的目录,并加载模板文件 config.setDirectoryForTemplateLoading(file); // 设置包装器,并将对象包装为数据模型 config.setObjectWrapper(new DefaultObjectWrapper()); // 获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致 Template template = config.getTemplate(templateName, templateEncoding); return template; }
/** * * @param messager - the compiler message to print messages to * @param generateMockImplementation * @param packageName - the package name of the generated class (and the interface to implement) * @param interfaceName - the (simple) name of the interface to implement */ public FacadeRouterCodeGenerator(Messager messager, boolean generateMockImplementation, boolean generateTests) { freemarkerConfig = new Configuration(); freemarkerConfig.setTemplateLoader( new ClassLoaderTemplateLoader(this.getClass().getClassLoader(), messager) ); freemarkerConfig.setObjectWrapper(new DefaultObjectWrapper()); dataModel.put(METHODS, new ArrayList<Map<String, Object>>()); dataModel.put(IMPORTS, new ArrayList<String>()); this.messager = messager; this.generateMockImplementation = generateMockImplementation; this.generateTests = generateTests; }
public SourceReportGenerator(GradeCategories grades, SourceLoader sourceLoader, File outputDirectory, CostModel costModel, Date currentTime, int worstCount, Configuration cfg) { this.grades = grades; this.sourceLoader = sourceLoader; this.directory = outputDirectory; this.costModel = costModel; this.cfg = cfg; cfg.setTemplateLoader(new ClassPathTemplateLoader(PREFIX)); cfg.setObjectWrapper(new DefaultObjectWrapper()); try { cfg.setSharedVariable("maxExcellentCost", grades.getMaxExcellentCost()); cfg.setSharedVariable("maxAcceptableCost", grades.getMaxAcceptableCost()); cfg.setSharedVariable("currentTime", currentTime); cfg.setSharedVariable("computeOverallCost", new OverallCostMethod()); cfg.setSharedVariable("printCost", new PrintCostMethod()); } catch (TemplateModelException e) { throw new RuntimeException(e); } projectByClassReport = new ProjectReport("index", grades, new WeightedAverage()); projectByClassReport.setMaxUnitCosts(worstCount); projectByPackageReport = new ProjectReport("index", grades, new WeightedAverage()); }
public ExtraDaoGenerator() throws IOException { System.out.println("greenDAO Generator"); System.out.println("Copyright 2011-2014 Markus Junginger, greenrobot.de. Licensed under GPL V3."); System.out.println("This program comes with ABSOLUTELY NO WARRANTY"); patternKeepIncludes = compilePattern("INCLUDES"); patternKeepFields = compilePattern("FIELDS"); patternKeepMethods = compilePattern("METHODS"); Configuration config = new Configuration(); config.setClassForTemplateLoading(this.getClass(), "/"); config.setObjectWrapper(new DefaultObjectWrapper()); templateDao = config.getTemplate("dao.ftl"); templateDaoMaster = config.getTemplate("dao-master.ftl"); templateDaoSession = config.getTemplate("dao-session.ftl"); templateEntity = config.getTemplate("entity.ftl"); templateDaoUnitTest = config.getTemplate("dao-unit-test.ftl"); templateContentProvider = config.getTemplate("content-provider.ftl"); templateDBService = config.getTemplate("db-service.ftl"); }
public FreeMarkerRenderer() { cfg = new Configuration(); if(ApplicationState.isDevelopment()){ try { cfg.setDirectoryForTemplateLoading(new File("src/main/resources/templates/")); } catch (IOException e) { l.error("Failed to access path", e); } }else{ cfg.setClassForTemplateLoading(this.getClass(), "/templates/"); } cfg.setObjectWrapper(new DefaultObjectWrapper()); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER); }
public void initConfiguration() { try { config = new Configuration(); config.setDirectoryForTemplateLoading(new File("templates/")); config.setObjectWrapper(new DefaultObjectWrapper()); config.setSetting("classic_compatible", "true"); config.setSetting("whitespace_stripping", "true"); config.setSetting("template_update_delay", "1"); config.setSetting("locale", "zh_CN"); config.setSetting("default_encoding", "utf-8"); config.setSetting("url_escaping_charset", "utf-8"); config.setSetting("datetime_format", "yyyy-MM-dd hh:mm:ss"); config.setSetting("date_format", "yyyy-MM-dd"); config.setSetting("time_format", "HH:mm:ss"); config.setSetting("number_format", "0.######;"); } catch (Exception e) { e.printStackTrace(); } }
AbstractPrintGeneratingTest() { targetDirectory.mkdirs(); try { freeMarkerConfiguration = new Configuration(); freeMarkerConfiguration.setTemplateLoader(new ClassTemplateLoader(Class.class, "/")); //freeMarkerConfiguration.setDirectoryForTemplateLoading(new File(templateDirectory).getAbsoluteFile()); freeMarkerConfiguration.setObjectWrapper(new DefaultObjectWrapper()); freeMarkerConfiguration.setDefaultEncoding("UTF-8"); freeMarkerConfiguration.setTemplateExceptionHandler(HTML_DEBUG_HANDLER); freeMarkerConfiguration.setIncompatibleImprovements(new Version(2, 3, 20)); printsRendererService.setFreeMarkerConfiguration(freeMarkerConfiguration); } catch (Exception e) { throw new RuntimeException(e); } }
public static void generate(DatabaseClasses classes, String outputdir) throws IOException, TemplateException { Configuration cfg = new Configuration(); cfg.setClassForTemplateLoading(TypeGen.class, "/"); cfg.setObjectWrapper(new DefaultObjectWrapper()); Template interfaceTemp = cfg.getTemplate(DATABASE_TEMPLATE_FILE); Template implTemp = cfg.getTemplate(DATABASE_IMPL_TEMPLATE_FILE); for (DatabaseClass databaseClass : classes.getClasses().values()) { Map<String, DatabaseClass> root = new HashMap<String, DatabaseClass>(); root.put("databaseClass", databaseClass); Writer out = FileUtil.createAndGetOutputStream(databaseClass.getQualifiedInterfaceName(), outputdir); interfaceTemp.process(root, out); out.flush(); out = FileUtil.createAndGetOutputStream(databaseClass.getQualifiedImplementationName(), outputdir); implTemp.process(root, out); out.flush(); } }
public void generate() throws GlobalConfigException { Configuration cfg = new Configuration(); File tmplDir = globalConfig.getTmplFile(); try { cfg.setDirectoryForTemplateLoading(tmplDir); } catch (IOException e) { throw new GlobalConfigException("tmplPath", e); } cfg.setObjectWrapper(new DefaultObjectWrapper()); for (Module module : modules) { logger.debug("module:" + module.getName()); for (Bean bean : module.getBeans()) { logger.debug("bean:" + bean.getName()); Map dataMap = new HashMap(); dataMap.put("bean", bean); dataMap.put("module", module); dataMap.put("generate", generate); dataMap.put("config", config); dataMap.put("now", DateFormatUtils.ISO_DATE_FORMAT.format(new Date())); generate(cfg, dataMap); } } }
public void generateUpdateClass(File outJavaFile, String outJavaPackage) throws IOException { String template = new String(IOUtils.toCharArray(UpdateClassGenerator.class.getResourceAsStream("/UpdateClass.template.java"))); Configuration cfg = new Configuration(); StringTemplateLoader loader = new StringTemplateLoader(); loader.putTemplate("template", template); cfg.setTemplateLoader(loader); cfg.setObjectWrapper(new DefaultObjectWrapper()); Template temp = cfg.getTemplate("template"); FileWriter fw = new FileWriter(outJavaFile); BufferedWriter bw = new BufferedWriter(fw); try { temp.process(this.buildTemplateModel(outJavaPackage), bw); } catch (TemplateException e) { throw new Error(e); } bw.close(); fw.close(); }
public DaoGenerator() throws IOException { System.out.println("greenDAO Generator"); System.out.println("Copyright 2011-2013 Markus Junginger, greenrobot.de. Licensed under GPL V3."); System.out.println("This program comes with ABSOLUTELY NO WARRANTY"); patternKeepIncludes = compilePattern("INCLUDES"); patternKeepFields = compilePattern("FIELDS"); patternKeepMethods = compilePattern("METHODS"); Configuration config = new Configuration(); config.setClassForTemplateLoading(this.getClass(), "/"); config.setObjectWrapper(new DefaultObjectWrapper()); templateDao = config.getTemplate("dao.ftl"); templateDaoMaster = config.getTemplate("dao-master.ftl"); templateDaoSession = config.getTemplate("dao-session.ftl"); templateEntity = config.getTemplate("entity.ftl"); templateDaoUnitTest = config.getTemplate("dao-unit-test.ftl"); templateContentProvider = config.getTemplate("content-provider.ftl"); }
@Provides @Singleton public FreemarkerTemplater createFreemarker(ServletContext context, FreemarkerURLHelper urlHelper, GuiceConfig configuration) { Configuration freemarker = new Configuration(FREEMARKER_COMPATIBILITY_VERSION); freemarker.setServletContextForTemplateLoading(context, "/WEB-INF/template/"); freemarker.setObjectWrapper(new DefaultObjectWrapper(FREEMARKER_COMPATIBILITY_VERSION)); FreemarkerTemplater templater = new FreemarkerTemplater(freemarker); templater.set("urls", urlHelper); templater.set("config", configuration); return templater; }
public AbstractGenerator() { try { this.config = new Configuration(); this.config.setClassForTemplateLoading(this.getClass(), "templates"); this.config.setObjectWrapper(new DefaultObjectWrapper()); } catch (NoClassDefFoundError var2) { if (var2.getCause() == null) { var2.initCause(INITIALIZER_EXCEPTION); } throw var2; } catch (ExceptionInInitializerError var3) { INITIALIZER_EXCEPTION = var3; throw var3; } }
public AbstractAdapterGenerator() { synchronized (AbstractAdapterGenerator.class) { try { this.config = new Configuration(); this.config.setClassForTemplateLoading(this.getClass(), "templates"); this.config.setObjectWrapper(new DefaultObjectWrapper()); } catch (NoClassDefFoundError var2) { if (var2.getCause() == null) { var2.initCause(INITIALIZER_EXCEPTION); } throw var2; } catch (ExceptionInInitializerError var3) { INITIALIZER_EXCEPTION = var3; throw var3; } } }
protected void writeTemplate(String templateName, Writer out) throws TemplateException, IOException { Configuration cfg = new Configuration(); // Specify the data source where the template files come from. cfg.setClassForTemplateLoading(TemplateTest.class, "/com/alvermont/terraj/stargen/templates/"); // Specify how templates will see the data model. This is an advanced topic... // but just use this: cfg.setObjectWrapper(new DefaultObjectWrapper()); DetailsFromTemplate dft = new DetailsFromTemplate(); Template temp = cfg.getTemplate(templateName); dft.processTemplate(temp, parent.planets, parent.star, out); }
protected void writeTemplate(String templateName, Writer out) throws TemplateException, IOException { Configuration cfg = new Configuration(); // Specify the data source where the template files come from. cfg.setDirectoryForTemplateLoading(templateFile.getParentFile()); // Specify how templates will see the data model. This is an advanced topic... // but just use this: cfg.setObjectWrapper(new DefaultObjectWrapper()); DetailsFromTemplate dft = new DetailsFromTemplate(); Template temp = cfg.getTemplate(templateName); dft.processTemplate(temp, parent.planets, parent.star, out); }
/** * Prepare the initial browser content template. * * @param resourceName * resource name to be loaded. * @param lang * language name * @return loaded template */ protected Template prepareTemplate(String resourceName, String lang) { String fullResourceName = "/html/" + resourceName + "_" + lang + ".html"; InputStream htmlResourceStream = Recorder.class.getResourceAsStream(fullResourceName); if (htmlResourceStream == null) { htmlResourceStream = Recorder.class.getResourceAsStream("/html/" + resourceName + ".html"); } try { loader.putTemplate(resourceName, IOUtils.toString(htmlResourceStream, "UTF-8")); Configuration freemarkerConfig = new Configuration(); freemarkerConfig.setTemplateLoader(loader); DefaultObjectWrapper objectWrapper = new DefaultObjectWrapper(); objectWrapper.setExposureLevel(DefaultObjectWrapper.EXPOSE_ALL); freemarkerConfig.setObjectWrapper(objectWrapper); return freemarkerConfig.getTemplate(resourceName); } catch (IOException e) { NoOp.noOp(); } finally { IOUtils.closeQuietly(htmlResourceStream); } return null; }
/** * Prepare a freemarker template for the given language. * * @param lang * language to be used in the template * @return prepared template */ private Template prepareTemplate(Language lang) { InputStream resourceAsStream = ProcessHTTPRecordingWithFreeMarker.class.getResourceAsStream("/template/" + lang.getTemplateName() + ".ftl"); try { loader.putTemplate(lang.getTemplateName(), IOUtils.toString(resourceAsStream)); Configuration freemarkerConfig = new Configuration(); freemarkerConfig.setTemplateLoader(loader); DefaultObjectWrapper objectWrapper = new DefaultObjectWrapper(); objectWrapper.setExposureLevel(DefaultObjectWrapper.EXPOSE_ALL); freemarkerConfig.setObjectWrapper(objectWrapper); return freemarkerConfig.getTemplate(lang.getTemplateName()); } catch (IOException e) { LOGGER.error("basic template load error", e); } finally { IOUtils.closeQuietly(resourceAsStream); } return null; }
private void executeScript(String templateScript, ObjectModel object) { if (StringUtils.isEmpty(templateScript)) { return; } try { Map<String, ObjectModel> model = Collections.singletonMap("object", object); Configuration cfg = new Configuration(); cfg.setObjectWrapper(new DefaultObjectWrapper()); Template t = new Template("templateScript", new StringReader(templateScript), cfg); Writer out = new StringWriter(); t.process(model, out); String transformedScript = out.toString(); log.info(transformedScript); qRunner.update(transformedScript); } catch (Exception e) { throw new RuntimeException(e); } }
private void createTemplateConfiguration(final CompositeConfiguration config, final File templatesPath) { templateCfg = new Configuration(); templateCfg.setDefaultEncoding(config.getString(Keys.RENDER_ENCODING)); try { templateCfg.setDirectoryForTemplateLoading(templatesPath); } catch (IOException e) { e.printStackTrace(); } templateCfg.setObjectWrapper(new DefaultObjectWrapper()); }
protected Configuration getFreemarkerConfiguration(RepoCtx ctx) { Configuration cfg = new Configuration(); cfg.setObjectWrapper(new DefaultObjectWrapper()); // custom template loader cfg.setTemplateLoader(new TemplateWebScriptLoader(ctx.getRepoEndPoint(), ctx.getTicket())); // TODO review i18n cfg.setLocalizedLookup(false); cfg.setIncompatibleImprovements(new Version(2, 3, 20)); cfg.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER); return cfg; }
public static File processTemplate(File template) throws IOException, TemplateException { Configuration config = new Configuration(); config.setDirectoryForTemplateLoading(template.getParentFile()); config.setObjectWrapper(new DefaultObjectWrapper()); config.setDefaultEncoding("UTF-8"); Template temp = config.getTemplate(template.getName()); String child = template.getName() + RandomStringUtils.randomAlphanumeric(8); File fileOutput = new File(template.getParentFile(), child); Writer fileWriter = new FileWriter(fileOutput); Map<Object, Object> currentSession = Thucydides.getCurrentSession(); temp.process(currentSession, fileWriter); return fileOutput; }
private File prepareFreemarkerTemplate(String filePath) throws IOException, TemplateException { File template = getFileFromResourcesByFilePath(filePath); Configuration config = new Configuration(); config.setDirectoryForTemplateLoading(template.getParentFile()); config.setObjectWrapper(new DefaultObjectWrapper()); config.setDefaultEncoding("UTF-8"); Template temp = config.getTemplate(template.getName()); String child = template.getName() + RandomStringUtils.randomAlphanumeric(8); File fileOutput = new File(template.getParentFile(), child); Writer fileWriter = new FileWriter(fileOutput); Map<Object, Object> currentSession = Thucydides.getCurrentSession(); temp.process(currentSession, fileWriter); return fileOutput; }
/** * 初始化模板配置 * * @param servletContext * javax.servlet.ServletContext * @param templateDir * 模板位置 */ public static void initConfig(ServletContext servletContext, String templateDir) { config.setLocale(Locale.CHINA); config.setDefaultEncoding("utf-8"); config.setEncoding(Locale.CHINA, "utf-8"); templateDir="WEB-INF/templates"; config.setServletContextForTemplateLoading(servletContext, templateDir); config.setObjectWrapper(new DefaultObjectWrapper()); }
@SuppressWarnings("rawtypes") @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { TemplateModel pValue = (TemplateModel) params.get("value"); SimpleScalar pVar = (SimpleScalar) params.get("var"); if (pVar == null) throw new IllegalArgumentException("The var parameter cannot be null in set-directive"); String var = pVar.getAsString(); Object value = null; if (pValue != null) { if (pValue instanceof StringModel) { value = ((StringModel) pValue).getWrappedObject(); } else if (pValue instanceof SimpleHash) { value = ((SimpleHash) pValue).toMap(); } else { value = DeepUnwrap.unwrap(pValue); } } else if (body != null) { StringWriter sw = new StringWriter(); try { body.render(sw); value = sw.toString().trim(); } finally { IOUtils.closeQuietly(sw); } } env.setVariable(var, DefaultObjectWrapper.getDefaultInstance().wrap(value)); }
@Async @Override public void sendMail(String to, Map<String, String> parameters, String template, String subject) { log.debug("sendMail() - to: " + to); MimeMessage message = mailSender.createMimeMessage(); try { String stringDir = MailServiceImpl.class.getResource("/templates/freemarker").getPath(); Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setDefaultEncoding("UTF-8"); File dir = new File(stringDir); cfg.setDirectoryForTemplateLoading(dir); cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_22)); StringBuffer content = new StringBuffer(); Template temp = cfg.getTemplate(template + ".ftl"); content.append(FreeMarkerTemplateUtils.processTemplateIntoString(temp, parameters)); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content.toString(), "text/html;charset=\"UTF-8\""); MimeMultipart multipart = new MimeMultipart("related"); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); message.setFrom(new InternetAddress(platformMailConfigurationProperties.getUser().getUsername(), platformMailConfigurationProperties.getUser().getName())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); mailSender.send(message); log.info("Message has been sent to: " + to); } catch (Exception e) { e.printStackTrace(); } }