freemarker.cache.TemplateLoader Java Examples

The following examples show how to use freemarker.cache.TemplateLoader. 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: SkipLocaleForStringContentTemplateLookupStrategy.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Override
public TemplateLookupResult lookup(TemplateLookupContext ctx) throws IOException {
	try {
		ResourceResolver matchingResolver = resolverRegistry.getSupportingResolver(new UnresolvedPath(ctx.getTemplateName()));
		// no match, delegate to let delegate decide
		if (matchingResolver == null) {
			return delegate.lookup(ctx);
		}
		TemplateLoader matchingAdapter = adapter.adapt(matchingResolver);
		// if it is a template content (directly a string)
		// => skip locale resolution
		if (matchingAdapter instanceof StringContentTemplateLoader) {
			return ctx.lookupWithLocalizedThenAcquisitionStrategy(ctx.getTemplateName(), null);
		}
		// standard Freemarker behavior
		return delegate.lookup(ctx);
	} catch (ResolverAdapterException e) {
		LOG.debug("Failed to determine which Freemarker adapter to use for template name " + ctx.getTemplateName(), e);
		return delegate.lookup(ctx);
	}
}
 
Example #3
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 #4
Source File: FreemarkerTemplateEngine.java    From enkan with Eclipse Public License 1.0 6 votes vote down vote up
private TemplateLoader createTemplateLoader() {
    TemplateLoader classTemplateLoader = new ClassTemplateLoader(classLoader, prefix);
    if (templateLoader != null) {
        if (templateLoader instanceof MultiTemplateLoader) {
            MultiTemplateLoader mtl = (MultiTemplateLoader) templateLoader;
            TemplateLoader[] loaders = new TemplateLoader[mtl.getTemplateLoaderCount() + 1];
            for(int i=0; i < mtl.getTemplateLoaderCount(); i++) {
                loaders[i] = mtl.getTemplateLoader(i);
            }
            loaders[mtl.getTemplateLoaderCount() + 1] = classTemplateLoader;
            return new MultiTemplateLoader(loaders);

        } else {
            return new MultiTemplateLoader(new TemplateLoader[]{templateLoader, classTemplateLoader});
        }
    } else {
        return classTemplateLoader;
    }
}
 
Example #5
Source File: PluginTemplateLoader.java    From onetwo with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args){
	PluginTemplateLoader j = new PluginTemplateLoader(new TemplateLoader[]{}, null);
	System.out.println(j.pluginNameParser.getPluginName("lib/test/test.ftl"));
	String path = "[codegen]/lib/test/test.ftl";
	String pname = j.pluginNameParser.getPluginName(path);
	System.out.println(pname);
	System.out.println(path.substring(pname.length()+j.pluginNameParser.getLength()));
	
	path = "[codegen]/test.ftl";
	pname = j.pluginNameParser.getPluginName(path);
	System.out.println(pname);
	System.out.println(path.substring(pname.length()+j.pluginNameParser.getLength()));
	
	path = "[[codegen-test";
	pname = j.pluginNameParser.getPluginName(path);
	System.out.println("[["+pname);
	System.out.println("[["+path.substring(pname.length()+j.pluginNameParser.getLength()));
	

}
 
Example #6
Source File: TemplateHelper.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected static String __processTemplate(TemplateLoader templateLoader, String templateName,
                                          Map<String, ?> parameterValues) {
    Map<String, Object> params = prepareParams(parameterValues);

    StringWriter writer = new StringWriter();

    try {
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setTemplateLoader(templateLoader);
        Template template = configuration.getTemplate(templateName);
        template.process(params, writer);

        return writer.toString();
    } catch (Throwable e) {
        throw new RuntimeException("Unable to process template", e);
    }
}
 
