use of freemarker.cache.MultiTemplateLoader in project wombat by PLOS.
the class WombatControllerTestConfig method freeMarkerConfig.
@Bean
public FreeMarkerConfig freeMarkerConfig(ServletContext servletContext) throws IOException {
String[] templates = getFreeMarkerTemplateDirsForTest();
List<TemplateLoader> loaders = new ArrayList<TemplateLoader>();
for (String template : templates) {
FileTemplateLoader loader = new FileTemplateLoader(new File(servletContext.getRealPath(template)));
loaders.add(loader);
}
MultiTemplateLoader mtl = new MultiTemplateLoader(loaders.toArray(new TemplateLoader[0]));
FreeMarkerConfigurer config = new FreeMarkerConfigurer();
config.setPreTemplateLoaders(mtl);
ImmutableMap.Builder<String, Object> variables = ImmutableMap.builder();
variables.put("formatJsonDate", new Iso8601DateDirective());
variables.put("replaceParams", new ReplaceParametersDirective());
variables.put("siteLink", getEmptyTemplateDirectiveModel());
variables.put("cssLink", getEmptyTemplateDirectiveModel());
variables.put("renderCssLinks", getEmptyTemplateDirectiveModel());
variables.put("js", getEmptyTemplateDirectiveModel());
variables.put("renderJs", getEmptyTemplateDirectiveModel());
variables.put("buildInfo", getEmptyTemplateDirectiveModel());
variables.put("fetchHtml", getEmptyTemplateDirectiveModel());
variables.put("themeConfig", getEmptyTemplateDirectiveModel());
variables.put("appLink", getEmptyTemplateDirectiveModel());
config.setFreemarkerVariables(variables.build());
return config;
}
use of freemarker.cache.MultiTemplateLoader in project tephra by heisedebaise.
the class FreemarkerImpl method getConfiguration.
private Configuration getConfiguration() throws IOException {
if (configuration == null) {
synchronized (this) {
if (configuration == null) {
configuration = new Configuration(Configuration.VERSION_2_3_27);
configuration.setTemplateLoader(new MultiTemplateLoader(new TemplateLoader[] { new FileTemplateLoader(new File(context.getAbsolutePath(root))), stringTemplateLoader = new StringTemplateLoader() }));
configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_27));
configuration.setTemplateExceptionHandler((e, env, out) -> logger.warn(e, "解析FreeMarker模板时发生异常!"));
}
}
}
return configuration;
}
use of freemarker.cache.MultiTemplateLoader in project ofbiz-framework by apache.
the class FreeMarkerWorker method makeConfiguration.
public static Configuration makeConfiguration(BeansWrapper wrapper) {
Configuration newConfig = newConfiguration();
newConfig.setObjectWrapper(wrapper);
TemplateHashModel staticModels = wrapper.getStaticModels();
newConfig.setSharedVariable("Static", staticModels);
try {
newConfig.setSharedVariable("EntityQuery", staticModels.get("org.apache.ofbiz.entity.util.EntityQuery"));
} catch (TemplateModelException e) {
Debug.logError(e, module);
}
newConfig.setLocalizedLookup(false);
newConfig.setSharedVariable("StringUtil", new BeanModel(StringUtil.INSTANCE, wrapper));
TemplateLoader[] templateLoaders = { new FlexibleTemplateLoader(), new StringTemplateLoader() };
MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(templateLoaders);
newConfig.setTemplateLoader(multiTemplateLoader);
Map<?, ?> freemarkerImports = UtilProperties.getProperties("freemarkerImports");
if (freemarkerImports != null) {
newConfig.setAutoImports(freemarkerImports);
}
newConfig.setLogTemplateExceptions(false);
newConfig.setTemplateExceptionHandler(new FreeMarkerWorker.OFBizTemplateExceptionHandler());
try {
newConfig.setSetting("datetime_format", "yyyy-MM-dd HH:mm:ss.SSS");
newConfig.setSetting("number_format", "0.##########");
} catch (TemplateException e) {
Debug.logError("Unable to set date/time and number formats in FreeMarker: " + e, module);
}
// Transforms properties file set up as key=transform name, property=transform class name
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> resources;
try {
resources = loader.getResources("freemarkerTransforms.properties");
} catch (IOException e) {
Debug.logError(e, "Could not load list of freemarkerTransforms.properties", module);
throw UtilMisc.initCause(new InternalError(e.getMessage()), e);
}
while (resources.hasMoreElements()) {
URL propertyURL = resources.nextElement();
Debug.logInfo("loading properties: " + propertyURL, module);
Properties props = UtilProperties.getProperties(propertyURL);
if (UtilValidate.isEmpty(props)) {
Debug.logError("Unable to locate properties file " + propertyURL, module);
} else {
loadTransforms(loader, props, newConfig);
}
}
return newConfig;
}
use of freemarker.cache.MultiTemplateLoader in project freemarker by apache.
the class InitParamParser method createTemplateLoader.
static TemplateLoader createTemplateLoader(String templatePath, Configuration cfg, Class classLoaderClass, ServletContext srvCtx) throws IOException {
final int settingAssignmentsStart = findTemplatePathSettingAssignmentsStart(templatePath);
String pureTemplatePath = (settingAssignmentsStart == -1 ? templatePath : templatePath.substring(0, settingAssignmentsStart)).trim();
final TemplateLoader templateLoader;
if (pureTemplatePath.startsWith(TEMPLATE_PATH_PREFIX_CLASS)) {
String packagePath = pureTemplatePath.substring(TEMPLATE_PATH_PREFIX_CLASS.length());
packagePath = normalizeToAbsolutePackagePath(packagePath);
templateLoader = new ClassTemplateLoader(classLoaderClass, packagePath);
} else if (pureTemplatePath.startsWith(TEMPLATE_PATH_PREFIX_CLASSPATH)) {
// To be similar to Spring resource paths, we don't require "//":
String packagePath = pureTemplatePath.substring(TEMPLATE_PATH_PREFIX_CLASSPATH.length());
packagePath = normalizeToAbsolutePackagePath(packagePath);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
LOG.warn("No Thread Context Class Loader was found. Falling back to the class loader of " + classLoaderClass.getName() + ".");
classLoader = classLoaderClass.getClassLoader();
}
templateLoader = new ClassTemplateLoader(classLoader, packagePath);
} else if (pureTemplatePath.startsWith(TEMPLATE_PATH_PREFIX_FILE)) {
String filePath = pureTemplatePath.substring(TEMPLATE_PATH_PREFIX_FILE.length());
templateLoader = new FileTemplateLoader(new File(filePath));
} else if (pureTemplatePath.startsWith("[") && cfg.getIncompatibleImprovements().intValue() >= _TemplateAPI.VERSION_INT_2_3_22) {
if (!pureTemplatePath.endsWith("]")) {
// B.C. constraint: Can't throw any checked exceptions.
throw new TemplatePathParsingException("Failed to parse template path; closing \"]\" is missing.");
}
String commaSepItems = pureTemplatePath.substring(1, pureTemplatePath.length() - 1).trim();
List listItems = parseCommaSeparatedTemplatePaths(commaSepItems);
TemplateLoader[] templateLoaders = new TemplateLoader[listItems.size()];
for (int i = 0; i < listItems.size(); i++) {
String pathItem = (String) listItems.get(i);
templateLoaders[i] = createTemplateLoader(pathItem, cfg, classLoaderClass, srvCtx);
}
templateLoader = new MultiTemplateLoader(templateLoaders);
} else if (pureTemplatePath.startsWith("{") && cfg.getIncompatibleImprovements().intValue() >= _TemplateAPI.VERSION_INT_2_3_22) {
throw new TemplatePathParsingException("Template paths starting with \"{\" are reseved for future purposes");
} else {
templateLoader = new WebappTemplateLoader(srvCtx, pureTemplatePath);
}
if (settingAssignmentsStart != -1) {
try {
int nextPos = _ObjectBuilderSettingEvaluator.configureBean(templatePath, templatePath.indexOf('(', settingAssignmentsStart) + 1, templateLoader, _SettingEvaluationEnvironment.getCurrent());
if (nextPos != templatePath.length()) {
throw new TemplatePathParsingException("Template path should end after the setting list in: " + templatePath);
}
} catch (Exception e) {
throw new TemplatePathParsingException("Failed to set properties in: " + templatePath, e);
}
}
return templateLoader;
}
use of freemarker.cache.MultiTemplateLoader in project freemarker by apache.
the class TemplateNotFoundMessageTest method testMultiTemplateLoader.
@Test
public void testMultiTemplateLoader() throws IOException {
final String errMsg = failWith(new MultiTemplateLoader(new TemplateLoader[] { new WebappTemplateLoader(new MockServletContext(), "WEB-INF/templates"), new ClassTemplateLoader(this.getClass(), "foo/bar") }));
showErrorMessage(errMsg);
assertThat(errMsg, containsString("MultiTemplateLoader"));
assertThat(errMsg, containsString("WebappTemplateLoader"));
assertThat(errMsg, containsString("MyApp"));
assertThat(errMsg, containsString("WEB-INF/templates"));
assertThat(errMsg, containsString("ClassTemplateLoader"));
assertThat(errMsg, containsString("foo/bar"));
}
Aggregations