Java Code Examples for freemarker.template.Configuration#setTemplateLoader()

The following examples show how to use freemarker.template.Configuration#setTemplateLoader() . 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: DrillRestServer.java    From Bats with Apache License 2.0 7 votes vote down vote up
/**
 * Creates freemarker configuration settings,
 * default output format to trigger auto-escaping policy
 * and template loaders.
 *
 * @param servletContext servlet context
 * @return freemarker configuration settings
 */
private Configuration getFreemarkerConfiguration(ServletContext servletContext) {
  Configuration configuration = new Configuration(Configuration.VERSION_2_3_26);
  configuration.setOutputFormat(HTMLOutputFormat.INSTANCE);

  List<TemplateLoader> loaders = new ArrayList<>();
  loaders.add(new WebappTemplateLoader(servletContext));
  loaders.add(new ClassTemplateLoader(DrillRestServer.class, "/"));
  try {
    loaders.add(new FileTemplateLoader(new File("/")));
  } catch (IOException e) {
    logger.error("Could not set up file template loader.", e);
  }
  configuration.setTemplateLoader(new MultiTemplateLoader(loaders.toArray(new TemplateLoader[loaders.size()])));
  return configuration;
}
 
Example 2
Source File: MavenUtils.java    From camel-kafka-connector with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: LocalFeedTaskProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected Configuration getFreemarkerConfiguration(RepoCtx ctx)
{
    if (useRemoteCallbacks)
    {
        // as per 3.0, 3.1
        return super.getFreemarkerConfiguration(ctx);
    } 
    else
    {
        Configuration cfg = new Configuration();
        cfg.setObjectWrapper(new DefaultObjectWrapper());

        cfg.setTemplateLoader(new ClassPathRepoTemplateLoader(nodeService, contentService, defaultEncoding));

        // TODO review i18n
        cfg.setLocalizedLookup(false);
        cfg.setIncompatibleImprovements(new Version(2, 3, 20));
        cfg.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);

        return cfg;
    }
}
 
Example 4
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 5
Source File: TckComparisonReport.java    From openCypher with Apache License 2.0 6 votes vote down vote up
public static void generate(File outputDir, Diff diff) throws IOException, TemplateException {
    File report = new File(outputDir, "comparison.html");

    Configuration cfg = new Configuration(VERSION_2_3_23);
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(RETHROW_HANDLER);
    ClassTemplateLoader templateLoader = new ClassTemplateLoader(TckComparisonReport.class, "");
    cfg.setTemplateLoader(templateLoader);

    Map<String, Object> input = new HashMap<>();
    input.put("diff", diff);

    try (Writer fileWriter = new FileWriter(report)) {
        Template template = cfg.getTemplate("ComparisonReport.ftl");
        template.process(input, fileWriter);
        System.out.println("\nComparison report saved to " + report.toURI());
    }
}
 
Example 6
Source File: FreemarkerUtil.java    From jeewx-api with Apache License 2.0 6 votes vote down vote up
/**
 * 解析ftl
 * @param tplContent 模板内容
 * @param encoding 编码
 * @param paras 参数
 * @return String 模板解析后内容
 */
public String parseTemplateContent(String tplContent,
		Map<String, Object> paras, String encoding) {
	Configuration cfg = new Configuration();    
    StringWriter writer = new StringWriter(); 
       cfg.setTemplateLoader(new StringTemplateLoader(tplContent));  
       encoding = encoding==null?"UTF-8":encoding;
       cfg.setDefaultEncoding(encoding);    
  
       Template template;
	try {
		template = cfg.getTemplate("");
        template.process(paras, writer);    
		} catch (Exception e) {
			e.printStackTrace();
		}
       return writer.toString();       
}
 
Example 7
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 8
Source File: FreeMarkerRenderer.java    From opoopress with Apache License 2.0 5 votes vote down vote up
public FreeMarkerRenderer(Site site) {
    super();
    this.site = site;
    templateDir = site.getTemplates();
    log.debug("Template directory: " + templateDir.getAbsolutePath());

    //Working directory
    workingTemplateDir = new File(site.getWorking(), "templates");
    PathUtils.checkDir(workingTemplateDir, PathUtils.Strategy.CREATE_IF_NOT_EXISTS);
    log.debug("Working template directory: {}", workingTemplateDir.getAbsolutePath());

    //config
    configuration = new Configuration();
    configuration.setObjectWrapper(new DefaultObjectWrapper());
    configuration.setTemplateLoader(buildTemplateLoader(site));

    Locale locale = site.getLocale();
    if (locale != null) {
        configuration.setLocale(site.getLocale());
    }

    //Add import i18n messages template.
    //config.addAutoImport("i18n", "i18n/messages.ftl");

    initializeAutoImportTemplates(site, configuration);
    initializeAutoIncludeTemplates(site, configuration);

    initializeTemplateModels();


    renderMethod = site.get(PROPERTY_PREFIX + "render_method");

    Boolean useMacroLayout = site.get(PROPERTY_PREFIX + "macro_layout");
    workingTemplateHolder = (useMacroLayout == null || useMacroLayout.booleanValue()) ?
            new MacroWorkingTemplateHolder() : new NonMacroWorkingTemplateHolder();
}
 