Example #7
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 #8
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 #9
Source File: AdminFreemarkerTemplateProvider.java    From karyon with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void commonConstruct() {
    // Just look for files in the class path
    fmConfig.setTemplateLoader(new MultiTemplateLoader(new TemplateLoader[]{
    		new ViewableResourceTemplateLoader(),
    		new ClassTemplateLoader(getClass(), "/"),
    		}));
    fmConfig.setNumberFormat("0");
    fmConfig.setLocalizedLookup(false);
    fmConfig.setTemplateUpdateDelay(0);

    try {
        if (manager != null) {
            fmConfig.setSharedVariable("Global", manager.getGlobalModel());
            fmConfig.setSharedVariable("Explorers", manager);
        }
        fmConfig.setSharedVariable("toJson", new ToJsonMethod());
    } catch (TemplateModelException e) {
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: FreeMarkerWorker.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends TemplateLoader> T getTemplateLoader(Configuration config, Class<T> templateLoaderClass) {
    TemplateLoader loader = config.getTemplateLoader();
    if (templateLoaderClass.isAssignableFrom(loader.getClass())) {
        return (T) loader;
    } else if (loader instanceof MultiTemplateLoader) {
        return getTemplateLoader((MultiTemplateLoader) loader, templateLoaderClass);
    }
    Debug.logWarning("No " + templateLoaderClass.getName() + " template loader class found for Freemarker Configuration " + config, module);
    return null;
}
 
Example #11
Source File: FreeMarkerConfigurationFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Return a TemplateLoader based on the given TemplateLoader list.
 * If more than one TemplateLoader has been registered, a FreeMarker
 * MultiTemplateLoader needs to be created.
 * @param templateLoaders the final List of TemplateLoader instances
 * @return the aggregate TemplateLoader
 */
@Nullable
protected TemplateLoader getAggregateTemplateLoader(List<TemplateLoader> templateLoaders) {
	switch (templateLoaders.size()) {
		case 0:
			logger.debug("No FreeMarker TemplateLoaders specified");
			return null;
		case 1:
			return templateLoaders.get(0);
		default:
			TemplateLoader[] loaders = templateLoaders.toArray(new TemplateLoader[0]);
			return new MultiTemplateLoader(loaders);
	}
}
 
Example #12
Source File: WordprocessingMLFreemarkerTemplate.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * Return a TemplateLoader based on the given TemplateLoader list.
 * If more than one TemplateLoader has been registered, a FreeMarker
 * MultiTemplateLoader needs to be created.
 * @param templateLoaders the final List of TemplateLoader instances
 * @return the aggregate TemplateLoader
 */
protected TemplateLoader getAggregateTemplateLoader(List<TemplateLoader> templateLoaders) {
	int loaderCount = templateLoaders.size();
	switch (loaderCount) {
		case 0:
			LOG.info("No FreeMarker TemplateLoaders specified");
			return null;
		case 1:
			return templateLoaders.get(0);
		default:
			TemplateLoader[] loaders = templateLoaders.toArray(new TemplateLoader[loaderCount]);
			return new MultiTemplateLoader(loaders);
	}
}
 
Example #13
Source File: FreeMarkerConfigurationFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return a TemplateLoader based on the given TemplateLoader list.
 * If more than one TemplateLoader has been registered, a FreeMarker
 * MultiTemplateLoader needs to be created.
 * @param templateLoaders the final List of TemplateLoader instances
 * @return the aggregate TemplateLoader
 */
protected TemplateLoader getAggregateTemplateLoader(List<TemplateLoader> templateLoaders) {
	int loaderCount = templateLoaders.size();
	switch (loaderCount) {
		case 0:
			logger.info("No FreeMarker TemplateLoaders specified");
			return null;
		case 1:
			return templateLoaders.get(0);
		default:
			TemplateLoader[] loaders = templateLoaders.toArray(new TemplateLoader[loaderCount]);
			return new MultiTemplateLoader(loaders);
	}
}
 
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: MolgenisWebAppConfig.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Configure freemarker. All freemarker templates should be on the classpath in a package called
 * 'freemarker'
 */
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() {
  FreeMarkerConfigurer result =
      new FreeMarkerConfigurer() {
        @Override
        protected void postProcessConfiguration(Configuration config) {
          config.setObjectWrapper(new MolgenisFreemarkerObjectWrapper(VERSION_2_3_23));
        }

        @Override
        protected void postProcessTemplateLoaders(List<TemplateLoader> templateLoaders) {
          templateLoaders.add(new ClassTemplateLoader(FreeMarkerConfigurer.class, ""));
        }
      };
  result.setPreferFileSystemAccess(false);
  result.setTemplateLoaderPath("classpath:/templates/");
  result.setDefaultEncoding("UTF-8");
  Properties freemarkerSettings = new Properties();
  freemarkerSettings.setProperty(Configuration.LOCALIZED_LOOKUP_KEY, Boolean.FALSE.toString());
  freemarkerSettings.setProperty(Configuration.NUMBER_FORMAT_KEY, "computer");
  result.setFreemarkerSettings(freemarkerSettings);
  Map<String, Object> freemarkerVariables = Maps.newHashMap();
  freemarkerVariables.put("hasPermission", new HasPermissionDirective(permissionService));
  freemarkerVariables.put("notHasPermission", new NotHasPermissionDirective(permissionService));
  addFreemarkerVariables(freemarkerVariables);

  result.setFreemarkerVariables(freemarkerVariables);

  return result;
}
 
Example #16
Source File: FreeMarkerConfigurationFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Return a TemplateLoader based on the given TemplateLoader list.
 * If more than one TemplateLoader has been registered, a FreeMarker
 * MultiTemplateLoader needs to be created.
 * @param templateLoaders the final List of TemplateLoader instances
 * @return the aggregate TemplateLoader
 */
@Nullable
protected TemplateLoader getAggregateTemplateLoader(List<TemplateLoader> templateLoaders) {
	switch (templateLoaders.size()) {
		case 0:
			logger.debug("No FreeMarker TemplateLoaders specified");
			return null;
		case 1:
			return templateLoaders.get(0);
		default:
			TemplateLoader[] loaders = templateLoaders.toArray(new TemplateLoader[0]);
			return new MultiTemplateLoader(loaders);
	}
}
 
Example #17
Source File: EmailHelperTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Before
public void setup() throws Exception
{
    this.dummyTemplateNodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, GUID.generate());
    // Mock the required services
    this.serviceRegistryMock = mock(ServiceRegistry.class);
    this.nodeServiceMock = mock(NodeService.class);
    this.searchServiceMock = mock(SearchService.class);
    this.namespaceServiceMock = mock(NamespaceService.class);
    this.fileFolderServiceMock = mock(FileFolderService.class);
    this.personServiceMock = mock(PersonService.class);
    this.preferenceServiceMock = mock(PreferenceService.class);
    this.repositoryHelperMock = mock(Repository.class);
    this.templateLoaderMock = mock(TemplateLoader.class);

    when(serviceRegistryMock.getNodeService()).thenReturn(nodeServiceMock);
    when(serviceRegistryMock.getSearchService()).thenReturn(searchServiceMock);
    when(serviceRegistryMock.getNamespaceService()).thenReturn(namespaceServiceMock);
    when(serviceRegistryMock.getFileFolderService()).thenReturn(fileFolderServiceMock);
    when(serviceRegistryMock.getPersonService()).thenReturn(personServiceMock);
    when(serviceRegistryMock.getContentService()).thenReturn(mock(ContentService.class));
    when(repositoryHelperMock.getRootHome()).thenReturn(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, GUID.generate()));
    when(fileFolderServiceMock.getLocalizedSibling(dummyTemplateNodeRef)).thenReturn(dummyTemplateNodeRef);

    this.emailHelper = new EmailHelper();
    emailHelper.setServiceRegistry(serviceRegistryMock);
    emailHelper.setPreferenceService(preferenceServiceMock);
    emailHelper.setRepositoryHelper(repositoryHelperMock);
    emailHelper.setCompanyHomeChildName("app:company_home");
    //test init
    emailHelper.init();
    // Note: set the template loader after the init method
    emailHelper.setTemplateLoader(templateLoaderMock);
}
 
