下面列出了freemarker.template.Version#freemarker.cache.StringTemplateLoader 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* freemark处理文字
*
* @param input
* @param templateStr
* @return
*/
public static String freemarkerProcess(Map input, String templateStr) {
StringTemplateLoader stringLoader = new StringTemplateLoader();
String template = "content";
stringLoader.putTemplate(template, templateStr);
Configuration cfg = new Configuration();
cfg.setTemplateLoader(stringLoader);
try {
Template templateCon = cfg.getTemplate(template, "UTF-8");
StringWriter writer = new StringWriter();
templateCon.process(input, writer);
return writer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 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();
}
}
private boolean loadTemplate(String key) {
String content;
content = loadTemplateFromConfig(key);
if (content == null) {
content = loadTemplateFromDisk(key);
}
if (content == null) {
logger.error("gendoc parse key:" + key + " template not found!");
return false;
} else {
StringTemplateLoader stringTemplateLoader = (StringTemplateLoader) configuration.getTemplateLoader();
stringTemplateLoader.putTemplate(key, content);
return true;
}
}
private Template loadTemplate(String name) {
final Path path = ResourceLoaderUtils.getResourceAsPath(name);
try {
final byte[] encoded = Files.readAllBytes(path);
final String tempId = "REPORT";
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
stringTemplateLoader.putTemplate(tempId, new String(encoded, "UTF-8"));
this.cfg.setTemplateLoader(stringTemplateLoader);
return this.cfg.getTemplate(tempId);
} catch (IOException e) {
throw new RuntimeException("Error loading report HTML template '"+ name +"': " + e.getMessage(), e);
}
}
public static String process(String resource, String queryName, Map<String, Object> paramMap) throws Exception {
DynamicHql dynamicHql = loadResource(resource);
if (null == dynamicHql) {
logger.error( "no dynamic hql resource." );
throw new Exception( "no dynamic hql resource." );
}
String hql = "";
for (int i=0; i<dynamicHql.getQuery().size() && hql.length()<1; i++) {
Query queryObj = dynamicHql.getQuery().get(i);
if (!queryObj.getName().equals(queryName)) {
continue;
}
StringTemplateLoader templateLoader = new StringTemplateLoader();
templateLoader.putTemplate(TEMPLATE_ID, queryObj.getContent());
Configuration cfg = new Configuration( Configuration.VERSION_2_3_21 );
cfg.setTemplateLoader(templateLoader);
Template template = cfg.getTemplate(TEMPLATE_ID, Constants.BASE_ENCODING);
Writer out = new StringWriter();
template.process(paramMap, out);
hql = out.toString();
}
if (StringUtils.isBlank(hql)) {
logger.warn( "hql is blank." );
}
return hql;
}
private static void initStringTemplateLoader(StringTemplateLoader loader) {
// text 文本消息
loader.putTemplate(OutTextMsg.class.getSimpleName(), OutTextMsg.TEMPLATE);
// news 图文消息
loader.putTemplate(OutNewsMsg.class.getSimpleName(), OutNewsMsg.TEMPLATE);
// image 图片消息
loader.putTemplate(OutImageMsg.class.getSimpleName(), OutImageMsg.TEMPLATE);
//voice 语音消息
loader.putTemplate(OutVoiceMsg.class.getSimpleName(), OutVoiceMsg.TEMPLATE);
// video 视频消息
loader.putTemplate(OutVideoMsg.class.getSimpleName(), OutVideoMsg.TEMPLATE);
// music 音乐消息
loader.putTemplate(OutMusicMsg.class.getSimpleName(), OutMusicMsg.TEMPLATE);
// 转发多客服消息
loader.putTemplate(OutCustomMsg.class.getSimpleName(), OutCustomMsg.TEMPLATE);
}
/**
* 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);
}
}
/** Processes template contents against the given {@link TemplateHashModel}. */
public static String processTemplateContents(String templateContents, final TemplateHashModel substitutions) {
try {
Configuration cfg = new Configuration();
StringTemplateLoader templateLoader = new StringTemplateLoader();
templateLoader.putTemplate("config", templateContents);
cfg.setTemplateLoader(templateLoader);
Template template = cfg.getTemplate("config");
// TODO could expose CAMP '$brooklyn:' style dsl, based on template.createProcessingEnvironment
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Writer out = new OutputStreamWriter(baos);
template.process(substitutions, out);
out.flush();
return new String(baos.toByteArray());
} catch (Exception e) {
log.warn("Error processing template (propagating): "+e, e);
log.debug("Template which could not be parsed (causing "+e+") is:"
+ (Strings.isMultiLine(templateContents) ? "\n"+templateContents : templateContents));
throw Exceptions.propagate(e);
}
}
protected freemarker.template.Template getFreemarkerTemplate() {
try {
String templateContent = IOUtils.toString(reportTemplate.getDocumentContent(), StandardCharsets.UTF_8);
StringTemplateLoader stringLoader = new StringTemplateLoader();
stringLoader.putTemplate(reportTemplate.getDocumentName(), templateContent);
Configuration fmConfiguration = new Configuration();
fmConfiguration.setTemplateLoader(stringLoader);
fmConfiguration.setDefaultEncoding("UTF-8");
freemarker.template.Template htmlTemplate = fmConfiguration.getTemplate(reportTemplate.getDocumentName());
htmlTemplate.setObjectWrapper(objectWrapper);
return htmlTemplate;
} catch (Exception e) {
throw wrapWithReportingException("An error occurred while creating freemarker template", e);
}
}
@Override
public String format(String template, Map<String, Object> env) {
String key = md5Key(template);
StringTemplateLoader loader = (StringTemplateLoader) dynamicConfig.getTemplateLoader();
loader.putTemplate(key, template);
return process(dynamicConfig, key, env);
}
@Bean
public freemarker.template.Configuration dynamicConfig() {
freemarker.template.Configuration configuration =
new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_25);
configuration.setDateTimeFormat("UTF-8");
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);
configuration.setClassicCompatible(true);
configuration.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
configuration.setTemplateLoader(new StringTemplateLoader());
return configuration;
}
@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);
}
private TemplateParse(){
configuration = new Configuration(Configuration.getVersion());
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
configuration.setTemplateLoader(stringTemplateLoader);
configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.getVersion()));
configuration.setDefaultEncoding("UTF-8");
initTemplateCache();
}
/**
* FreeMarker configuration for loading the specified template directly from a String
*
* @param path Pseudo Path to the template
* @param template Template content
*
* @return FreeMarker configuration
*/
protected Configuration getStringConfig(String path, String template)
{
Configuration config = new Configuration();
// setup template cache
config.setCacheStorage(new MruCacheStorage(2, 0));
// use our custom loader to load a template directly from a String
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
stringTemplateLoader.putTemplate(path, template);
config.setTemplateLoader(stringTemplateLoader);
// use our custom object wrapper that can deal with QNameMap objects directly
config.setObjectWrapper(qnameObjectWrapper);
// rethrow any exception so we can deal with them
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
// set default template encoding
if (defaultEncoding != null)
{
config.setDefaultEncoding(defaultEncoding);
}
config.setIncompatibleImprovements(new Version(2, 3, 20));
config.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);
return config;
}
public StructTemplate() {
this.configuration = new Configuration(Configuration.getVersion());
this.loader = new StringTemplateLoader();
this.configuration.setTemplateLoader(this.loader);
this.configuration.setDefaultEncoding("UTF-8");
this.configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
this.configuration.setLogTemplateExceptions(false);
this.configuration.setObjectWrapper(new ConnectObjectWrapper());
}
@Override
public Single<Email> reloadEmail(Email email) {
final String templateName = getTemplateName(email);
if (email.isEnabled()) {
reloadTemplate(templateName + TEMPLATE_SUFFIX, email.getContent());
emailTemplates.put(templateName, email);
} else {
// remove email who has been disabled
emailTemplates.remove(templateName);
((StringTemplateLoader) templateLoader).removeTemplate(templateName + TEMPLATE_SUFFIX);
}
return Single.just(email);
}
@Override
public Completable deleteEmail(String email) {
Optional<Email> emailOptional = emailTemplates.values().stream().filter(email1 -> email.equals(email1.getId())).findFirst();
if (emailOptional.isPresent()) {
Email emailToRemove = emailOptional.get();
emailTemplates.remove(getTemplateName(emailToRemove));
((StringTemplateLoader) templateLoader).removeTemplate(getTemplateName(emailToRemove) + TEMPLATE_SUFFIX);
}
return Completable.complete();
}
private static String processTemplate(String resource, Map<String, Object> params) throws Exception {
StringTemplateLoader templateLoader = new StringTemplateLoader();
templateLoader.putTemplate("sysTemplate", resource);
Configuration cfg = new Configuration( Configuration.VERSION_2_3_21 );
cfg.setTemplateLoader(templateLoader);
Template template = cfg.getTemplate("sysTemplate", Constants.BASE_ENCODING);
Writer out = new StringWriter();
template.process(params, out);
return out.toString();
}
/**
* 單獨提供單處理 template 取出結果
*
* @param name
* @param classLoader
* @param templateResource
* @param parameter
* @return
* @throws Exception
*/
public static String processTemplate(String name, ClassLoader classLoader, String templateResource,
Map<String, Object> parameter) throws Exception {
StringTemplateLoader templateLoader = new StringTemplateLoader();
templateLoader.putTemplate("resourceTemplate", getResourceSrc(classLoader, templateResource) );
Configuration cfg = new Configuration( Configuration.VERSION_2_3_21 );
cfg.setTemplateLoader(templateLoader);
Template template = cfg.getTemplate("resourceTemplate", Constants.BASE_ENCODING);
Writer out = new StringWriter();
template.process(parameter, out);
return out.toString();
}
public static String generatorResource(Class<?> c, String type, String metaInfFile, Map<String, Object> params) throws Exception {
StringTemplateLoader templateLoader = new StringTemplateLoader();
templateLoader.putTemplate("resourceTemplate", getResourceSrc(c, type, metaInfFile) );
Configuration cfg = new Configuration( Configuration.VERSION_2_3_21 );
cfg.setTemplateLoader(templateLoader);
Template template = cfg.getTemplate("resourceTemplate", Constants.BASE_ENCODING);
Writer out = new StringWriter();
template.process(params, out);
return out.toString();
}
private static Configuration initFreeMarkerConfiguration() {
Configuration config = new Configuration();
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
initStringTemplateLoader(stringTemplateLoader);
config.setTemplateLoader(stringTemplateLoader);
// 模板缓存更新时间,对于OutMsg xml 在类文件中的模板来说已有热加载保障了更新
config.setTemplateUpdateDelay(999999);
// - Set an error handler that prints errors so they are readable with
// a HTML browser.
// config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
// - Use beans wrapper (recommmended for most applications)
config.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
// - Set the default charset of the template files
config.setDefaultEncoding(encoding); // config.setDefaultEncoding("ISO-8859-1");
// - Set the charset of the output. This is actually just a hint, that
// templates may require for URL encoding and for generating META element
// that uses http-equiv="Content-type".
config.setOutputEncoding(encoding); // config.setOutputEncoding("UTF-8");
// - Set the default locale
config.setLocale(Locale.getDefault() /* Locale.CHINA */ ); // config.setLocale(Locale.US);
config.setLocalizedLookup(false);
// 去掉int型输出时的逗号, 例如: 123,456
// config.setNumberFormat("#"); // config.setNumberFormat("0"); 也可以
config.setNumberFormat("#0.#####");
config.setDateFormat("yyyy-MM-dd");
config.setTimeFormat("HH:mm:ss");
config.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
return config;
}
public void executeWorkItem(WorkItem workItem,
WorkItemManager workItemManager) {
try {
RequiredParameterValidator.validate(this.getClass(),
workItem);
Map<String, Object> results = new HashMap<>();
String templateXHTML = (String) workItem.getParameter("TemplateXHTML");
String pdfName = (String) workItem.getParameter("PDFName");
if (pdfName == null || pdfName.isEmpty()) {
pdfName = "generatedpdf";
}
Configuration cfg = new Configuration(freemarker.template.Configuration.VERSION_2_3_26);
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
StringTemplateLoader stringLoader = new StringTemplateLoader();
stringLoader.putTemplate("pdfTemplate",
templateXHTML);
cfg.setTemplateLoader(stringLoader);
StringWriter stringWriter = new StringWriter();
Template pdfTemplate = cfg.getTemplate("pdfTemplate");
pdfTemplate.process(workItem.getParameters(),
stringWriter);
resultXHTML = stringWriter.toString();
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(resultXHTML);
renderer.layout();
Document document = new DocumentImpl();
document.setName(pdfName + ".pdf");
document.setLastModified(new Date());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
renderer.createPDF(baos);
document.setContent(baos.toByteArray());
results.put(RESULTS_VALUE,
document);
workItemManager.completeWorkItem(workItem.getId(),
results);
} catch (Exception e) {
logger.error(e.getMessage());
handleException(e);
}
}
private void reloadTemplate(String templateName, String content) {
((StringTemplateLoader) templateLoader).putTemplate(templateName, content, System.currentTimeMillis());
configuration.clearTemplateCache();
}
public static String processTemplate(String templateStr, Map<String, ?> parameterValues) {
StringTemplateLoader templateLoader = new StringTemplateLoader();
templateLoader.putTemplate("template", templateStr);
return __processTemplate(templateLoader, "template", parameterValues);
}