use of freemarker.cache.FileTemplateLoader in project spring-framework by spring-projects.
the class FreeMarkerConfigurationFactory method getTemplateLoaderForPath.
/**
* Determine a FreeMarker TemplateLoader for the given path.
* <p>Default implementation creates either a FileTemplateLoader or
* a SpringTemplateLoader.
* @param templateLoaderPath the path to load templates from
* @return an appropriate TemplateLoader
* @see freemarker.cache.FileTemplateLoader
* @see SpringTemplateLoader
*/
protected TemplateLoader getTemplateLoaderForPath(String templateLoaderPath) {
if (isPreferFileSystemAccess()) {
// (for hot detection of template changes, if possible).
try {
Resource path = getResourceLoader().getResource(templateLoaderPath);
// will fail if not resolvable in the file system
File file = path.getFile();
if (logger.isDebugEnabled()) {
logger.debug("Template loader path [" + path + "] resolved to file path [" + file.getAbsolutePath() + "]");
}
return new FileTemplateLoader(file);
} catch (IOException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Cannot resolve template loader path [" + templateLoaderPath + "] to [java.io.File]: using SpringTemplateLoader as fallback", ex);
}
return new SpringTemplateLoader(getResourceLoader(), templateLoaderPath);
}
} else {
// Always load via SpringTemplateLoader (without hot detection of template changes).
logger.debug("File system access not preferred: using SpringTemplateLoader");
return new SpringTemplateLoader(getResourceLoader(), templateLoaderPath);
}
}
use of freemarker.cache.FileTemplateLoader in project jforum2 by rafaelsteil.
the class JForumBaseServlet method init.
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
String appPath = config.getServletContext().getRealPath("");
debug = "true".equals(config.getInitParameter("development"));
DOMConfigurator.configure(appPath + "/WEB-INF/log4j.xml");
logger.info("Starting JForum. Debug mode is " + debug);
ConfigLoader.startSystemglobals(appPath);
ConfigLoader.startCacheEngine();
// Configure the template engine
Configuration templateCfg = new Configuration();
templateCfg.setTemplateUpdateDelay(2);
templateCfg.setSetting("number_format", "#");
templateCfg.setSharedVariable("startupTime", new Long(new Date().getTime()));
// Create the default template loader
String defaultPath = SystemGlobals.getApplicationPath() + "/templates";
FileTemplateLoader defaultLoader = new FileTemplateLoader(new File(defaultPath));
String extraTemplatePath = SystemGlobals.getValue(ConfigKeys.FREEMARKER_EXTRA_TEMPLATE_PATH);
if (StringUtils.isNotBlank(extraTemplatePath)) {
// An extra template path is configured, we need a MultiTemplateLoader
FileTemplateLoader extraLoader = new FileTemplateLoader(new File(extraTemplatePath));
TemplateLoader[] loaders = new TemplateLoader[] { extraLoader, defaultLoader };
MultiTemplateLoader multiLoader = new MultiTemplateLoader(loaders);
templateCfg.setTemplateLoader(multiLoader);
} else {
// An extra template path is not configured, we only need the default loader
templateCfg.setTemplateLoader(defaultLoader);
}
ModulesRepository.init(SystemGlobals.getValue(ConfigKeys.CONFIG_DIR));
this.loadConfigStuff();
if (!this.debug) {
templateCfg.setTemplateUpdateDelay(3600);
}
JForumExecutionContext.setTemplateConfig(templateCfg);
} catch (Exception e) {
throw new ForumStartupException("Error while starting JForum", e);
}
}
use of freemarker.cache.FileTemplateLoader in project pratilipi by Pratilipi.
the class FreeMarkerUtil method getConfiguration.
private static Configuration getConfiguration() throws UnexpectedServerException {
if (cfg == null) {
FileTemplateLoader ftl;
try {
ftl = new FileTemplateLoader(new File("."));
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to set template directory.", e);
throw new UnexpectedServerException();
}
ClassTemplateLoader ctl = new ClassTemplateLoader(FreeMarkerUtil.class.getClassLoader(), "");
MultiTemplateLoader mtl = new MultiTemplateLoader(new TemplateLoader[] { ftl, ctl });
cfg = new Configuration(Configuration.VERSION_2_3_22);
cfg.setTemplateLoader(mtl);
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
}
return cfg;
}
use of freemarker.cache.FileTemplateLoader in project asterixdb by apache.
the class LoadFileDirective method execute.
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
String fileParam = null;
String defaultParam = null;
boolean trimParam = false;
for (Object paramObj : params.entrySet()) {
Map.Entry param = (Map.Entry) paramObj;
String paramName = (String) param.getKey();
TemplateModel paramValue = (TemplateModel) param.getValue();
switch(paramName) {
case PARAM_FILE:
if (paramValue instanceof TemplateScalarModel) {
fileParam = ((TemplateScalarModel) paramValue).getAsString();
} else {
throw new TemplateModelException(PARAM_FILE + " must be a string");
}
break;
case PARAM_DEFAULT_TEXT:
if (paramValue instanceof TemplateScalarModel) {
defaultParam = ((TemplateScalarModel) paramValue).getAsString();
} else {
throw new TemplateModelException(PARAM_DEFAULT_TEXT + " must be a string");
}
break;
case PARAM_TRIM:
if (paramValue instanceof TemplateBooleanModel) {
trimParam = ((TemplateBooleanModel) paramValue).getAsBoolean();
} else {
throw new TemplateModelException(PARAM_TRIM + " must be a boolean");
}
break;
default:
throw new TemplateModelException("Unknown param: " + paramName);
}
}
if (fileParam == null) {
throw new TemplateModelException("The required \"" + PARAM_FILE + "\" parameter" + "is missing.");
}
if (body != null) {
throw new TemplateModelException("Body is not supported by this directive");
}
Writer out = env.getOut();
File baseDir = ((FileTemplateLoader) ((Configuration) env.getTemplate().getParent()).getTemplateLoader()).baseDir;
File file = new File(baseDir, fileParam);
if (file.exists()) {
if (trimParam) {
LicenseUtil.readAndTrim(out, file);
out.write('\n');
} else {
IOUtils.copy(new FileInputStream(file), out, StandardCharsets.UTF_8);
}
} else if (defaultParam != null) {
out.append(defaultParam).append("\n");
} else {
throw new IOException("File not found: " + file);
}
}
use of freemarker.cache.FileTemplateLoader in project asterixdb by apache.
the class GenerateFileMojo method generateFiles.
private void generateFiles() throws TemplateException, IOException {
Map<String, Object> props = getProperties();
Configuration config = new Configuration();
config.setTemplateLoader(new FileTemplateLoader(templateRootDir));
for (GeneratedFile generation : generatedFiles) {
Template template = config.getTemplate(generation.getTemplate(), StandardCharsets.UTF_8.name());
if (template == null) {
throw new IOException("Could not load template " + generation.getTemplate());
}
outputDir.mkdirs();
final File file = new File(outputDir, generation.getOutputFile());
getLog().info("Writing " + file + "...");
try (final FileOutputStream fos = new FileOutputStream(file);
final Writer writer = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) {
template.process(props, writer);
}
}
}
Aggregations