Example #18
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 #19
Source File: ScipioFtlTemplateLoader.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/** Gets the configured instance, expected to match the default instance unless extended. Not expected to return null unless misconfiguration. */
public static ScipioFtlTemplateLoader getInstance(Configuration config) {
    TemplateLoader loader = config.getTemplateLoader();
    if (loader instanceof MultiTemplateLoader) {
        loader = FreeMarkerWorker.getTemplateLoader((MultiTemplateLoader) loader, ScipioFtlTemplateLoader.class);
    }
    return (ScipioFtlTemplateLoader) loader;
}
 
Example #20
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 #21
Source File: FreeMarkerConfigurationFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return a TemplateLoader based on the given TemplateLoader list.
 * If more than one TemplateLoader has been registered, a FreeMarker
 * MultiTemplateLoader needs to be created.
 * @param templateLoaders the final List of TemplateLoader instances
 * @return the aggregate TemplateLoader
 */
protected TemplateLoader getAggregateTemplateLoader(List<TemplateLoader> templateLoaders) {
	int loaderCount = templateLoaders.size();
	switch (loaderCount) {
		case 0:
			logger.info("No FreeMarker TemplateLoaders specified");
			return null;
		case 1:
			return templateLoaders.get(0);
		default:
			TemplateLoader[] loaders = templateLoaders.toArray(new TemplateLoader[loaderCount]);
			return new MultiTemplateLoader(loaders);
	}
}
 
