Java Code Examples for freemarker.template.Configuration#setSharedVariable()

The following examples show how to use freemarker.template.Configuration#setSharedVariable() . 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: SourceReportGenerator.java    From testability-explorer with Apache License 2.0 6 votes vote down vote up
public SourceReportGenerator(GradeCategories grades, SourceLoader sourceLoader,
    File outputDirectory, CostModel costModel, Date currentTime,
    int worstCount, Configuration cfg) {
  this.grades = grades;
  this.sourceLoader = sourceLoader;
  this.directory = outputDirectory;
  this.costModel = costModel;
  this.cfg = cfg;
  cfg.setTemplateLoader(new ClassPathTemplateLoader(PREFIX));
  cfg.setObjectWrapper(new DefaultObjectWrapper());
  try {
    cfg.setSharedVariable("maxExcellentCost", grades.getMaxExcellentCost());
    cfg.setSharedVariable("maxAcceptableCost", grades.getMaxAcceptableCost());
    cfg.setSharedVariable("currentTime", currentTime);
    cfg.setSharedVariable("computeOverallCost", new OverallCostMethod());
    cfg.setSharedVariable("printCost", new PrintCostMethod());
  } catch (TemplateModelException e) {
    throw new RuntimeException(e);
  }
  projectByClassReport = new ProjectReport("index", grades,
      new WeightedAverage());
  projectByClassReport.setMaxUnitCosts(worstCount);
  projectByPackageReport = new ProjectReport("index", grades,
      new WeightedAverage());
}
 
Example 2
Source File: FreeMarkerConfigFactory.java    From youran with Apache License 2.0 5 votes vote down vote up
/**
 * 构建freemarker配置
 *
 * @param templatePO
 * @return (freemarker配置 , 模板内部版本号 , 模板目录地址)
 */
private Triple<Configuration, Integer, String> buildTriple(CodeTemplatePO templatePO) {
    String templateDir = dataDirService.getTemplateRecentDir(templatePO);
    LOGGER.info("开始构建FreeMarker Configuration,templateId={},innerVersion={},模板文件输出目录:{}",
        templatePO.getTemplateId(), templatePO.getInnerVersion(), templateDir);
    // 把模板输出到目录
    templateFileOutputService.outputTemplateFiles(templatePO.getTemplateFiles(), templateDir);

    Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
    try {
        cfg.setDirectoryForTemplateLoading(new File(templateDir));
    } catch (IOException e) {
        LOGGER.error("模板目录设置异常", e);
        throw new BusinessException("模板目录设置异常");
    }
    cfg.setNumberFormat("#");
    // 设置可访问的静态工具类
    cfg.setSharedVariable("MetaConstType", metaConstTypeModel);
    cfg.setSharedVariable("JFieldType", jFieldTypeModel);
    cfg.setSharedVariable("QueryType", queryTypeModel);
    cfg.setSharedVariable("EditType", editTypeModel);
    cfg.setSharedVariable("MetaSpecialField", metaSpecialFieldModel);
    cfg.setSharedVariable("PrimaryKeyStrategy", primaryKeyStrategyModel);
    cfg.setSharedVariable("CommonTemplateFunction", commonTemplateFunctionModel);
    cfg.setSharedVariable("JavaTemplateFunction", javaTemplateFunctionModel);
    cfg.setSharedVariable("SqlTemplateFunction", sqlTemplateFunctionModel);
    return Triple.of(cfg, templatePO.getInnerVersion(), templateDir);
}
 
Example 3
Source File: FreeMarkerConfigExtend.java    From belling-admin with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws IOException, TemplateException {
	super.afterPropertiesSet();
	Configuration cfg = this.getConfiguration();
	cfg.setSharedVariable("shiro", new ShiroTags());// shiro标签
	cfg.setNumberFormat("#");// 防止页面输出数字,变成2,000
	// 可以添加很多自己的要传输到页面的[方法、对象、值]
}
 
Example 4
Source File: CmsRenderTemplate.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Protected helper method.
 * <p>
 * SCIPIO: TODO: delegate to FreeMarkerWorker and remove license notice
 */
