Search in sources :

Example 1 with FileTemplateLoader

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);
    }
}
Also used : Resource(org.springframework.core.io.Resource) IOException(java.io.IOException) FileTemplateLoader(freemarker.cache.FileTemplateLoader) File(java.io.File)

Example 2 with FileTemplateLoader

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);
    }
}
Also used : MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) Configuration(freemarker.template.Configuration) TemplateLoader(freemarker.cache.TemplateLoader) FileTemplateLoader(freemarker.cache.FileTemplateLoader) MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) FileTemplateLoader(freemarker.cache.FileTemplateLoader) ForumStartupException(net.jforum.exceptions.ForumStartupException) File(java.io.File) Date(java.util.Date) ServletException(javax.servlet.ServletException) ForumStartupException(net.jforum.exceptions.ForumStartupException)

Example 3 with FileTemplateLoader

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;
}
Also used : MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) Configuration(freemarker.template.Configuration) ClassTemplateLoader(freemarker.cache.ClassTemplateLoader) IOException(java.io.IOException) FileTemplateLoader(freemarker.cache.FileTemplateLoader) File(java.io.File)

Example 4 with FileTemplateLoader

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);
    }
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) TemplateModel(freemarker.template.TemplateModel) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) TemplateScalarModel(freemarker.template.TemplateScalarModel) FileTemplateLoader(freemarker.cache.FileTemplateLoader) Map(java.util.Map) File(java.io.File) TemplateBooleanModel(freemarker.template.TemplateBooleanModel) Writer(java.io.Writer)

Example 5 with FileTemplateLoader

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);
        }
    }
}
Also used : Configuration(freemarker.template.Configuration) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) FileTemplateLoader(freemarker.cache.FileTemplateLoader) JarFile(java.util.jar.JarFile) File(java.io.File) SequenceWriter(com.fasterxml.jackson.databind.SequenceWriter) OutputStreamWriter(java.io.OutputStreamWriter) StringWriter(java.io.StringWriter) Writer(java.io.Writer) Template(freemarker.template.Template)

Aggregations

FileTemplateLoader (freemarker.cache.FileTemplateLoader)5 File (java.io.File)5 IOException (java.io.IOException)4 Configuration (freemarker.template.Configuration)3 MultiTemplateLoader (freemarker.cache.MultiTemplateLoader)2 Writer (java.io.Writer)2 SequenceWriter (com.fasterxml.jackson.databind.SequenceWriter)1 UnexpectedServerException (com.pratilipi.common.exception.UnexpectedServerException)1 ClassTemplateLoader (freemarker.cache.ClassTemplateLoader)1 TemplateLoader (freemarker.cache.TemplateLoader)1 Template (freemarker.template.Template)1 TemplateBooleanModel (freemarker.template.TemplateBooleanModel)1 TemplateModel (freemarker.template.TemplateModel)1 TemplateModelException (freemarker.template.TemplateModelException)1 TemplateScalarModel (freemarker.template.TemplateScalarModel)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 OutputStreamWriter (java.io.OutputStreamWriter)1 StringWriter (java.io.StringWriter)1 Date (java.util.Date)1