Java Code Examples for freemarker.cache.StringTemplateLoader#putTemplate()

The following examples show how to use freemarker.cache.StringTemplateLoader#putTemplate() . 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: FreemarkerTest.java    From mogu_blog_v2 with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 2
Source File: HtmlFormatter.java    From yarg with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 3
Source File: TemplateProcessor.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** 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);
    }
}
 
Example 4
Source File: TemplateProcessor.java    From contribution with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 5
Source File: OutMsgXmlBuilder.java    From jfinal-weixin with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 6
Source File: DynamicHqlUtils.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
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;		
}
 
Example 7
Source File: HtmlReportWriter.java    From vind with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 8
Source File: TemplateParse.java    From genDoc with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example 9
Source File: CodeRenderer.java    From jpa-entity-generator with MIT License 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 10
Source File: EmailExchanger.java    From open-cloud with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example 11
Source File: TemplateUtils.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 12
Source File: TemplateUtils.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
/**
 * 單獨提供單處理 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();
}
 
Example 13
Source File: FreeMarkerProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 14
Source File: ComponentResourceUtils.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 15
Source File: TemplateService.java    From frostmourne with MIT License 5 votes vote down vote up
@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);
}
 
Example 16
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 17
Source File: TemplateHelper.java    From cuba with Apache License 2.0 4 votes vote down vote up
public static String processTemplate(String templateStr, Map<String, ?> parameterValues) {
    StringTemplateLoader templateLoader = new StringTemplateLoader();
    templateLoader.putTemplate("template", templateStr);
    return __processTemplate(templateLoader, "template", parameterValues);
}