下面列出了freemarker.template.Version#freemarker.template.Template 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void _convertFreeMarkerTemplate(String name, byte[] template, Map<String,Object> dynamicMap, Writer writer) throws TrasformazioneException {
try {
// ** Aggiungo utility per usare metodi statici ed istanziare oggetti
// statici
BeansWrapper wrapper = new BeansWrapper(Configuration.VERSION_2_3_23);
TemplateModel classModel = wrapper.getStaticModels();
dynamicMap.put(Costanti.MAP_CLASS_LOAD_STATIC, classModel);
// newObject
dynamicMap.put(Costanti.MAP_CLASS_NEW_INSTANCE, new freemarker.template.utility.ObjectConstructor());
// ** costruisco template
Template templateFTL = TemplateUtils.buildTemplate(name, template);
templateFTL.process(dynamicMap, writer);
writer.flush();
}catch(Exception e) {
throw new TrasformazioneException(e.getMessage(),e);
}
}
public static Template getTemplate(File templateFile) throws IOException {
Configuration cfg = new Configuration(Configuration.getVersion());
cfg.setTemplateLoader(new URLTemplateLoader() {
@Override
protected URL getURL(String name) {
try {
return new URL(name);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}
});
cfg.setDefaultEncoding("UTF-8");
cfg.setLocalizedLookup(false);
Template template = cfg.getTemplate(templateFile.toURI().toURL().toExternalForm());
return template;
}
/**
* freemarker渲染html
*/
public static <T> String freeMarkerRender(T data, String htmlTmp) {
Writer out = new StringWriter();
try {
// 获取模板,并设置编码方式
Template template = freemarkerCfg.getTemplate(htmlTmp);
template.setEncoding("UTF-8");
// 合并数据模型与模板,将合并后的数据和模板写入到流中,这里使用的字符流
template.process(data, out);
out.flush();
return out.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return null;
}
/**
* 发送带有附件的邮件
*
* @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();
}
}
/**
* Generates output file with release notes using FreeMarker.
*
* @param variables the map which represents template variables.
* @param outputFile output file.
* @param templateFileName the optional file name of the template.
* @param defaultResource the resource file name to use if no file name was given.
* @throws IOException if I/O error occurs.
* @throws TemplateException if an error occurs while generating freemarker template.
*/
public static void generateWithFreemarker(Map<String, Object> variables, String outputFile,
String templateFileName, String defaultResource) throws IOException, TemplateException {
final Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
configuration.setDefaultEncoding("UTF-8");
configuration.setLocale(Locale.US);
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
configuration.setNumberFormat("0.######");
final StringTemplateLoader loader = new StringTemplateLoader();
loader.putTemplate(TEMPLATE_NAME, loadTemplate(templateFileName, defaultResource));
configuration.setTemplateLoader(loader);
final Template template = configuration.getTemplate(TEMPLATE_NAME);
try (Writer fileWriter = new OutputStreamWriter(
new FileOutputStream(outputFile), StandardCharsets.UTF_8)) {
template.process(variables, fileWriter);
}
}
@Override
public String render(ModelAndView modelAndView) {
try {
Template template = configuration.getTemplate(provider.layout(), "utf-8");
Object model = modelAndView.getModel();
if (model == null) {
model = Collections.emptyMap();
}
if (model instanceof Map) {
Map<String, Object> context = initialContextProvider.getContext((Map) model, controller, modelAndView.getViewName());
StringWriter writer = new StringWriter();
Object meta = context.get("meta");
context.put("meta", GSON.toJson(meta));
template.process(context, writer);
return writer.toString();
} else {
throw new IllegalArgumentException("modelAndView must be of type java.util.Map");
}
} catch (IOException | TemplateException e) {
throw new IllegalArgumentException(e);
}
}
/**
* ���������
*/
public String getText(String templateId, Map<Object, Object> parameters) {
@SuppressWarnings("deprecation")
Configuration configuration = new Configuration();
configuration.setTemplateLoader(new ClassTemplateLoader(FreemarkerEmailTemplate.class, TEMPLATE_PATH));
configuration.setDefaultEncoding("gbk");
//configuration.setEncoding(Locale.getDefault(), "UTF-8");
configuration.setDateFormat("yyyy-MM-dd HH:mm:ss");
String templateFile = templateId + SUFFIX;
try {
Template template = TEMPLATE_CACHE.get(templateFile);
if (template == null) {
template = configuration.getTemplate(templateFile);
TEMPLATE_CACHE.put(templateFile, template);
}
StringWriter stringWriter = new StringWriter();
parameters.put("webip", WEB_IP);
parameters.put("webport", WEB_PORT);
template.process(parameters, stringWriter);
return stringWriter.toString();
} catch (Exception e) {
LogUtil.APP.error("��ȡ�ʼ�ģ���������ó����쳣",e);
throw new RuntimeException(e);
}
}
/**
* 解析ftl
* @param tplName 模板名
* @param encoding 编码
* @param paras 参数
* @return
*/
public String parseTemplate(String tplName, String encoding,
Map<String, Object> paras) {
try {
StringWriter swriter = new StringWriter();
Template mytpl = null;
mytpl = _tplConfig.getTemplate(tplName, encoding);
mytpl.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
mytpl.setDateFormat("yyyy-MM-dd");
mytpl.setTimeFormat("HH:mm:ss");
mytpl.process(paras, swriter);
return swriter.toString();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
/**
* Gets a (String)TemplateInvoker with compiled Freemarker template for the attribute
* content inline template.
* <p>
* TODO: decide cache... can make CmsAttributeTemplate-specific cache (by id or so, faster) but
* may get memory duplication with #interpretStd calls (cached by body, because no id/name avail)
* -> could do both at once maybe? share the Template instance between 2 cache...
* TODO: subject to refactor/move
* TODO?: FUTURE: this does NOT wrap the TemplateInvoker in a TemplateModel for time being...
* we will rely on the default ObjectWrapper(s) to wrap the StringTemplateInvoker
* in a freemarker StringModel (BeanModel) which renders throughs the ?string built-in
* or string evaluation.
*/
public static TemplateInvoker getStringTemplateInvokerForContent(String tmplStr, Map<String, Object> ctxVars, CmsPageContext pageContext) throws TemplateException, IOException {
Configuration config = CmsRenderTemplate.TemplateRenderer.getDefaultCmsConfig();
// TODO: REVIEW: cache selection is a problem...
// instead of by template body we could cache by some derivative unique name
// derived from the CmsAttributeTemplate ID (maybe?)
// would likely be much faster
UtilCache<String, Template> cache = TemplateSource.getTemplateInlineSelfCacheForConfig(config, null);
if (cache == null) {
Debug.logWarning("Cms: could not determine"
+ " an inline template cache to use; not using cache", module);
}
TemplateSource templateSource = TemplateSource.getForInline(null, tmplStr, cache, config, true);
// NOTE: must get StringInvoker so BeansWrapper's StringModel can invoke toString()
// NOTE: context parameters could be passed to the template using InvokeOptions.ctxVars...
// but not yet needed
TemplateInvoker invoker = TemplateInvoker.getInvoker(templateSource, new InvokeOptions(null, null, null, ctxVars, false), null);
return invoker;
}
private void generateEditionsTemplate(Set<MagicEdition> eds, MagicCollection col)throws IOException, SQLException, TemplateException {
Template cardTemplate = cfg.getTemplate("page-ed.html");
Map<String,Object> rootEd = new HashMap<>();
rootEd.put("cols", cols);
rootEd.put("editions", eds);
rootEd.put("col", col);
rootEd.put("colName", col.getName());
for (MagicEdition ed : eds) {
rootEd.put("cards", MTGControler.getInstance().getEnabled(MTGDao.class).listCardsFromCollection(col, ed));
rootEd.put("edition", ed);
FileWriter out = new FileWriter(
Paths.get(dest, "page-ed-" + col.getName() + "-" + ed.getId() + ".htm").toFile());
cardTemplate.process(rootEd, out);
}
}
/**
* 解析ftl
*
* @param tplContent 模板内容
* @param paras 参数
* @return String 模板解析后内容
*/
public static String parseTemplateContent(String tplContent,
Map<String, Object> paras) {
try {
StringWriter swriter = new StringWriter();
if (stringTemplateLoader.findTemplateSource("sql_" + tplContent.hashCode()) == null) {
stringTemplateLoader.putTemplate("sql_" + tplContent.hashCode(), tplContent);
}
Template mytpl = _sqlConfig.getTemplate("sql_" + tplContent.hashCode(), ENCODE);
if (paras.containsKey(MINI_DAO_FORMAT)) {
throw new RuntimeException("DaoFormat 是 minidao 保留关键字,不允许使用 ,请更改参数定义!");
}
paras.put(MINI_DAO_FORMAT, new SimpleFormat());
mytpl.process(paras, swriter);
String sql = getSqlText(swriter.toString());
paras.remove(MINI_DAO_FORMAT);
return sql;
} catch (Exception e) {
log.error(e.getMessage(), e.fillInStackTrace());
log.error("发送一次的模板key:{ " + tplContent + " }");
//System.err.println(e.getMessage());
//System.err.println("模板内容:{ "+ tplContent +" }");
throw new RuntimeException("解析SQL模板异常");
}
}
/**
* Renders source code by using Freemarker template engine.
*/
public static String render(String templatePath, RenderingData data) throws IOException, TemplateException {
Configuration config = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
StringTemplateLoader templateLoader = new StringTemplateLoader();
String source;
try (InputStream is = ResourceReader.getResourceAsStream(templatePath);
BufferedReader buffer = new BufferedReader(new InputStreamReader(is))) {
source = buffer.lines().collect(Collectors.joining("\n"));
}
templateLoader.putTemplate("template", source);
config.setTemplateLoader(templateLoader);
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
config.setObjectWrapper(new BeansWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
config.setWhitespaceStripping(true);
try (Writer writer = new java.io.StringWriter()) {
Template template = config.getTemplate("template");
template.process(data, writer);
return writer.toString();
}
}
public void emit(PubsubType pubsubType) throws ZserioEmitException
{
try
{
Template tpl = cfg.getTemplate("doc/pubsub.html.ftl");
setCurrentFolder(CONTENT_FOLDER);
openOutputFileFromType(pubsubType);
tpl.process(new PubsubTemplateData(getExpressionFormatter(), pubsubType, outputPath,
withSvgDiagrams), writer);
}
catch (Throwable exception)
{
throw new ZserioEmitException(exception.getMessage());
}
finally
{
if (writer != null)
writer.close();
}
}
protected void processThroughFreeMarker(String testString,
String expectedResult)
{
try
{
Configuration c = new Configuration(Configuration.VERSION_2_3_28);
Template t = new Template("test", testString, c);
StringWriter sw = new StringWriter();
BufferedWriter bw = new BufferedWriter(sw);
Map<String, Object> input = OutputDB.buildDataModel(id);
t.process(input, bw);
String s = sw.getBuffer().toString();
assertEquals(expectedResult, s);
}
catch (IOException | TemplateException e)
{
e.printStackTrace();
fail(e.getLocalizedMessage());
}
}
/**
* 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.");
}
private String doProcess(final String name,
final String source,
final Context context,
final Map<String, String> params)
throws IOException, TemplateException {
final Template template = new Template(name, source, this.configuration);
final StringWriter stringWriter = new StringWriter();
// pass in context
final Map<String, Object> model = new HashMap<>();
model.put("context", context);
model.put("params", params);
// process the template
template.process(model, stringWriter);
return stringWriter.toString();
}
public static boolean applyTemplate(File sourceTemplate, File destinationFile, Map<?, ?> data) throws IOException, TemplateException{
boolean success = false;
// Console output
try ( BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destinationFile), Charset.forName("UTF-8"))) ) {
// Process the template file using the data in the "data" Map
final Configuration cfg = new Configuration( new Version("2.3.23"));
cfg.setDirectoryForTemplateLoading(sourceTemplate.getParentFile());
// Load template from source folder
final Template template = cfg.getTemplate(sourceTemplate.getName());
template.process(data, fw);
success = true;
}catch (Exception e) {
logger.error("Error reading FreeMarker template", e);
}
return success;
}
public String createDroolRule(Rule rule) throws TemplateException, IOException {
try {
Template temp = cfg.getTemplate(templateName);
Writer out = new StringWriter();
temp.process(createMap(rule), out);
return out.toString();
} catch (IOException iE) {
logger.error("Problem getting rule template file." + iE.getMessage());
throw iE;
} catch (TemplateException tE) {
logger.error("Problem writing Drool rule." + tE.getMessage());
throw tE;
} catch (Exception e) {
logger.error("Problem creating rule: " + e.getMessage());
throw e;
}
}
/**
* 解析ftl模板
*
* @param tplName 模板名
* @param paras 参数
* @return
*/
public static String parseTemplate(String tplName, Map<String, Object> paras) {
try {
log.debug(" minidao sql templdate : " + tplName);
StringWriter swriter = new StringWriter();
Template mytpl = _tplConfig.getTemplate(tplName, ENCODE);
if (paras.containsKey(MINI_DAO_FORMAT)) {
throw new RuntimeException("DaoFormat 是 minidao 保留关键字,不允许使用 ,请更改参数定义!");
}
paras.put(MINI_DAO_FORMAT, new SimpleFormat());
mytpl.process(paras, swriter);
String sql = getSqlText(swriter.toString());
paras.remove(MINI_DAO_FORMAT);
return sql;
} catch (Exception e) {
log.error(e.getMessage(), e.fillInStackTrace());
log.error("发送一次的模板key:{ " + tplName + " }");
//System.err.println(e.getMessage());
//System.err.println("模板名:{ "+ tplName +" }");
throw new RuntimeException("解析SQL模板异常");
}
}
/**
* 判断模板是否存在
*
* @throws Exception
*/
public static boolean isExistTemplate(String tplName) throws Exception {
try {
Template mytpl = _tplConfig.getTemplate(tplName, "UTF-8");
if (mytpl == null) {
return false;
}
} catch (Exception e) {
//update-begin--Author:scott Date:20180320 for:解决问题 - 错误提示sql文件不存在,实际问题是sql freemarker用法错误-----
if (e instanceof ParseException) {
log.error(e.getMessage(), e.fillInStackTrace());
throw new Exception(e);
}
log.debug("----isExistTemplate----" + e.toString());
//update-end--Author:scott Date:20180320 for:解决问题 - 错误提示sql文件不存在,实际问题是sql freemarker用法错误------
return false;
}
return true;
}
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();
}
}
/**
* 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);
}
}
/**
* 解析ftl
* @param tplName 模板名
* @param encoding 编码
* @param paras 参数
* @return
*/
public String parseTemplate(String tplName, String encoding,
Map<String, Object> paras) {
try {
StringWriter swriter = new StringWriter();
Template mytpl = null;
mytpl = _tplConfig.getTemplate(tplName, encoding);
mytpl.process(paras, swriter);
return swriter.toString();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
@Override
public void aggregate(final Configuration configuration,
final List<LaunchResults> launchesResults,
final Path outputDirectory) throws IOException {
final FreemarkerContext context = configuration.requireContext(FreemarkerContext.class);
final Path exportFolder = Files.createDirectories(outputDirectory.resolve(Constants.EXPORT_DIR));
final Path mailFile = exportFolder.resolve("mail.html");
try (BufferedWriter writer = Files.newBufferedWriter(mailFile)) {
final Template template = context.getValue().getTemplate("mail.html.ftl");
template.process(new HashMap<>(), writer);
} catch (TemplateException e) {
LOGGER.error("Could't write mail file", e);
}
}
/**
* 获取渲染后的文本
* @param name
* 相对路径下的模板
* @param data
* 数据
* @param out
* 输出流
*/
public static String renderTemplate(String name, Object data) {
String result = null;
try {
Template template = cfg.getTemplate(name);
StringWriter out = new StringWriter();
template.process(data, out);
result = out.toString();
out.close();
return result;
} catch (Exception e) {
throw new ServiceException(e);
}
}
private static void genServiceInterface(String className,
String classComment,
String resourcePath,
GeneratorConfig generatorConfig) {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("className", className);
paramMap.put("classComment", classComment);
paramMap.put("sysTime", new Date());
paramMap.put("packageName", generatorConfig.getPackageName());
Version version = new Version("2.3.27");
Configuration configuration = new Configuration(version);
try {
URL url = ServiceGenerator.class.getClassLoader().getResource(resourcePath);
configuration.setDirectoryForTemplateLoading(new File(url.getPath()));
configuration.setObjectWrapper(new DefaultObjectWrapper(version));
String filePath = generatorConfig.getSrcBasePath() + "service//";
String savePath = filePath + className + "Service.java";
File dirPath = new File(filePath);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
try (FileWriter fileWriter = new FileWriter(new File(savePath))) {
Template template = configuration.getTemplate("service.ftl");
template.process(paramMap, fileWriter);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void createServiceImplJpa(Project project, VirtualFile packageDir, Service service) {
try {
VirtualFile virtualFile = packageDir.createChildData(project, service.getSimpleName() + "Impl.java");
StringWriter sw = new StringWriter();
Template template = freemarker.getTemplate("service_impl.ftl");
template.process(service, sw);
virtualFile.setBinaryContent(sw.toString().getBytes(CrudUtils.DEFAULT_CHARSET));
CrudUtils.addWaitOptimizeFile(virtualFile);
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendEmailNotification(final EmailNotification emailNotification) {
if (enabled && emailNotification.getTo() != null && emailNotification.getTo().length > 0) {
try {
final MimeMessageHelper mailMessage = new MimeMessageHelper(mailSender.createMimeMessage(), true, StandardCharsets.UTF_8.name());
final Template template = freemarkerConfiguration.getTemplate(emailNotification.getTemplate());
String content = processTemplateIntoString(template, emailNotification.getParams());
content = content.replaceAll("<br />", "<br />");
final String from = isNull(emailNotification.getFrom()) || emailNotification.getFrom().isEmpty()
? defaultFrom
: emailNotification.getFrom();
if (isEmpty(emailNotification.getFromName())) {
mailMessage.setFrom(from);
} else {
mailMessage.setFrom(from, emailNotification.getFromName());
}
mailMessage.setTo(emailNotification.getTo());
if (emailNotification.isCopyToSender() && emailNotification.getFrom() != null) {
mailMessage.setBcc(emailNotification.getFrom());
}
if (emailNotification.getBcc() != null && emailNotification.getBcc().length > 0) {
mailMessage.setBcc(emailNotification.getBcc());
}
mailMessage.setSubject(format(subject, emailNotification.getSubject()));
final String html = addResourcesInMessage(mailMessage, content);
LOGGER.debug("Sending an email to: {}\nSubject: {}\nMessage: {}",
emailNotification.getTo(), emailNotification.getSubject(), html);
mailSender.send(mailMessage.getMimeMessage());
} catch (final Exception ex) {
LOGGER.error("Error while sending email notification", ex);
throw new TechnicalManagementException("Error while sending email notification", ex);
}
}
}
public TemplateManager(String templateName, String templateBody) {
this();
try {
template = new Template(templateName, templateBody, cfg);
} catch (IOException e) {
throw new RuntimeException("Template Exception", e);
}
}
public void process(String name, Map<String, Object> model, OutputStream output) {
try {
Configuration config = new Configuration();
config.setClassForTemplateLoading(getClass(), "");
config.setObjectWrapper(new DefaultObjectWrapper());
Template templateEngine = config.getTemplate(name);
templateEngine.process(model, new PrintWriter(output));
} catch (Throwable t) {
throw new RuntimeException("Error processing template: " + t.getClass().getName(), t);
}
}