Example #22
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 #23
Source File: AbstractFreemarkerTemplateConfigurer.java    From onetwo with Apache License 2.0 5 votes vote down vote up
/****
	 * must be invoke after contruction
	 */
	public void initialize() {
		if(isInitialized())
			return ;
		
		TemplateLoader loader = getTempateLoader();
		Assert.notNull(loader);
		try {
			this.configuration = new Configuration(Configuration.VERSION_2_3_0);
			this.configuration.setObjectWrapper(getBeansWrapper());
			this.configuration.setOutputEncoding(this.encoding);
			//设置默认不自动格式化数字……以防sb……
			this.configuration.setNumberFormat("#");
//			this.cfg.setDirectoryForTemplateLoading(new File(templateDir));
			
			/*if(templateProvider!=null){
				this.configuration.setTemplateLoader(new DynamicTemplateLoader(templateProvider));
			}*/
			if(LangUtils.isNotEmpty(getFreemarkerVariables()))
				configuration.setAllSharedVariables(new SimpleHash(freemarkerVariables, configuration.getObjectWrapper()));
			
			//template loader
			/*if(!LangUtils.isEmpty(templatePaths)){
				TemplateLoader loader = FtlUtils.getTemplateLoader(resourceLoader, templatePaths);
				this.configuration.setTemplateLoader(loader);
			}*/
			this.configuration.setTemplateLoader(loader);
			
			this.buildConfigration(this.configuration);
			
			initialized = true;
		} catch (Exception e) {
			throw new BaseException("create freemarker template error : " + e.getMessage(), e);
		}
	}
 
Example #24
Source File: FtlUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static TemplateLoader getTemplateLoader(ResourceLoader resourceLoader, String... templateLoaderPaths) {
	Assert.notEmpty(templateLoaderPaths);
	List<TemplateLoader> loaders = LangUtils.newArrayList(templateLoaderPaths.length);
	for(String path :templateLoaderPaths){
		TemplateLoader loader = getTemplateLoaderForPath(resourceLoader, path);
		loaders.add(loader);
	}
	return loaders.size()==1?loaders.get(0):getMultiTemplateLoader(loaders);
}
 
Example #25
Source File: PluginTemplateLoader.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public Object findPluginTemplateSource(PluginMeta meta, String name) throws IOException {
	if(meta==null)
		return null;
	TemplateLoader loader = pluginLoaders.get(meta.getName());
	Object source = loader.findTemplateSource(name);
	if (source != null) {
		return new MultiSource(source, loader);
	}
	
	return null;
}
 
