freemarker.cache.FileTemplateLoader Java Examples

The following examples show how to use freemarker.cache.FileTemplateLoader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DrillRestServer.java    From Bats with Apache License 2.0 7 votes vote down vote up
/**
 * Creates freemarker configuration settings,
 * default output format to trigger auto-escaping policy
 * and template loaders.
 *
 * @param servletContext servlet context
 * @return freemarker configuration settings
 */
private Configuration getFreemarkerConfiguration(ServletContext servletContext) {
  Configuration configuration = new Configuration(Configuration.VERSION_2_3_26);
  configuration.setOutputFormat(HTMLOutputFormat.INSTANCE);

  List<TemplateLoader> loaders = new ArrayList<>();
  loaders.add(new WebappTemplateLoader(servletContext));
  loaders.add(new ClassTemplateLoader(DrillRestServer.class, "/"));
  try {
    loaders.add(new FileTemplateLoader(new File("/")));
  } catch (IOException e) {
    logger.error("Could not set up file template loader.", e);
  }
  configuration.setTemplateLoader(new MultiTemplateLoader(loaders.toArray(new TemplateLoader[loaders.size()])));
  return configuration;
}
 
Example #2
Source File: PlacemarkUpdateServlet.java    From collect-earth with MIT License 6 votes vote down vote up
private void intializeTemplate() throws IOException {
	if (template == null) {
		
		// first check if there is a custom update template included on the customization that can be used for the project
		
		String possibleUpdateKmlLocation = localPropertiesService.getProjectFolder() + File.separatorChar + STANDARD_KML_FOR_UPDATES_FILENAME;
		File possibleKmlFile = new File( possibleUpdateKmlLocation );
		
		if( possibleKmlFile.exists() ){
			/*
			 * We need to create a new TemplateLoader and use it momentarily as by default the Template loader 
			 * uses the basedir of the project which causes problems when loading file from outside the project folder
			 */				
			cfg.setTemplateLoader( new FileTemplateLoader( new File( possibleKmlFile.getParent() ) ) );
			template = cfg.getTemplate( STANDARD_KML_FOR_UPDATES_FILENAME );
			
		}else{
			// No specific updatekml template found on the project folder, fall back to the general one
			// Load template from the resource folder
			cfg.setTemplateLoader( new FileTemplateLoader( new File( "." ) ) );
			template = cfg.getTemplate(GENERIC_KML_FOR_UPDATES);
		}
	}
}
 
Example #3
Source File: FreeMarkerRenderer.java    From opoopress with Apache License 2.0 6 votes vote down vote up
private TemplateLoader buildTemplateLoader(Site site) {
    try {
        List<TemplateLoader> loaders = new ArrayList<TemplateLoader>();
        loaders.add(new FileTemplateLoader(workingTemplateDir));
        loaders.add(new FileTemplateLoader(templateDir));
        loaders.add(new ClassTemplateLoader(AbstractFreeMarkerRenderer.class, "/org/opoo/press/templates"));

        //template registered by plugins
        List<TemplateLoader> instances = site.getFactory().getPluginManager().getObjectList(TemplateLoader.class);
        if (instances != null && !instances.isEmpty()) {
            loaders.addAll(instances);
        }

        TemplateLoader[] loadersArray = loaders.toArray(new TemplateLoader[loaders.size()]);
        return new MultiTemplateLoader(loadersArray);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #4
Source File: FtlUtils.java    From onetwo with Apache License 2.0 6 votes vote down vote up
public static TemplateLoader getTemplateLoaderForPath(ResourceLoader resourceLoader, String templateLoaderPath) {
	try {
		Resource path = resourceLoader.getResource(templateLoaderPath);
		File file = path.getFile();  // will fail if not resolvable in the file system
		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(resourceLoader, templateLoaderPath);
	}
	
}
 
Example #5
Source File: TemplateHelpers.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
public static Configuration getConfiguration(String... tempRoots) throws IOException {
    List<File> templateRootDirs = new ArrayList<File>(tempRoots.length);
    for (String fileName : tempRoots) {
        File file = FileHelpers.getFile(fileName);
        if (file.exists() && file.isDirectory()){
          templateRootDirs.add(file);
        }
    }

    Configuration conf = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
    FileTemplateLoader[] templateLoaders = new FileTemplateLoader[templateRootDirs.size()];
    for (int i = 0; i < templateRootDirs.size(); i++) {
        templateLoaders[i] = new FileTemplateLoader((File) templateRootDirs.get(i));
    }
    MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(templateLoaders);

    conf.setTemplateLoader(multiTemplateLoader);

    return conf;
}
 
Example #6
Source File: EmailConfiguration.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@Bean
public freemarker.template.Configuration getConfiguration() {
    final freemarker.template.Configuration configuration =
            new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_22);

    TemplateConfiguration tcHTML = new TemplateConfiguration();
    tcHTML.setOutputFormat(HTMLOutputFormat.INSTANCE);

    configuration.setTemplateConfigurations(
            new ConditionalTemplateConfigurationFactory(new FileExtensionMatcher(HTML_TEMPLATE_EXTENSION), tcHTML));

    try {
        configuration.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);
        configuration.setTemplateLoader(new FileTemplateLoader(new File(templatesPath)));
    } catch (final IOException e) {
        LOGGER.warn("Error occurred while trying to read email templates directory", e);
    }
    return configuration;
}
 