protected static void loadTransforms(ClassLoader loader, Properties props, Configuration config) {
    for (Iterator<Object> i = props.keySet().iterator(); i.hasNext();) {
        String key = (String) i.next();
        String className = props.getProperty(key);
        if (Debug.verboseOn()) {
            Debug.logVerbose("Adding FTL Transform " + key + " with class " + className, module);
        }
        try {
            config.setSharedVariable(key, FreeMarkerWorker.getTransformInstance(className, loader));
        } catch (Exception e) {
            Debug.logError(e, "Could not pre-initialize dynamically loaded class: " + className + ": " + e, module);
        }
    }
}
 
Example 5
Source File: FreeMarkerWorker.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
private static void loadTransforms(ClassLoader loader, Properties props, Configuration config) {
    for (Object object : props.keySet()) {
        String key = (String) object;
        String className = props.getProperty(key);
        if (Debug.verboseOn()) {
            Debug.logVerbose("Adding FTL Transform " + key + " with class " + className, module);
        }
        try {
            config.setSharedVariable(key, getTransformInstance(className, loader)); // SCIPIO: getTransformInstance
        } catch (Exception e) {
            Debug.logError(e, "Could not pre-initialize dynamically loaded class: " + className + ": " + e, module);
        }
    }
}
 
Example 6
Source File: FreeMarkerWorker.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * SCIPIO: Loads shared vars.
 */
protected static void loadSharedVars(Properties props, Configuration config) {
    for (Iterator<Object> i = props.keySet().iterator(); i.hasNext();) {
        String key = (String) i.next();
        String value = props.getProperty(key);
        if (Debug.verboseOn()) {
            Debug.logVerbose("Adding FTL shared var " + key + " with value " + value, module);
        }
        try {
            config.setSharedVariable(key, value);
        } catch (Exception e) {
            Debug.logError(e, "Could not pre-initialize dynamically loaded shared var: " + key + ": " + e, module);
        }
    }
}
 
Example 7
Source File: FreemarkerConfigurationBuilder.java    From ogham with Apache License 2.0 5 votes vote down vote up
private void buildSharedVariables(Configuration configuration) {
	try {
		if (variablesHash != null) {
			configuration.setAllSharedVariables(variablesHash);
		}
		for (Entry<String, Object> entry : sharedVariables.entrySet()) {
			configuration.setSharedVariable(entry.getKey(), entry.getValue());
		}
	} catch (TemplateModelException e) {
		throw new BuildException("Failed to configure FreeMarker shared variables", e);
	}
}
 
Example 8
Source File: FreemarkerConfigurationBuilder.java    From ogham with Apache License 2.0 5 votes vote down vote up
private void buildStaticMethodAccess(Configuration configuration) {
	boolean enableStaticMethods = enableStaticMethodAccessValueBuilder.getValue(false);
	if (enableStaticMethods) {
		String staticsVariableName = staticMethodAccessVariableNameValueBuilder.getValue();
		configuration.setSharedVariable(staticsVariableName, getBeansWrapper(configuration).getStaticModels());
	}
}
 
Example 9
Source File: WordprocessingMLFreemarkerTemplate.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
protected Configuration getInternalEngine() throws IOException, TemplateException{
	
	try {
		BeansWrapper beansWrapper = new BeansWrapper(Configuration.VERSION_2_3_23);
		this.templateModel = beansWrapper.getStaticModels().get(String.class.getName());
	} catch (TemplateModelException e) {
		throw new IOException(e.getMessage(),e.getCause());
	}

	// 创建 Configuration 实例
	Configuration config = new Configuration(Configuration.VERSION_2_3_23);
	
	Properties props = ConfigUtils.filterWithPrefix("docx4j.freemarker.", "docx4j.freemarker.", Docx4jProperties.getProperties(), false);

	// FreeMarker will only accept known keys in its setSettings and
	// setAllSharedVariables methods.
	if (!props.isEmpty()) {
		config.setSettings(props);
	}

	if (this.freemarkerVariables != null && !this.freemarkerVariables.isEmpty()) {
		config.setAllSharedVariables(new SimpleHash(this.freemarkerVariables, config.getObjectWrapper()));
	}

	if (this.defaultEncoding != null) {
		config.setDefaultEncoding(this.defaultEncoding);
	}

	List<TemplateLoader> templateLoaders = new LinkedList<TemplateLoader>(this.templateLoaders);
	
	// Register template loaders that are supposed to kick in early.
	if (this.preTemplateLoaders != null) {
		templateLoaders.addAll(this.preTemplateLoaders);
	}
	
	postProcessTemplateLoaders(templateLoaders);
	
	// Register template loaders that are supposed to kick in late.
	if (this.postTemplateLoaders != null) {
		templateLoaders.addAll(this.postTemplateLoaders);
	}
	
	TemplateLoader loader = getAggregateTemplateLoader(templateLoaders);
	if (loader != null) {
		config.setTemplateLoader(loader);
	}
	//config.setClassLoaderForTemplateLoading(classLoader, basePackagePath);
	//config.setCustomAttribute(name, value);
	//config.setDirectoryForTemplateLoading(dir);
	//config.setServletContextForTemplateLoading(servletContext, path);
	//config.setSharedVariable(name, value);
	//config.setSharedVariable(name, tm);
	config.setSharedVariable("fmXmlEscape", new XmlEscape());
	config.setSharedVariable("fmHtmlEscape", new HtmlEscape());
	//config.setSharedVaribles(map);
	
	// 设置模板引擎,减少重复初始化消耗
       this.setEngine(config);
       return config;
}
 