Example 9
Source File: DiffReportTest.java    From testability-explorer with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();
  out = new StringWriter();
  cfg = new Configuration();
  cfg.setTemplateLoader(new ClassPathTemplateLoader(ReportGeneratorProvider.PREFIX));
}
 
Example 10
Source File: TemplateWrapperFactory.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public TemplateWrapperFactory(String templatesPackagePath) {
    configuration = new Configuration(Configuration.VERSION_2_3_24);

    configuration.setTemplateLoader(new ClassTemplateLoader(HtmlReport.class, templatesPackagePath));
    configuration.setDefaultEncoding("UTF-8");
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    configuration.setAPIBuiltinEnabled(true);
    configuration.setObjectWrapper(new BeansWrapperBuilder(Configuration.VERSION_2_3_24).build());
    configuration.setRecognizeStandardFileExtensions(true);
}
 
Example 11
Source File: HelpTemplateWrapperFactory.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public HelpTemplateWrapperFactory(String templatesPackagePath) throws IOException {
    configuration = new Configuration(Configuration.VERSION_2_3_24);

    configuration.setTemplateLoader(new ClassTemplateLoader(HelpBuilder.class, templatesPackagePath));
    configuration.setDefaultEncoding("UTF-8");
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    configuration.setAPIBuiltinEnabled(true);
    configuration.setRecognizeStandardFileExtensions(true);
}
 
Example 12
Source File: FreemarkerUtils.java    From my_curd with Apache License 2.0 5 votes vote down vote up
/**
 * 通过模板文本字符串和数据获得渲染后的文本
 *
 * @param templateContent 模板文本内容
 * @param paramMap        数据
 * @return
 */