Example #7
Source File: CreateExtensionMojo.java    From quarkus with Apache License 2.0 6 votes vote down vote up
static TemplateLoader createTemplateLoader(File basedir, String templatesUriBase) throws IOException {
    final TemplateLoader defaultLoader = new ClassTemplateLoader(CreateExtensionMojo.class,
            DEFAULT_TEMPLATES_URI_BASE.substring(CLASSPATH_PREFIX.length()));
    if (DEFAULT_TEMPLATES_URI_BASE.equals(templatesUriBase)) {
        return defaultLoader;
    } else if (templatesUriBase.startsWith(CLASSPATH_PREFIX)) {
        return new MultiTemplateLoader( //
                new TemplateLoader[] { //
                        new ClassTemplateLoader(CreateExtensionMojo.class,
                                templatesUriBase.substring(CLASSPATH_PREFIX.length())), //
                        defaultLoader //
                });
    } else if (templatesUriBase.startsWith(FILE_PREFIX)) {
        final Path resolvedTemplatesDir = basedir.toPath().resolve(templatesUriBase.substring(FILE_PREFIX.length()));
        return new MultiTemplateLoader( //
                new TemplateLoader[] { //
                        new FileTemplateLoader(resolvedTemplatesDir.toFile()),
                        defaultLoader //
                });
    } else {
        throw new IllegalStateException(String.format(
                "Cannot handle templatesUriBase '%s'; only value starting with '%s' or '%s' are supported",
                templatesUriBase, CLASSPATH_PREFIX, FILE_PREFIX));
    }
}
 
Example #8
Source File: EmailConfiguration.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@Bean
public freemarker.template.Configuration getConfiguration() {
    final freemarker.template.Configuration configuration =
            new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_22);

    TemplateConfiguration tcHTML = new TemplateConfiguration();
    tcHTML.setOutputFormat(HTMLOutputFormat.INSTANCE);

    configuration.setTemplateConfigurations(
            new ConditionalTemplateConfigurationFactory(new FileExtensionMatcher(HTML_TEMPLATE_EXTENSION), tcHTML));

    try {
        configuration.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);
        configuration.setTemplateLoader(new FileTemplateLoader(new File(templatesPath)));
    } catch (final IOException e) {
        LOGGER.warn("Error occurred while trying to read email templates directory", e);
    }
    return configuration;
}
 
Example #9
Source File: WordprocessingMLFreemarkerTemplate_Test.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
@Before
public void Before() {
	
	//准备参数
       variables();
	
       freemarkerTemplate = new WordprocessingMLFreemarkerTemplate();
       
       try {
       	File dirFile = new File(WordprocessingMLFreemarkerTemplate_Test.class.getResource("/tpl/").getPath());
		freemarkerTemplate.setPreTemplateLoaders(new FileTemplateLoader(dirFile));
	} catch (IOException e) {
		e.printStackTrace();
	}
       
       
}
 
