Search in sources :

Example 1 with MultiTemplateLoader

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;
}
Also used : TemplateLoader(freemarker.cache.TemplateLoader) FileTemplateLoader(freemarker.cache.FileTemplateLoader) MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) ArrayList(java.util.ArrayList) FreeMarkerConfigurer(org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer) ImmutableMap(com.google.common.collect.ImmutableMap) MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) ReplaceParametersDirective(org.ambraproject.wombat.freemarker.ReplaceParametersDirective) FileTemplateLoader(freemarker.cache.FileTemplateLoader) File(java.io.File) Iso8601DateDirective(org.ambraproject.wombat.freemarker.Iso8601DateDirective) Bean(org.springframework.context.annotation.Bean)

Example 2 with MultiTemplateLoader

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;
}
Also used : MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) StringTemplateLoader(freemarker.cache.StringTemplateLoader) Configuration(freemarker.template.Configuration) StringTemplateLoader(freemarker.cache.StringTemplateLoader) TemplateLoader(freemarker.cache.TemplateLoader) FileTemplateLoader(freemarker.cache.FileTemplateLoader) MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) DefaultObjectWrapper(freemarker.template.DefaultObjectWrapper) FileTemplateLoader(freemarker.cache.FileTemplateLoader) File(java.io.File)

Example 3 with MultiTemplateLoader

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;
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) Configuration(freemarker.template.Configuration) BeanModel(freemarker.ext.beans.BeanModel) TemplateException(freemarker.template.TemplateException) StringTemplateLoader(freemarker.cache.StringTemplateLoader) URLTemplateLoader(freemarker.cache.URLTemplateLoader) TemplateLoader(freemarker.cache.TemplateLoader) MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) IOException(java.io.IOException) UtilProperties(org.apache.ofbiz.base.util.UtilProperties) Properties(java.util.Properties) URL(java.net.URL) StringTemplateLoader(freemarker.cache.StringTemplateLoader) MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) TemplateHashModel(freemarker.template.TemplateHashModel)

Example 4 with MultiTemplateLoader

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;
}
Also used : MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) WebappTemplateLoader(freemarker.cache.WebappTemplateLoader) ClassTemplateLoader(freemarker.cache.ClassTemplateLoader) TemplateLoader(freemarker.cache.TemplateLoader) WebappTemplateLoader(freemarker.cache.WebappTemplateLoader) FileTemplateLoader(freemarker.cache.FileTemplateLoader) MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) ClassTemplateLoader(freemarker.cache.ClassTemplateLoader) ArrayList(java.util.ArrayList) List(java.util.List) FileTemplateLoader(freemarker.cache.FileTemplateLoader) File(java.io.File) IOException(java.io.IOException) ParseException(java.text.ParseException)

Example 5 with MultiTemplateLoader

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"));
}
Also used : MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) WebappTemplateLoader(freemarker.cache.WebappTemplateLoader) ClassTemplateLoader(freemarker.cache.ClassTemplateLoader) StringTemplateLoader(freemarker.cache.StringTemplateLoader) TemplateLoader(freemarker.cache.TemplateLoader) WebappTemplateLoader(freemarker.cache.WebappTemplateLoader) FileTemplateLoader(freemarker.cache.FileTemplateLoader) MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) ClassTemplateLoader(freemarker.cache.ClassTemplateLoader) Test(org.junit.Test)

Aggregations

MultiTemplateLoader (freemarker.cache.MultiTemplateLoader)15 TemplateLoader (freemarker.cache.TemplateLoader)12 Configuration (freemarker.template.Configuration)11 FileTemplateLoader (freemarker.cache.FileTemplateLoader)8 File (java.io.File)7 ClassTemplateLoader (freemarker.cache.ClassTemplateLoader)6 WebappTemplateLoader (freemarker.cache.WebappTemplateLoader)5 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 StringTemplateLoader (freemarker.cache.StringTemplateLoader)4 ImmutableMap (com.google.common.collect.ImmutableMap)2 Test (org.junit.jupiter.api.Test)2 UnexpectedServerException (com.pratilipi.common.exception.UnexpectedServerException)1 ByteArrayTemplateLoader (freemarker.cache.ByteArrayTemplateLoader)1 StrongCacheStorage (freemarker.cache.StrongCacheStorage)1 URLTemplateLoader (freemarker.cache.URLTemplateLoader)1 BeanModel (freemarker.ext.beans.BeanModel)1 DefaultObjectWrapper (freemarker.template.DefaultObjectWrapper)1 DefaultObjectWrapperBuilder (freemarker.template.DefaultObjectWrapperBuilder)1 TemplateException (freemarker.template.TemplateException)1