public static String renderAsText(String templateContent, Map<String, Object> paramMap) {
    StringWriter writer = new StringWriter();
    try {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
        cfg.setTemplateLoader(new StringTemplateLoader(templateContent));
        cfg.setDefaultEncoding(Constant.DEFAULT_ENCODEING);
        Template template = cfg.getTemplate("");
        template.process(paramMap, writer);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return writer.toString();
}
 
Example 13
Source File: ViewBuilder.java    From docker-elastic-agents-plugin with Apache License 2.0 5 votes vote down vote up
private ViewBuilder() {
    configuration = new Configuration(Configuration.VERSION_2_3_23);
    configuration.setTemplateLoader(new ClassTemplateLoader(getClass(), "/"));
    configuration.setDefaultEncoding("UTF-8");
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    configuration.setLogTemplateExceptions(false);
    configuration.setDateTimeFormat("iso");
}
 
Example 14
Source File: FreeMarkerUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Template getTemplate(String templateName, Theme theme) throws IOException {
    Configuration cfg = new Configuration();

    // Assume *.ftl files are html.  This lets freemarker know how to
    // sanitize and prevent XSS attacks.
    if (templateName.toLowerCase().endsWith(".ftl")) {
        cfg.setOutputFormat(HTMLOutputFormat.INSTANCE);
    }
    
    cfg.setTemplateLoader(new ThemeTemplateLoader(theme));
    return cfg.getTemplate(templateName, "UTF-8");
}
 
Example 15
Source File: MailTestCases.java    From kaif with Apache License 2.0 5 votes vote down vote up
@Before
public void mailSetup() {
  configuration = new Configuration(Configuration.VERSION_2_3_21);
  configuration.setDefaultEncoding("UTF-8");
  configuration.setTemplateLoader(new ClassTemplateLoader(MailComposer.class, "/mail"));

  //keep config same as application.yml and WebConfiguration.java
  messageSource = new ResourceBundleMessageSource();
  messageSource.setBasename("i18n/messages");
  messageSource.setDefaultEncoding("UTF-8");
  messageSource.setFallbackToSystemLocale(false);
}
 
Example 16
Source File: BaseDocumentationTest.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void loadTemplates() {
  loader = new ClassTemplateLoader(
      BaseDocumentationTest.class,
      "templates"
  );

  configuration = new Configuration(Configuration.getVersion());
  configuration.setDefaultEncoding("UTF-8");
  configuration.setTemplateLoader(loader);
  configuration.setObjectWrapper(new BeansWrapper(Configuration.getVersion()));
  configuration.setNumberFormat("computer");
}
 
Example 17
Source File: CqUtils.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
public static Configuration getTemplateConfig(Path basePath, String defaultUriBase, String templatesUriBase,
        String encoding) {
    final Configuration templateCfg = new Configuration(Configuration.VERSION_2_3_28);
    templateCfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    templateCfg.setTemplateLoader(createTemplateLoader(basePath, defaultUriBase, templatesUriBase));
    templateCfg.setDefaultEncoding(encoding);
    templateCfg.setInterpolationSyntax(Configuration.SQUARE_BRACKET_INTERPOLATION_SYNTAX);
    templateCfg.setTagSyntax(Configuration.SQUARE_BRACKET_TAG_SYNTAX);
    return templateCfg;
}
 
Example 18
Source File: FreeMarkerConfigurationFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prepare the FreeMarker Configuration and return it.
 * @return the FreeMarker Configuration object
 * @throws IOException if the config file wasn't found
 * @throws TemplateException on FreeMarker initialization failure
 */
public Configuration createConfiguration() throws IOException, TemplateException {
	Configuration config = newConfiguration();
	Properties props = new Properties();

	// Load config file if specified.
	if (this.configLocation != null) {
		if (logger.isInfoEnabled()) {
			logger.info("Loading FreeMarker configuration from " + this.configLocation);
		}
		PropertiesLoaderUtils.fillProperties(props, this.configLocation);
	}

	// Merge local properties if specified.
	if (this.freemarkerSettings != null) {
		props.putAll(this.freemarkerSettings);
	}

	// FreeMarker will only accept known keys in its setSettings and
	// setAllSharedVariables methods.
	if (!props.isEmpty()) {
		config.setSettings(props);
	}

	if (!CollectionUtils.isEmpty(this.freemarkerVariables)) {
		config.setAllSharedVariables(new SimpleHash(this.freemarkerVariables, config.getObjectWrapper()));
	}

	if (this.defaultEncoding != null) {
		config.setDefaultEncoding(this.defaultEncoding);
	}

	List<TemplateLoader> templateLoaders = new LinkedList<TemplateLoader>(this.templateLoaders);

	// Register template loaders that are supposed to kick in early.
	if (this.preTemplateLoaders != null) {
		templateLoaders.addAll(this.preTemplateLoaders);
	}

	// Register default template loaders.
	if (this.templateLoaderPaths != null) {
		for (String path : this.templateLoaderPaths) {
			templateLoaders.add(getTemplateLoaderForPath(path));
		}
	}
	postProcessTemplateLoaders(templateLoaders);

	// Register template loaders that are supposed to kick in late.
	if (this.postTemplateLoaders != null) {
		templateLoaders.addAll(this.postTemplateLoaders);
	}

	TemplateLoader loader = getAggregateTemplateLoader(templateLoaders);
	if (loader != null) {
		config.setTemplateLoader(loader);
	}

	postProcessConfiguration(config);
	return config;
}
 
Example 19
Source File: WordprocessingMLFreemarkerTemplate.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
protected Configuration getInternalEngine() throws IOException, TemplateException{
	
	try {
		BeansWrapper beansWrapper = new BeansWrapper(Configuration.VERSION_2_3_23);
		this.templateModel = beansWrapper.getStaticModels().get(String.class.getName());
	} catch (TemplateModelException e) {
		throw new IOException(e.getMessage(),e.getCause());
	}

	// 创建 Configuration 实例
	Configuration config = new Configuration(Configuration.VERSION_2_3_23);
	
	Properties props = ConfigUtils.filterWithPrefix("docx4j.freemarker.", "docx4j.freemarker.", Docx4jProperties.getProperties(), false);

	// FreeMarker will only accept known keys in its setSettings and
	// setAllSharedVariables methods.
	if (!props.isEmpty()) {
		config.setSettings(props);
	}

	if (this.freemarkerVariables != null && !this.freemarkerVariables.isEmpty()) {
		config.setAllSharedVariables(new SimpleHash(this.freemarkerVariables, config.getObjectWrapper()));
	}

	if (this.defaultEncoding != null) {
		config.setDefaultEncoding(this.defaultEncoding);
	}

	List<TemplateLoader> templateLoaders = new LinkedList<TemplateLoader>(this.templateLoaders);
	
	// Register template loaders that are supposed to kick in early.
	if (this.preTemplateLoaders != null) {
		templateLoaders.addAll(this.preTemplateLoaders);
	}
	
	postProcessTemplateLoaders(templateLoaders);
	
	// Register template loaders that are supposed to kick in late.
	if (this.postTemplateLoaders != null) {
		templateLoaders.addAll(this.postTemplateLoaders);
	}
	
	TemplateLoader loader = getAggregateTemplateLoader(templateLoaders);
	if (loader != null) {
		config.setTemplateLoader(loader);
	}
	//config.setClassLoaderForTemplateLoading(classLoader, basePackagePath);
	//config.setCustomAttribute(name, value);
	//config.setDirectoryForTemplateLoading(dir);
	//config.setServletContextForTemplateLoading(servletContext, path);
	//config.setSharedVariable(name, value);
	//config.setSharedVariable(name, tm);
	config.setSharedVariable("fmXmlEscape", new XmlEscape());
	config.setSharedVariable("fmHtmlEscape", new HtmlEscape());
	//config.setSharedVaribles(map);
	
	// 设置模板引擎,减少重复初始化消耗
       this.setEngine(config);
       return config;
}
 
Example 20
Source File: FreemarkerTemplatingService.java    From blackduck-alert with Apache License 2.0 3 votes vote down vote up
public Configuration createFreemarkerConfig(TemplateLoader templateLoader) {
    Configuration configuration = createDefaultConfiguration();

    configuration.setTemplateLoader(templateLoader);

    return configuration;
}