Example #10
Source File: FreemarkerTemplateEngineTest.java    From enkan with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void test() throws IOException {
    EnkanSystem system = EnkanSystem.of("freemarker", new FreemarkerTemplateEngine());
    FreemarkerTemplateEngine freemarker = system.getComponent("freemarker");
    FileTemplateLoader loader = new FileTemplateLoader(new File("src/test/resources"));
    freemarker.setTemplateLoader(loader);
    system.start();

    HttpResponse response = freemarker.render("file/hello");
    try(BufferedReader reader = new BufferedReader(new InputStreamReader(response.getBodyAsStream()))) {
        String line = reader.readLine();
        assertThat(line).isEqualTo("Hello, Freemarker");
    }

}
 
Example #11
Source File: FileResolverAdapter.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Override
public TemplateLoader adapt(ResourceResolver resolver) throws ResolverAdapterConfigurationException {
	try {
		return new FileTemplateLoader(baseDir, true);
	} catch (IOException e) {
		throw new ResolverAdapterConfigurationException("Invalid configuration for " + FileTemplateLoader.class.getSimpleName(), resolver, e);
	}
}
 
Example #12
Source File: FreeMarkerConfiguration.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Bean
public freemarker.template.Configuration getConfiguration() {
    final freemarker.template.Configuration configuration =
            new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_22);
    configuration.setLocalizedLookup(false);
    configuration.setOutputFormat(HTMLOutputFormat.INSTANCE);
    configuration.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);
    try {
        TemplateLoader[] templateLoaders = { overrideTemplateLoader(), new FileTemplateLoader(new File(templatesPath)) };
        configuration.setTemplateLoader(new MultiTemplateLoader(templateLoaders));
    } catch (final IOException e) {
        LOGGER.warn("Error occurred while trying to read email templates", e);
    }
    return configuration;
}
 
Example #13
Source File: FreeMarkerConfigurationFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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()) {
		// Try to load via the file system, fall back to SpringTemplateLoader
		// (for hot detection of template changes, if possible).
		try {
			Resource path = getResourceLoader().getResource(templateLoaderPath);
			File file = path.getFile();  // will fail if not resolvable in the file system
			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);
	}
}
 
Example #14
Source File: FreeMarkerConfigurationFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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()) {
		// Try to load via the file system, fall back to SpringTemplateLoader
		// (for hot detection of template changes, if possible).
		try {
			Resource path = getResourceLoader().getResource(templateLoaderPath);
			File file = path.getFile();  // will fail if not resolvable in the file system
			if (logger.isDebugEnabled()) {
				logger.debug(
						"Template loader path [" + path + "] resolved to file path [" + file.getAbsolutePath() + "]");
			}
			return new FileTemplateLoader(file);
		}
		catch (Exception 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);
	}
}
 
Example #15
Source File: TestHelper.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
/**
 * Render the expected template and compare it with the given actual file.
 * The actual file must exist and be identical to the rendered template,
 * otherwise assert errors will be thrown.
 *
 * @param outputdir the output directory where to render the expected template
 * @param expectedTpl the template used for comparing the actual file
 * @param actual the rendered file to be compared
 * @throws Exception if an error occurred
 */
public static void assertRendering(File outputdir, File expectedTpl, File actual)
        throws Exception {

    assertTrue(actual.exists(), actual.getAbsolutePath() + " does not exist");

    // render expected
    FileTemplateLoader ftl = new FileTemplateLoader(expectedTpl.getParentFile());
    Configuration config = new Configuration(Configuration.VERSION_2_3_23);
    config.setTemplateLoader(ftl);
    Template template = config.getTemplate(expectedTpl.getName());
    File expected = new File(outputdir, "expected_" + actual.getName());
    FileWriter writer = new FileWriter(expected);
    Map<String, Object> model = new HashMap<>();
    model.put("basedir", getBasedirPath());
    template.process(model, writer);

    // diff expected and rendered
    List<String> expectedLines = Files.readAllLines(expected.toPath());
    List<String> actualLines = Files.readAllLines(actual.toPath());

    // compare expected and rendered
    Patch<String> patch = DiffUtils.diff(expectedLines, actualLines);
    if (patch.getDeltas().size() > 0) {
        fail("rendered file " + actual.getAbsolutePath() + " differs from expected: " + patch.toString());
    }
}
 
