Java Code Examples for freemarker.template.Template#process()

The following examples show how to use freemarker.template.Template#process() . 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 File: CreateFileUtil.java    From Vert.X-generator with MIT License 7 votes vote down vote up
/**
 * 执行创建文件
 * 
 * @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);
	}
}
 
Example 2
Source File: FreemarkerTool.java    From fun-generator with MIT License 6 votes vote down vote up
/**
 * 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();
}
 
Example 3
Source File: TemplateService.java    From frostmourne with MIT License 5 votes vote down vote up
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);
    }
}
 
Example 4
Source File: PageGenerator.java    From tp_java_2015_02 with MIT License 5 votes vote down vote up
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();
}
 
Example 5
Source File: CodeGenerator.java    From QuickProject with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 6
Source File: BaseServlet.java    From drivemarks with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 7
Source File: GenerateHQL.java    From occurrence with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 8
Source File: FreeMarkerUtils.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
/**
 * 获取渲染后的文本
 * @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);
	}
}
 
Example 9
Source File: CodeGenerateUtils.java    From scaffold-cloud with MIT License 5 votes vote down vote up
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);
}
 
Example 10
Source File: FreemarkerTransformer.java    From tutorials with MIT License 5 votes vote down vote up
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();
    }
}
 
Example 11
Source File: GenerateHQL.java    From occurrence with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 12
Source File: PageGenerator.java    From tp_java_2015_02 with MIT License 5 votes vote down vote up
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();
}
 
Example 13
Source File: FreemarkerHelper.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 14
Source File: GeneratePDFWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
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);
    }
}
 
Example 15
Source File: GradleInspectorScriptCreator.java    From synopsys-detect with Apache License 2.0 4 votes vote down vote up
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);
    }
}
 
Example 16
Source File: FreeMarkerTemplateUtils.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * 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();
}
 
Example 17
Source File: FreeMarkerTemplateUtils.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * 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();
}
 
Example 18
Source File: FreeMarkerEngine.java    From requirementsascode with Apache License 2.0 3 votes vote down vote up
/**
 * '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);
}
 
Example 19
Source File: FreemarkerUtils.java    From t-io with Apache License 2.0 2 votes vote down vote up
/**
 * @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);
}
 
Example 20
Source File: FreeMarkerView.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * 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());
}