Example #26
Source File: TextReporter.java    From revapi with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new FreeMarker configuration.
 * By default, it is configured as follows:
 * <ul>
 * <li>compatibility level is set to 2.3.23
 * <li>the object wrapper is configured to expose fields
 * <li>API builtins are enabled
 * <li>there are 2 template loaders - 1 for loading templates from /META-INF using a classloader and a second
 *     one to load templates from files.
 * </ul>
 * @return
 */
protected Configuration createFreeMarkerConfiguration() {
    DefaultObjectWrapperBuilder bld = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_23);
    bld.setExposeFields(true);

    Configuration freeMarker = new Configuration(Configuration.VERSION_2_3_23);

    freeMarker.setObjectWrapper(bld.build());
    freeMarker.setAPIBuiltinEnabled(true);
    freeMarker.setTemplateLoader(new MultiTemplateLoader(
            new TemplateLoader[]{new ClassTemplateLoader(getClass(), "/META-INF"),
                    new NaiveFileTemplateLoader()}));

    return freeMarker;
}
 
Example #27
Source File: PluginTemplateLoader.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public void resetState() {
	lastLoaderForName.clear();
	for (int i = 0; i < loaders.length; i++) {
		TemplateLoader loader = loaders[i];
		if (loader instanceof StatefulTemplateLoader) {
			((StatefulTemplateLoader) loader).resetState();
		}
	}
}
 
Example #28
Source File: PluginFreeMarkerConfigurer.java    From onetwo with Apache License 2.0 5 votes vote down vote up
protected TemplateLoader findPluginTemplateLoader(WebPlugin plugin){
	String templateLoaderPath = DEFAULT_PLUGIN_FTL_LOCATION + plugin.getPluginMeta().getName();
	TemplateLoader loader = getTemplateLoaderForPath(templateLoaderPath);
	if(logger.isInfoEnabled()){
		logger.info("add template loader from path : " + templateLoaderPath);
	}
	return loader;
}
 
Example #29
Source File: PluginFreeMarkerConfigurer.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
	protected TemplateLoader getAggregateTemplateLoader(List<TemplateLoader> templateLoaders) {
//		return super.getAggregateTemplateLoader(templateLoaders);
		/*int loaderCount = templateLoaders.size();
		switch (loaderCount) {
			case 0:
				logger.info("No FreeMarker TemplateLoaders specified");
				return null;
			case 1:
				return templateLoaders.get(0);
			default:
				TemplateLoader[] loaders = templateLoaders.toArray(new TemplateLoader[loaderCount]);
				PluginTemplateLoader pluginLoader = new PluginTemplateLoader(loaders, pluginManager);
//				if(this.pluginManager!=null) this.pluginManager.onTemplateLoader();
				pluginManager.getPlugins().forEach(plugin->{
					pluginLoader.putPluginTemplateLoader(plugin, findPluginTemplateLoader(plugin));
				});
				return pluginLoader;
		}*/
		
		TemplateLoader[] loaders = templateLoaders.toArray(new TemplateLoader[templateLoaders.size()]);
		PluginTemplateLoader pluginLoader = new PluginTemplateLoader(loaders, pluginManager);
//		if(this.pluginManager!=null) this.pluginManager.onTemplateLoader();
		pluginManager.getPlugins().forEach(plugin->{
			pluginLoader.putPluginTemplateLoader(plugin, findPluginTemplateLoader(plugin));
		});
		return pluginLoader;
	}
 
Example #30
Source File: FirstSupportingResolverAdapter.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Override
public TemplateLoader adapt(ResourceResolver resolver) throws ResolverAdapterException {
	for (TemplateLoaderAdapter adapter : adapters) {
		if (adapter.supports(resolver)) {
			return adapter.adapt(resolver);
		}
	}
	throw new NoResolverAdapterException("No resolver adapter found for the provided resolver: " + resolverName(resolver), resolver);
}