Example #16
Source File: Generator.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Configuration newFreeMarkerConfiguration(List<File> templateRootDirs,
                                                               String defaultEncoding,
                                                               String templateName)
                throws IOException {
            Configuration conf = new Configuration();

            FileTemplateLoader[] templateLoaders = new FileTemplateLoader[templateRootDirs.size()];
            for (int i = 0; i < templateRootDirs.size(); i++) {
                templateLoaders[i] = new FileTemplateLoader((File) templateRootDirs.get(i));
            }
            MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(templateLoaders);

            conf.setTemplateLoader(multiTemplateLoader);
            conf.setNumberFormat("###############");
            conf.setBooleanFormat("true,false");
            conf.setDefaultEncoding(defaultEncoding);

            final String macro_include_ftl ="macro.include.ftl";
            String autoIncludes = new File(new File(templateName).getParent(),macro_include_ftl).getPath();
            List<String> availableAutoInclude = TemplateHelpers.getAvailableAutoInclude(conf, Arrays.asList(macro_include_ftl,autoIncludes));
            conf.setAutoIncludes(availableAutoInclude);
            GLogger.info("[set Freemarker.autoIncludes]"+availableAutoInclude+" for templateName:"+templateName);

//            GLogger.info(templateName);
//            List<String> autoIncludes = getParentPaths(templateName, "macro.include.ftl");
//            GLogger.info(autoIncludes.toString());
//            List<String> availableAutoInclude = TemplateHelpers.getAvailableAutoInclude(
//                conf, autoIncludes);
            conf.setAutoIncludes(availableAutoInclude);

            GLogger.trace("set Freemarker.autoIncludes:" + availableAutoInclude
                    + " for templateName:" + templateName + " autoIncludes:" + autoIncludes);
            return conf;
        }
 
Example #17
Source File: FreeMarkerConfigurationFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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()) {
		// Try to load via the file system, fall back to SpringTemplateLoader
		// (for hot detection of template changes, if possible).
		try {
			Resource path = getResourceLoader().getResource(templateLoaderPath);
			File file = path.getFile();  // will fail if not resolvable in the file system
			if (logger.isDebugEnabled()) {
				logger.debug(
						"Template loader path [" + path + "] resolved to file path [" + file.getAbsolutePath() + "]");
			}
			return new FileTemplateLoader(file);
		}
		catch (Exception 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);
	}
}
 
Example #18
Source File: FreeMarkerConfigurationFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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()) {
		// Try to load via the file system, fall back to SpringTemplateLoader
		// (for hot detection of template changes, if possible).
		try {
			Resource path = getResourceLoader().getResource(templateLoaderPath);
			File file = path.getFile();  // will fail if not resolvable in the file system
			if (logger.isDebugEnabled()) {
				logger.debug(
						"Template loader path [" + path + "] resolved to file path [" + file.getAbsolutePath() + "]");
			}
			return new FileTemplateLoader(file);
		}
		catch (Exception 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);
	}
}
 
Example #19
Source File: CqUtils.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
static TemplateLoader createTemplateLoader(Path basePath, String defaultUriBase, String templatesUriBase) {
    final TemplateLoader defaultLoader = new ClassTemplateLoader(CqUtils.class,
            defaultUriBase.substring(CLASSPATH_PREFIX.length()));
    if (defaultUriBase.equals(templatesUriBase)) {
        return defaultLoader;
    } else if (templatesUriBase.startsWith(CLASSPATH_PREFIX)) {
        return new MultiTemplateLoader( //
                new TemplateLoader[] { //
                        new ClassTemplateLoader(CqUtils.class,
                                templatesUriBase.substring(CLASSPATH_PREFIX.length())), //
                        defaultLoader //
                });
    } else if (templatesUriBase.startsWith(FILE_PREFIX)) {
        final Path resolvedTemplatesDir = basePath.resolve(templatesUriBase.substring(FILE_PREFIX.length()));
        try {
            return new MultiTemplateLoader( //
                    new TemplateLoader[] { //
                            new FileTemplateLoader(resolvedTemplatesDir.toFile()),
                            defaultLoader //
                    });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else {
        throw new IllegalStateException(String.format(
                "Cannot handle templatesUriBase '%s'; only value starting with '%s' or '%s' are supported",
                templatesUriBase, CLASSPATH_PREFIX, FILE_PREFIX));
    }
}
 
Example #20
Source File: TemplateServiceFreemarkerImpl.java    From Dolphin with Apache License 2.0 4 votes vote down vote up
@PostConstruct
public void init() throws Exception {
    cfg = new Configuration();
    cfg.setTemplateLoader(new FileTemplateLoader(new File("/")));
}