Example 10
Source File: DirectiveUtils.java    From metadata with Apache License 2.0 4 votes vote down vote up
public static void exposeRapidMacros(Configuration conf) {
    conf.setSharedVariable(BlockDirective.DIRECTIVE_NAME, new BlockDirective());
    conf.setSharedVariable(ExtendsDirective.DIRECTIVE_NAME, new ExtendsDirective());
    conf.setSharedVariable(OverrideDirective.DIRECTIVE_NAME, new OverrideDirective());
    conf.setSharedVariable(SuperDirective.DIRECTIVE_NAME, new SuperDirective());
}
 
Example 11
Source File: FreeMarkerExportHandler.java    From pcgen with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Produce an output file for a character using a FreeMarker template.
 *
 * @param aPC The character being output.
 * @param outputWriter The destination for the output.
 * @throws ExportException If the export fails.
 */
private void exportCharacterUsingFreemarker(PlayerCharacter aPC, Writer outputWriter) throws ExportException
{
	try
	{
		// Set Directory for templates
		Configuration cfg = new Configuration(VERSION_2_3_20);
		cfg.setDirectoryForTemplateLoading(getTemplateFile().getParentFile());

		// load template
		Template template = cfg.getTemplate(getTemplateFile().getName());

		// Configure our custom directives and functions.
		cfg.setSharedVariable("pcstring", new PCStringDirective(aPC, this));
		cfg.setSharedVariable("pcvar", new PCVarFunction(aPC));
		cfg.setSharedVariable("pcboolean", new PCBooleanFunction(aPC, this));
		cfg.setSharedVariable("pchasvar", new PCHasVarFunction(aPC, this));
		cfg.setSharedVariable("loop", new LoopDirective());
		cfg.setSharedVariable("equipsetloop", new EquipSetLoopDirective(aPC));

		GameMode gamemode = SettingsHandler.getGameAsProperty().get();
		// data-model
		Map<String, Object> pc = OutputDB.buildDataModel(aPC.getCharID());
		Map<String, Object> mode = OutputDB.buildModeDataModel(gamemode);
		Map<String, Object> input = new HashMap<>();
		input.put("pcgen", OutputDB.getGlobal());
		input.put("pc", ExportUtilities.getObjectWrapper().wrap(pc));
		input.put("gamemode", mode);
		input.put("gamemodename", gamemode.getName());

		// Process the template
		template.process(input, outputWriter);
	}
	catch (IOException | TemplateException exc)
	{
		String message = "Error exporting character using template " + getTemplateFile();
		Logging.errorPrint(message, exc);
		throw new ExportException(message + " : " + exc.getLocalizedMessage(), exc);
	}
	finally
	{
		if (outputWriter != null)
		{
			try
			{
				outputWriter.flush();
			}
			catch (Exception ignored)
			{
			}
		}
	}
}
 
Example 12
Source File: FreeMarkerExportHandler.java    From pcgen with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Produce an output file for a character using a FreeMarker template.
 *
 * @param aPC The character being output.
 * @param outputWriter The destination for the output.
 * @throws ExportException If the export fails.
 */
