下面列出了freemarker.template.Version#freemarker.template.TemplateExceptionHandler 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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();
}
}
@Bean
public freemarker.template.Configuration freemarkConfig() {
/* ------------------------------------------------------------------------ */
/* You should do this ONLY ONCE in the whole application life-cycle: */
/* Create and adjust the configuration singleton */
freemarker.template.Configuration cfg = new freemarker.template.Configuration(
freemarker.template.Configuration.VERSION_2_3_22);
File folder;
try {
folder = ResourceUtils.getFile("classpath:templates");
cfg.setDirectoryForTemplateLoading(folder);
} catch (IOException e) {
e.printStackTrace();
}
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
return cfg;
}
/**
* Inits the freemarker.
*
* @return the configuration
*/
public static Configuration initFreemarker() {
try {
Configuration config = new Configuration();
config.setTemplateLoader(new ClassTemplateLoader(Freemarker.class, "/templates"));
config.setTemplateUpdateDelay(0);
config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
config.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
config.setDefaultEncoding("ISO-8859-1");
config.setOutputEncoding("ISO-8859-1");
config.setNumberFormat("0");
config.setSetting("url_escaping_charset", "ISO-8859-1");
config.setLocale(Locale.ENGLISH);
setAutoImport(config);
setSharedVariables(config);
return config;
} catch (Throwable e) {
throw new RuntimeException("Could not initialise Freemarker configuration", e);
}
}
/**
* Create a new instance of {@link FreemarkerEngine}.
* @param backend the backend name
* @param directives custom directives to register
* @param model some model attributes to set for each rendering invocation
*/
public FreemarkerEngine(String backend,
Map<String, String> directives,
Map<String, String> model) {
checkNonNullNonEmpty(backend, BACKEND_PROP);
this.backend = backend;
this.directives = directives == null ? Collections.emptyMap() : directives;
this.model = model == null ? Collections.emptyMap() : model;
freemarker = new Configuration(FREEMARKER_VERSION);
freemarker.setTemplateLoader(new TemplateLoader());
freemarker.setDefaultEncoding(DEFAULT_ENCODING);
freemarker.setObjectWrapper(OBJECT_WRAPPER);
freemarker.setTemplateExceptionHandler(
TemplateExceptionHandler.RETHROW_HANDLER);
freemarker.setLogTemplateExceptions(false);
}
/**
* Configuring freemarker template file path.
*
* @return new FreeMarkerConfigurer
*/
@Bean
public FreeMarkerConfigurer freemarkerConfig(HaloProperties haloProperties) throws IOException, TemplateException {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setTemplateLoaderPaths(FILE_PROTOCOL + haloProperties.getWorkDir() + "templates/", "classpath:/templates/");
configurer.setDefaultEncoding("UTF-8");
Properties properties = new Properties();
properties.setProperty("auto_import", "/common/macro/common_macro.ftl as common,/common/macro/global_macro.ftl as global");
configurer.setFreemarkerSettings(properties);
// Predefine configuration
freemarker.template.Configuration configuration = configurer.createConfiguration();
configuration.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);
if (haloProperties.isProductionEnv()) {
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
}
// Set predefined freemarker configuration
configurer.setConfiguration(configuration);
return configurer;
}
private void setupTemplate() throws IOException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_21);
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setTemplateLoader(new ClassTemplateLoader(getClass(), "/web-headers"));
String templateName = "header";
switch (headerType) {
case MAL3:
templateName = "mal3";
break;
case ABABIL:
templateName = "ababil";
break;
default:
break;
}
template = cfg.getTemplate(templateName);
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
this.servletConfig = servletConfig;
//templateCfg.setClassForTemplateLoading(getClass(), "/");
Resource baseResource;
try {
baseResource = Resource.newResource(servletConfig.getInitParameter("resourceBase"));
} catch (IOException e) {
throw new ServletException(e);
}
templateCfg.setTemplateLoader(new ResourceTemplateLoader(baseResource));
templateCfg.setDefaultEncoding("UTF-8");
// Sets how errors will appear.
// During web page *development* TemplateExceptionHandler.HTML_DEBUG_HANDLER
// is better.
// cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
templateCfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
}
private void init(String dbHost, Integer dbPort, String dbName, String dnaCollection, String pathwayCollection) throws IOException {
cfg = new Configuration(Configuration.VERSION_2_3_23);
cfg.setClassLoaderForTemplateLoading(
this.getClass().getClassLoader(), "/act/installer/reachablesexplorer/templates");
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(true);
reachableTemplate = cfg.getTemplate(reachableTemplateName);
pathwayTemplate = cfg.getTemplate(pathwayTemplateName);
// TODO: move this elsewhere.
MongoClient client = new MongoClient(new ServerAddress(dbHost, dbPort));
DB db = client.getDB(dbName);
dnaDesignCollection = JacksonDBCollection.wrap(db.getCollection(dnaCollection), DNADesign.class, String.class);
Cascade.setCollectionName(pathwayCollection);
}
/**
* @param onTable
*/
public SchemaMaker(String tenant, String module, TenantOperation mode, String previousVersion, String newVersion){
if(SchemaMaker.cfg == null){
//do this ONLY ONCE
SchemaMaker.cfg = new Configuration(new Version(2, 3, 26));
// Where do we load the templates from:
cfg.setClassForTemplateLoading(SchemaMaker.class, "/templates/db_scripts");
cfg.setDefaultEncoding("UTF-8");
cfg.setLocale(Locale.US);
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
}
this.tenant = tenant;
this.module = module;
this.mode = mode;
this.previousVersion = previousVersion;
this.newVersion = newVersion;
this.rmbVersion = PomReader.INSTANCE.getRmbVersion();
}
public Configuration build() throws IOException {
Configuration _config = new Configuration(getVersion());
_config.setDefaultEncoding(getEncoding());
_config.setTemplateExceptionHandler(templateExceptionHandler != null ? templateExceptionHandler : TemplateExceptionHandler.HTML_DEBUG_HANDLER);
//
for (File _tplFileDir : templateFiles) {
templateLoaders.add(new FileTemplateLoader(_tplFileDir));
}
if (!templateSources.isEmpty()) {
StringTemplateLoader _stringTplLoader = new StringTemplateLoader();
for (Map.Entry<String, String> _entry : templateSources.entrySet()) {
_stringTplLoader.putTemplate(_entry.getKey(), _entry.getValue());
}
templateLoaders.add(_stringTplLoader);
}
//
if (!templateLoaders.isEmpty()) {
if (templateLoaders.size() > 1) {
_config.setTemplateLoader(new MultiTemplateLoader(templateLoaders.toArray(new TemplateLoader[0])));
} else {
_config.setTemplateLoader(templateLoaders.get(0));
}
}
//
return _config;
}
/**
* 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);
}
}
@Override
protected void setUp() throws Exception {
super.setUp();
try {
Configuration config = new Configuration();
DefaultObjectWrapper wrapper = new DefaultObjectWrapper();
config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
config.setObjectWrapper(wrapper);
config.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);
TemplateModel templateModel = this.createModel(wrapper);
ExecutorBeanContainer ebc = new ExecutorBeanContainer(config, templateModel);
super.getRequestContext().addExtraParam(SystemConstants.EXTRAPAR_EXECUTOR_BEAN_CONTAINER, ebc);
} catch (Throwable t) {
throw new Exception(t);
}
}
public FreeMarkerFormatter(String templateName) throws IOException {
// If the resource doesn't exist abort so we can look elsewhere
try (
InputStream in = this.getClass().getResourceAsStream(TEMPLATES + "/" + templateName)) {
if (in == null) {
throw new IOException("Resource not found:" + templateName);
}
}
this.templateName = templateName;
Configuration cfg = new Configuration(Configuration.VERSION_2_3_21);
TemplateLoader templateLoader = new ClassTemplateLoader(this.getClass(), TEMPLATES);
cfg.setTemplateLoader(templateLoader);
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
// This is fatal - bomb out of application
try {
template = cfg.getTemplate(templateName);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
private String buildDescription(String jiraTemplate, Map<String, Object> templateValues) {
String description;
// Render the values in templateValues map to the jira ftl template file
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (Writer out = new OutputStreamWriter(baos, CHARSET)) {
Configuration freemarkerConfig = new Configuration(Configuration.VERSION_2_3_21);
freemarkerConfig.setClassForTemplateLoading(getClass(), "/org/apache/pinot/thirdeye/detector");
freemarkerConfig.setDefaultEncoding(CHARSET);
freemarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
Template template = freemarkerConfig.getTemplate(jiraTemplate);
template.process(templateValues, out);
description = new String(baos.toByteArray(), CHARSET);
} catch (Exception e) {
description = "Found an exception while constructing the description content. Pls report & reach out"
+ " to the Thirdeye team. Exception = " + e.getMessage();
}
return description;
}
@Override
public void afterPropertiesSet() {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
configuration.setDefaultEncoding("utf-8");
configuration.setLogTemplateExceptions(true);
configuration.setNumberFormat("computer");
configuration.setOutputFormat(XHTMLOutputFormat.INSTANCE);
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
configuration.setTemplateLoader(new SpringTemplateLoader(this.resourceLoader, this.resourceLoaderPath));
if (this.shouldCheckForTemplateModifications) {
configuration.setTemplateUpdateDelayMilliseconds(1000);
} else {
configuration.setTemplateUpdateDelayMilliseconds(Long.MAX_VALUE);
}
this.configuration = configuration;
}
/**
* Configuration initialization
* @param resourceLoaderClass class for loading resources
* @param templatePath template path
*/
public FreemarkerProcessor(Class<?> resourceLoaderClass, String templatePath)
{
configuration = new Configuration(Configuration.VERSION_2_3_30);
configuration.setClassForTemplateLoading(resourceLoaderClass, templatePath);
configuration.setDefaultEncoding(StandardCharsets.UTF_8.toString());
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
}
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;
}
@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;
}
private Template getTemplate(String templateName) throws Exception {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
String templatePath = GeneratorHelper.class.getResource("/generator/templates/").getPath();
File file = new File(templatePath);
if (!file.exists()) {
templatePath = System.getProperties().getProperty(FebsConstant.JAVA_TEMP_DIR);
file = new File(templatePath + File.separator + templateName);
FileUtils.copyInputStreamToFile(Objects.requireNonNull(GeneratorHelper.class.getClassLoader().getResourceAsStream("classpath:generator/templates/" + templateName)), file);
}
configuration.setDirectoryForTemplateLoading(new File(templatePath));
configuration.setDefaultEncoding(FebsConstant.UTF8);
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
return configuration.getTemplate(templateName);
}
private static Configuration getConfiguration() throws IOException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
ConfigConstant.CONFIG_ENTITY.setConfigPath(StringUtil.addSeparator(ConfigConstant.CONFIG_ENTITY.getConfigPath()));
File file = new File(ConfigConstant.CONFIG_ENTITY.getBasedir() + ConfigConstant.CONFIG_ENTITY.getConfigPath());
if (!file.exists()) {
log.error(file + "配置文件不存在");
throw new RuntimeException("配置文件不存在");
}
cfg.setDirectoryForTemplateLoading(file);
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
return cfg;
}
private static freemarker.template.Configuration getConfiguration() throws IOException {
final freemarker.template.Configuration cfg =
new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
cfg.setDirectoryForTemplateLoading(new File(CodeGenerator.TEMPLATE_FILE_PATH));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
return cfg;
}
static String renderDocumentation(ConfigurationRegistry configurationRegistry) throws IOException, TemplateException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);
cfg.setClassLoaderForTemplateLoading(ConfigurationExporterTest.class.getClassLoader(), "/");
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
Template temp = cfg.getTemplate("configuration.asciidoc.ftl");
StringWriter tempRenderedFile = new StringWriter();
tempRenderedFile.write("////\n" +
"This file is auto generated\n" +
"\n" +
"Please only make changes in configuration.asciidoc.ftl\n" +
"////\n");
final List<ConfigurationOption<?>> nonInternalOptions = configurationRegistry.getConfigurationOptionsByCategory()
.values()
.stream()
.flatMap(List::stream)
.filter(option -> !option.getTags().contains("internal"))
.collect(Collectors.toList());
final Map<String, List<ConfigurationOption<?>>> optionsByCategory = nonInternalOptions.stream()
.collect(Collectors.groupingBy(ConfigurationOption::getConfigurationCategory, TreeMap::new, Collectors.toList()));
temp.process(Map.of(
"config", optionsByCategory,
"keys", nonInternalOptions.stream().map(ConfigurationOption::getKey).sorted().collect(Collectors.toList())
), tempRenderedFile);
// re-process the rendered template to resolve the ${allInstrumentationGroupNames} placeholder
StringWriter out = new StringWriter();
new Template("", tempRenderedFile.toString(), cfg)
.process(Map.of("allInstrumentationGroupNames", getAllInstrumentationGroupNames()), out);
return out.toString();
}
public Configuration initFreemarker() {
Configuration config = new Configuration();
config.setTemplateLoader(new ClassTemplateLoader(Freemarker.class, "/templates"));
config.setTemplateUpdateDelay(0);
config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
config.setObjectWrapper(ObjectWrapper.DEFAULT_WRAPPER);
config.setDefaultEncoding("UTF-8");
config.setOutputEncoding("UTF-8");
return config;
}
@Bean
public freemarker.template.Configuration configuration(){
final freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_22);
cfg.setTemplateLoader(new ClassTemplateLoader(getClass(), "/templates"));
cfg.setDefaultEncoding(StandardCharsets.UTF_8.name());
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
return cfg;
}
FreemarkerResolver() {
cfg = new Configuration(Configuration.getVersion());
cfg.setDefaultEncoding(StandardCharsets.UTF_8.name());
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setClassForTemplateLoading(Bootstrap.class,
WebConfigKeys.VIEW_PREFIX_FREEMARKER.getValue());
cfg.setNumberFormat(Strings.OCTOTHORP);
if (WebConfigKeys.VIEW_CACHE.castValue(boolean.class)) {
cfg.setCacheStorage(new MruCacheStorage(20, 250));
} else {
cfg.unsetCacheStorage();
}
}
/**
* Builds a default config for FreeMarker which reads templates from the classpath under the path specified in the prefix
* a prefix is specified.
*
* @param configuration free marker config
* @param resourceClass class to load resources relative to
* @return supplied configuration if not nul, otherwise a default one
*/
protected Configuration buildDefaultConfig(Configuration configuration, Class<?> resourceClass) {
if (configuration != null) {
return configuration;
}
Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
cfg.setClassForTemplateLoading(resourceClass == null ? getClass() : resourceClass, "/");
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(true);
cfg.setCacheStorage(NullCacheStorage.INSTANCE);
return cfg;
}
private static freemarker.template.Configuration getConfiguration() throws IOException {
freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
cfg.setDirectoryForTemplateLoading(new File(MailConstant.TEMPLATEPATH));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
return cfg;
}
private static freemarker.template.Configuration getConfiguration() throws IOException {
freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
cfg.setDirectoryForTemplateLoading(new File(TEMPLATE_FILE_PATH));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
return cfg;
}
private static freemarker.template.Configuration getConfiguration() throws IOException {
freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
cfg.setDirectoryForTemplateLoading(new File(TEMPLATE_FILE_PATH));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
return cfg;
}
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);
}