下面列出了freemarker.template.Template#process ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 执行创建文件
*
* @param content
* 模板所需要的上下文
* @param templeteName
* 模板的名字 示例:Entity.ftl
* @param projectPath
* 生成的项目路径 示例:D://create
* @param packageName
* 包名 示例:com.szmirren
* @param fileName
* 文件名 示例:Entity.java
* @param codeFormat
* 输出的字符编码格式 示例:UTF-8
* @throws Exception
*/
public static void createFile(GeneratorContent content, String templeteName, String projectPath, String packageName, String fileName,
String codeFormat, boolean isOverride) throws Exception {
String outputPath = projectPath + "/" + packageName.replace(".", "/") + "/";
if (!isOverride) {
if (Files.exists(Paths.get(outputPath + fileName))) {
LOG.debug("设置了文件存在不覆盖,文件已经存在,忽略本文件的创建");
return;
}
}
Configuration config = new Configuration(Configuration.VERSION_2_3_23);
String tempPath = Paths.get(Constant.TEMPLATE_DIR_NAME).toFile().getName();
config.setDirectoryForTemplateLoading(new File(tempPath));
config.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
config.setDefaultEncoding("utf-8");
Template template = config.getTemplate(templeteName);
Map<String, Object> item = new HashMap<>();
item.put("content", content);
if (!Files.exists(Paths.get(outputPath))) {
Files.createDirectories(Paths.get(outputPath));
}
try (Writer writer = new OutputStreamWriter(new FileOutputStream(outputPath + fileName), codeFormat)) {
template.process(item, writer);
}
}
/**
* 获取渲染后的文本
* @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);
}
}
public static String getPage(String filename, Map<String, Object> data) {
Writer stream = new StringWriter();
try {
Template template = CFG.getTemplate(HTML_DIR + File.separator + filename);
template.process(data, stream);
} catch (IOException | TemplateException e) {
e.printStackTrace();
}
return stream.toString();
}
/**
* Renders a template.
* @param resp
* @param templateName
* @param root
* @throws IOException
*/
protected void render(
HttpServletResponse resp, String templateName, Map<String, Object> root)
throws IOException {
Template t = fileMarkerCfg.getTemplate(templateName);
resp.setContentType("text/html; charset=utf-8");
Writer out = resp.getWriter();
try {
t.process(root, out);
} catch (TemplateException e) {
throw new RuntimeException(e);
}
}
/**
* process Template Into String
*
*/
public String processTemplateIntoString(Template template, Object model)
throws IOException, TemplateException {
StringWriter result = new StringWriter();
template.process(model, result);
return result.toString();
}
/**
* Generates HQL which is used to create the Hive table, and creates an HDFS equivalent.
*/
private static void generateOccurrenceAvroTableHQL(Configuration cfg, File outDir) throws IOException, TemplateException {
try (FileWriter out = new FileWriter(new File(outDir, "create-occurrence-avro.q"))) {
Template template = cfg.getTemplate("configure/create-occurrence-avro.ftl");
Map<String, Object> data = ImmutableMap.of(FIELDS, OccurrenceHDFSTableDefinition.definition());
template.process(data, out);
}
}
private void generateFileByTemplate(final String templateName, File file) throws Exception {
HashMap<String, Object> dataMap = new HashMap<>(20);
Template template = FreeMarkerTemplateUtils.getTemplate(templateName);
FileOutputStream fos = new FileOutputStream(file);
dataMap.put("table_name", changeTableName);
dataMap.put("package_name", packageName);
dataMap.put("feign_package_name", feignPackageName);
dataMap.put("author", AUTHOR);
dataMap.put("date", CURRENT_DATE);
dataMap.put("feign_service_name", feignServiceName);
Writer out = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8), 10240);
template.process(dataMap, out);
}
public String html() throws IOException, TemplateException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
cfg.setDirectoryForTemplateLoading(new File(templateDirectory));
cfg.setDefaultEncoding(StandardCharsets.UTF_8.toString());
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
cfg.setWrapUncheckedExceptions(true);
cfg.setFallbackOnNullLoopVariable(false);
Template temp = cfg.getTemplate(templateFile);
try (Writer output = new StringWriter()) {
temp.process(staxTransformer.getMap(), output);
return output.toString();
}
}
/**
* Generates the Hive query file used for CSV downloads.
*/
private static void generateSimpleCsvQueryHQL(Configuration cfg, File outDir) throws IOException, TemplateException {
try (FileWriter out = new FileWriter(new File(outDir, "execute-simple-csv-query.q"))) {
Template template = cfg.getTemplate("simple-csv-download/execute-simple-csv-query.ftl");
Map<String, Object> data = ImmutableMap.of(FIELDS, HIVE_QUERIES.selectSimpleDownloadFields(true).values());
template.process(data, out);
}
}
public static void processTemplate(Template template, Map model, File outputFile,String encoding) throws IOException, TemplateException {
@Cleanup
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
@Cleanup
Writer out = new BufferedWriter(new OutputStreamWriter(fileOutputStream,encoding));
template.process(model,out);
}
public static String getPage(String filename, Map<String, Object> data) {
Writer stream = new StringWriter();
try {
Template template = CFG.getTemplate(HTML_DIR + File.separator + filename);
template.process(data, stream);
} catch (IOException | TemplateException e) {
e.printStackTrace();
}
return stream.toString();
}
public static void generateDaoGetMethod(boolean isReturnList, String beanNameRegex, String tableName, String attrs) throws IOException, TemplateException {
File dir = resourceLoader.getResource("classpath:/tmpl/code").getFile();
Bean bean = new Bean();
bean.setTableName(tableName);
String[] attrArray = attrs.replace(", ", ",").split(",");
for (String attr : attrArray) {
try {
String[] splits = attr.split(" ");
Property property = new Property();
property.setType(new PropertyType(splits[0]));
property.setName(splits[1]);
bean.addProperty(property);
} catch (Exception e) {
throw new RuntimeException("attr的格式应为$Javatype$ $attrName$");
}
}
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(dir);
cfg.setObjectWrapper(new DefaultObjectWrapper());
Template temp = cfg.getTemplate(isReturnList ? "daoGetForListMethodTmpl.ftl" : "daoGetForObjMethodTmpl.ftl");
Map dataMap = new HashMap();
dataMap.put("bean", bean);
if (beanNameRegex != null) {
// 根据用户设置修正beanName
Pattern pattern = Pattern.compile(beanNameRegex);
Matcher matcher = pattern.matcher(bean.getTableName());
matcher.find();
String group = matcher.group(matcher.groupCount());
bean.setName(StringUtils.uncapitalizeCamelBySeparator(group, "_"));
}
Writer out = new OutputStreamWriter(System.out);
temp.process(dataMap, out);
out.flush();
out.close();
}
private String process(Configuration config, String key, Map<String, Object> env) {
try {
Template template = config.getTemplate(key, "utf-8");
StringWriter writer = new StringWriter();
template.process(env, writer);
return writer.toString();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
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 populateGradleScriptWithData(final File targetFile, final Map<String, String> gradleScriptData) throws IOException, TemplateException {
final Template gradleScriptTemplate = configuration.getTemplate(GRADLE_SCRIPT_TEMPLATE_FILENAME);
try (final Writer fileWriter = new FileWriter(targetFile)) {
gradleScriptTemplate.process(gradleScriptData, fileWriter);
}
}
/**
* 'Extracts' the use cases from the model. This is done by putting the specified models
* in the FreeMarker configuration under the name 'model'. Then, the specified template is
* used to transform the model to text and write it using the specified writer.
*
* @param model the input model, created with requirementsascodecore
* @param templateFileName name of the template file, relative to the base class path (when constructing the engine)
* @param outputWriter the writer that writes out the resulting text
* @throws Exception if anything goes wrong
*/
public void extract(Model model, String templateFileName, Writer outputWriter)
throws Exception {
put("model", model);
Template template = cfg.getTemplate(templateFileName);
template.process(dataModel, outputWriter);
}
/**
* Process the specified FreeMarker template with the given model and write
* the result to the given Writer.
* <p>When using this method to prepare a text for a mail to be sent with Spring's
* mail support, consider wrapping IO/TemplateException in MailPreparationException.
* @param model the model object, typically a Map that contains model names
* as keys and model objects as values
* @return the result as String
* @throws IOException if the template wasn't found or couldn't be read
* @throws freemarker.template.TemplateException if rendering failed
* @see org.springframework.mail.MailPreparationException
*/
public static String processTemplateIntoString(Template template, Object model)
throws IOException, TemplateException {
StringWriter result = new StringWriter();
template.process(model, result);
return result.toString();
}
/**
* Process the specified FreeMarker template with the given model and write
* the result to the given Writer.
* <p>When using this method to prepare a text for a mail to be sent with Spring's
* mail support, consider wrapping IO/TemplateException in MailPreparationException.
* @param model the model object, typically a Map that contains model names
* as keys and model objects as values
* @return the result as String
* @throws IOException if the template wasn't found or couldn't be read
* @throws freemarker.template.TemplateException if rendering failed
* @see org.springframework.mail.MailPreparationException
*/
public static String processTemplateIntoString(Template template, Object model)
throws IOException, TemplateException {
StringWriter result = new StringWriter();
template.process(model, result);
return result.toString();
}
/**
* Process the FreeMarker template to the servlet response.
* <p>Can be overridden to customize the behavior.
* @param template the template to process
* @param model the model for the template
* @param response servlet response (use this to get the OutputStream or Writer)
* @throws IOException if the template file could not be retrieved
* @throws TemplateException if thrown by FreeMarker
* @see freemarker.template.Template#process(Object, java.io.Writer)
*/
protected void processTemplate(Template template, SimpleHash model, HttpServletResponse response)
throws IOException, TemplateException {
template.process(model, response.getWriter());
}
/**
* @param writer
* @param template
* @param configuration
* @param model
* @throws TemplateNotFoundException
* @throws MalformedTemplateNameException
* @throws ParseException
* @throws IOException
* @throws TemplateException
*/
public static void generateStringByPath(Writer writer, String template, Configuration configuration, Object model)
throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
Template tpl = configuration.getTemplate(template, null, null, null, true, true);
tpl.process(model, writer);
}