private void exportCharacterUsingFreemarker(PlayerCharacter aPC, Writer outputWriter) throws ExportException
{
	try
	{
		// Set Directory for templates
		Configuration cfg = new Configuration(VERSION_2_3_20);
		cfg.setDirectoryForTemplateLoading(getTemplateFile().getParentFile());

		// load template
		Template template = cfg.getTemplate(getTemplateFile().getName());

		// Configure our custom directives and functions.
		cfg.setSharedVariable("pcstring", new PCStringDirective(aPC, this));
		cfg.setSharedVariable("pcvar", new PCVarFunction(aPC));
		cfg.setSharedVariable("pcboolean", new PCBooleanFunction(aPC, this));
		cfg.setSharedVariable("pchasvar", new PCHasVarFunction(aPC, this));
		cfg.setSharedVariable("loop", new LoopDirective());
		cfg.setSharedVariable("equipsetloop", new EquipSetLoopDirective(aPC));

		GameMode gamemode = SettingsHandler.getGameAsProperty().get();
		// data-model
		Map<String, Object> pc = OutputDB.buildDataModel(aPC.getCharID());
		Map<String, Object> mode = OutputDB.buildModeDataModel(gamemode);
		Map<String, Object> input = new HashMap<>();
		input.put("pcgen", OutputDB.getGlobal());
		input.put("pc", ExportUtilities.getObjectWrapper().wrap(pc));
		input.put("gamemode", mode);
		input.put("gamemodename", gamemode.getName());

		// Process the template
		template.process(input, outputWriter);
	}
	catch (IOException | TemplateException exc)
	{
		String message = "Error exporting character using template " + getTemplateFile();
		Logging.errorPrint(message, exc);
		throw new ExportException(message + " : " + exc.getLocalizedMessage(), exc);
	}
	finally
	{
		if (outputWriter != null)
		{
			try
			{
				outputWriter.flush();
			}
			catch (Exception ignored)
			{
			}
		}
	}
}
 
Example 13
Source File: FreemarkerTemplateEngine.java    From pippo with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Application application) {
    super.init(application);

    Router router = getRouter();
    PippoSettings pippoSettings = getPippoSettings();

    configuration = new Configuration(Configuration.VERSION_2_3_21);
    configuration.setDefaultEncoding(PippoConstants.UTF8);
    configuration.setOutputEncoding(PippoConstants.UTF8);
    configuration.setLocalizedLookup(true);
    configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, getTemplatePathPrefix());

    // We also do not want Freemarker to chose a platform dependent
    // number formatting. Eg "1000" could be printed out by FTL as "1,000"
    // on some platforms.
    // See also:
    // http://freemarker.sourceforge.net/docs/app_faq.html#faq_number_grouping
    configuration.setNumberFormat("0.######"); // now it will print 1000000

    if (pippoSettings.isDev()) {
        configuration.setTemplateUpdateDelayMilliseconds(0); // disable cache
    } else {
        // never update the templates in production or while testing...
        configuration.setTemplateUpdateDelayMilliseconds(Integer.MAX_VALUE);

        // Hold 20 templates as strong references as recommended by:
        // http://freemarker.sourceforge.net/docs/pgui_config_templateloading.html
        configuration.setCacheStorage(new freemarker.cache.MruCacheStorage(20, Integer.MAX_VALUE));
    }

    // set global template variables
    configuration.setSharedVariable("contextPath", new SimpleScalar(router.getContextPath()));
    configuration.setSharedVariable("appPath", new SimpleScalar(router.getApplicationPath()));

    webjarResourcesMethod = new WebjarsAtMethod(router);
    publicResourcesMethod = new PublicAtMethod(router);

    // allow custom initialization
    init(application, configuration);
}
 
Example 14
Source File: Freemarker.java    From freeacs with MIT License 2 votes vote down vote up
/**
 * Sets the shared variables.
 *
 * @param config the new shared variables
 * @throws TemplateModelException the template model exception
 */
private static void setSharedVariables(Configuration config) throws TemplateModelException {
  config.setAllSharedVariables(
      new ResourceBundleModel(ResourceHandler.getProperties(), new BeansWrapper()));
  config.setSharedVariable("format", new ResourceMethod());
}
 
Example 15
Source File: RandomMethod.java    From halo with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Constructor.
 *
 * @param configuration injected by spring.
 */
public RandomMethod(Configuration configuration) {
    configuration.setSharedVariable("randomMethod", this);
}