freemarker.template.Configuration Java Examples

The following examples show how to use freemarker.template.Configuration. 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: CreateFileUtil.java    From Vert.X-generator with MIT License 7 votes vote down vote up
/**
 * 执行创建文件
 * 
 * @param content
 *          模板所需要的上下文
 * @param templeteName
 *          模板的名字 示例:Entity.ftl
 * @param projectPath
 *          生成的项目路径 示例:D://create
 * @param packageName
 *          包名 示例:com.szmirren
 * @param fileName
 *          文件名 示例:Entity.java
 * @param codeFormat
 *          输出的字符编码格式 示例:UTF-8
 * @throws Exception
 */
public static void createFile(GeneratorContent content, String templeteName, String projectPath, String packageName, String fileName,
		String codeFormat, boolean isOverride) throws Exception {
	String outputPath = projectPath + "/" + packageName.replace(".", "/") + "/";
	if (!isOverride) {
		if (Files.exists(Paths.get(outputPath + fileName))) {
			LOG.debug("设置了文件存在不覆盖,文件已经存在,忽略本文件的创建");
			return;
		}
	}
	Configuration config = new Configuration(Configuration.VERSION_2_3_23);
	String tempPath = Paths.get(Constant.TEMPLATE_DIR_NAME).toFile().getName();
	config.setDirectoryForTemplateLoading(new File(tempPath));
	config.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
	config.setDefaultEncoding("utf-8");
	Template template = config.getTemplate(templeteName);
	Map<String, Object> item = new HashMap<>();
	item.put("content", content);
	if (!Files.exists(Paths.get(outputPath))) {
		Files.createDirectories(Paths.get(outputPath));
	}
	try (Writer writer = new OutputStreamWriter(new FileOutputStream(outputPath + fileName), codeFormat)) {
		template.process(item, writer);
	}
}
 
Example #2
Source File: TemplateUtilsTest.java    From aws-mock with MIT License 6 votes vote down vote up
@Test(expected = AwsMockException.class)
public void Test_getProcessTemplateExceptionWithNoData() throws Exception {

    Configuration config = Mockito.mock(Configuration.class);
    Template template = Mockito.mock(Template.class);

    Whitebox.setInternalState(TemplateUtils.class, "conf", config);
    Mockito.doNothing().when(config)
            .setClassForTemplateLoading(Mockito.eq(TemplateUtils.class), Mockito.anyString());

    Mockito.when(config.getTemplate(Mockito.anyString())).thenReturn(template);
    Mockito.doThrow(new TemplateException("Forced TemplateException", null)).when(template)
            .process(Mockito.any(), Mockito.any(Writer.class));

    TemplateUtils.get(errFTemplateFile, null);

}
 
Example #3
Source File: FilesGenerator.java    From QuickProject with Apache License 2.0 6 votes vote down vote up
public void generate() throws GlobalConfigException {
    Configuration cfg = new Configuration();
    File tmplDir = globalConfig.getTmplFile();
    try {
        cfg.setDirectoryForTemplateLoading(tmplDir);
    } catch (IOException e) {
        throw new GlobalConfigException("tmplPath", e);
    }
    cfg.setObjectWrapper(new DefaultObjectWrapper());
    for (Module module : modules) {
        logger.debug("module:" + module.getName());
        for (Bean bean : module.getBeans()) {
            logger.debug("bean:" + bean.getName());
            Map dataMap = new HashMap();
            dataMap.put("bean", bean);
            dataMap.put("module", module);
            dataMap.put("generate", generate);
            dataMap.put("config", config);
            dataMap.put("now", DateFormatUtils.ISO_DATE_FORMAT.format(new Date()));

            generate(cfg, dataMap);
        }
    }
}
 
Example #4
Source File: SecureSoapMessages.java    From spring-ws-security-soap-example with MIT License 6 votes vote down vote up
/**
 * Generates the text content for the plain password SOAP message.
 * <p>
 * This will be created from a freemarker template.
 *
 * @param path
 *            path to the freemarker template
 * @param user
 *            username to use
 * @param password
 *            password to use
 * @return the text content for the plain passworde message
 * @throws Exception
 *             if any error occurs during the message creation
 */
private static final String getPlainPasswordMessageContent(
        final String path, final String user, final String password)
        throws Exception {
    final Template template; // Freemarker template
    final Map<String, Object> data; // Data for the template
    final ByteArrayOutputStream out; // Steam with the message

    // Prepares the data for the template
    data = new HashMap<String, Object>();
    data.put("user", user);
    data.put("password", password);

    // Processes the template to the output
    out = new ByteArrayOutputStream();
    template = new Configuration(Configuration.VERSION_2_3_0)
            .getTemplate(path);
    template.process(data, new OutputStreamWriter(out));

    return new String(out.toByteArray());
}
 
Example #5
Source File: Service.java    From act with GNU General Public License v3.0 6 votes vote down vote up
public Controller(ServiceConfig config, Configuration cfg) {
  this.serviceConfig = config;
  this.cfg = cfg;

  // Do some path munging once to ensure we can build clean URLs.
  this.wikiUrlBase = config.getWikiUrlPrefix();
  this.imagesUrlBase = config.getImageUrlPrefix();

  // Add trailing slashes so we can assume they exist later.
  if (!this.wikiUrlBase.endsWith("/")) {
    this.wikiUrlBase = this.wikiUrlBase + "/";
  }

  if (!this.imagesUrlBase.endsWith("/")) {
    this.imagesUrlBase = this.imagesUrlBase + "/";
  }
}
 
Example #6
Source File: TemplateHelper.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected static Map<String, Object> prepareParams(Map<String, ?> parameterValues) {
    Map<String, Object> parameterValuesWithStats = new HashMap<>(parameterValues);
    BeansWrapper beansWrapper = new BeansWrapperBuilder(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS).build();
    parameterValuesWithStats.put("statics", beansWrapper.getStaticModels());

    @SuppressWarnings("unchecked")
    Map<String, Object> params = LazyMap.lazyMap(parameterValuesWithStats, propertyName -> {
        for (String appProperty : AppContext.getPropertyNames()) {
            if (appProperty.replace(".", "_").equals(propertyName)) {
                return AppContext.getProperty(propertyName);
            }
        }
        return null;
    });

    return params;
}
 
Example #7
Source File: TemplateHelpers.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List<String> getAvailableAutoInclude(Configuration conf, List<String> autoIncludes) {
    List<String> results = new ArrayList();
    for (String autoInclude : autoIncludes) {
        autoInclude =autoInclude.replace(StringUtil.BACK_SLASH, StringUtil.SLASH);
        try {
            Template t = new Template("__auto_include_test__", new StringReader("1"), conf);
            conf.setAutoIncludes(Arrays.asList(new String[] { autoInclude }));
            t.process(new HashMap(), new StringWriter());
            results.add(autoInclude);
        } catch (Exception e) {

        }
    }
    return results;
}
 
Example #8
Source File: AttributeExpander.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a (String)TemplateInvoker with compiled Freemarker template for the attribute
 * content inline template.
 * <p>
 * TODO: decide cache... can make CmsAttributeTemplate-specific cache (by id or so, faster) but
 * may get memory duplication with #interpretStd calls (cached by body, because no id/name avail)
 * -> could do both at once maybe? share the Template instance between 2 cache...
 * TODO: subject to refactor/move
 * TODO?: FUTURE: this does NOT wrap the TemplateInvoker in a TemplateModel for time being...
 * we will rely on the default ObjectWrapper(s) to wrap the StringTemplateInvoker
 * in a freemarker StringModel (BeanModel) which renders throughs the ?string built-in
 * or string evaluation.
 */
public static TemplateInvoker getStringTemplateInvokerForContent(String tmplStr, Map<String, Object> ctxVars, CmsPageContext pageContext) throws TemplateException, IOException {
    Configuration config = CmsRenderTemplate.TemplateRenderer.getDefaultCmsConfig();

    // TODO: REVIEW: cache selection is a problem...
    // instead of by template body we could cache by some derivative unique name
    // derived from the CmsAttributeTemplate ID (maybe?)
    // would likely be much faster

    UtilCache<String, Template> cache = TemplateSource.getTemplateInlineSelfCacheForConfig(config, null);
    if (cache == null) {
        Debug.logWarning("Cms: could not determine"
                + " an inline template cache to use; not using cache", module);
    }
    TemplateSource templateSource = TemplateSource.getForInline(null, tmplStr, cache, config, true);

    // NOTE: must get StringInvoker so BeansWrapper's StringModel can invoke toString()
    // NOTE: context parameters could be passed to the template using InvokeOptions.ctxVars...
    // but not yet needed
    TemplateInvoker invoker = TemplateInvoker.getInvoker(templateSource, new InvokeOptions(null, null, null, ctxVars, false), null);
    return invoker;
}
 
Example #9
Source File: FreemarkerTest.java    From mogu_blog_v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateHtmlByString() throws IOException, TemplateException {
    //创建配置类
    Configuration configuration = new Configuration(Configuration.getVersion());
    //获取模板内容
    //模板内容,这里测试时使用简单的字符串作为模板
    String templateString = "" +
            "<html>\n" +
            "    <head></head>\n" +
            "    <body>\n" +
            "    名称:${name}\n" +
            "    </body>\n" +
            "</html>";

    //加载模板
    //模板加载器
    StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
    stringTemplateLoader.putTemplate("template", templateString);
    configuration.setTemplateLoader(stringTemplateLoader);
    Template template = configuration.getTemplate("template", "utf-8");

    //数据模型
    Map map = getMap();
    //静态化
    String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
    //静态化内容
    System.out.println(content);
    InputStream inputStream = IOUtils.toInputStream(content);
    //输出文件
    FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.html"));
    IOUtils.copy(inputStream, fileOutputStream);
}
 
Example #10
Source File: HipChatNotificationMessageGenerator.java    From rundeck-hipchat-plugin with Apache License 2.0 6 votes vote down vote up
private String determineTemplateName(final String messageTemplateLocation,
                                     final String defaultMessageTemplateName,
                                     final Configuration freeMarkerCfg) {
    String templateName;

    if (messageTemplateLocation != null && messageTemplateLocation.length() > 0) {
        final File messageTemplateFile = new File(messageTemplateLocation);
        try {
            freeMarkerCfg.setDirectoryForTemplateLoading(messageTemplateFile.getParentFile());
        } catch (IOException ioEx) {
            throw new HipChatNotificationPluginException("Error setting FreeMarker template loading directory: [" + ioEx.getMessage() + "].", ioEx);
        }
        templateName = messageTemplateFile.getName();

    } else {
        freeMarkerCfg.setClassForTemplateLoading(HipChatNotificationPlugin.class, "/templates");
        templateName = defaultMessageTemplateName;
    }

    return templateName;
}
 
Example #11
Source File: OutMsgXmlBuilder.java    From jfinal-weixin with Apache License 2.0 5 votes vote down vote up
private static Configuration initFreeMarkerConfiguration() {
	Configuration config = new Configuration();
	StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
	initStringTemplateLoader(stringTemplateLoader);
	config.setTemplateLoader(stringTemplateLoader);
	
	// 模板缓存更新时间,对于OutMsg xml 在类文件中的模板来说已有热加载保障了更新
       config.setTemplateUpdateDelay(999999);
       // - Set an error handler that prints errors so they are readable with
       //   a HTML browser.
       // config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
       config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
       
       // - Use beans wrapper (recommmended for most applications)
       config.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
       // - Set the default charset of the template files
       config.setDefaultEncoding(encoding);		// config.setDefaultEncoding("ISO-8859-1");
       // - Set the charset of the output. This is actually just a hint, that
       //   templates may require for URL encoding and for generating META element
       //   that uses http-equiv="Content-type".
       config.setOutputEncoding(encoding);			// config.setOutputEncoding("UTF-8");
       // - Set the default locale
       config.setLocale(Locale.getDefault() /* Locale.CHINA */ );		// config.setLocale(Locale.US);
       config.setLocalizedLookup(false);
       
       // 去掉int型输出时的逗号, 例如: 123,456
       // config.setNumberFormat("#");		// config.setNumberFormat("0"); 也可以
       config.setNumberFormat("#0.#####");
       config.setDateFormat("yyyy-MM-dd");
       config.setTimeFormat("HH:mm:ss");
       config.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
	return config;
}
 
Example #12
Source File: ServiceGenerator.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
private static void genServiceImpl(String className,
                                   String classComment,
                                   String resourcePath,
                                   GeneratorConfig generatorConfig) {
    Map<String, Object> paramMap = new HashMap<>();

    paramMap.put("className", className);
    paramMap.put("classComment", classComment);
    paramMap.put("sysTime", new Date());
    paramMap.put("packageName", generatorConfig.getPackageName());

    Version version = new Version("2.3.27");
    Configuration configuration = new Configuration(version);
    try {
        URL url = ServiceGenerator.class.getClassLoader().getResource(resourcePath);
        configuration.setDirectoryForTemplateLoading(new File(url.getPath()));
        configuration.setObjectWrapper(new DefaultObjectWrapper(version));
        String filePath = generatorConfig.getSrcBasePath() + "service//impl//";
        String savePath = filePath + className + "ServiceImpl.java";
        File dirPath = new File(filePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try (FileWriter fileWriter = new FileWriter(new File(savePath))) {
            Template template = configuration.getTemplate("service_impl.ftl");
            template.process(paramMap, fileWriter);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #13
Source File: FreemarkerTemplatingService.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
private Configuration createDefaultConfiguration() {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);

    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
    cfg.setLogTemplateExceptions(false);

    return cfg;
}
 
Example #14
Source File: TemplateConfiguration.java    From megamek with GNU General Public License v2.0 5 votes vote down vote up
private static Configuration createConfiguration() {
    final Configuration cfg = new Configuration(Configuration.getVersion());
    cfg.setClassForTemplateLoading(TemplateConfiguration.class, "/megamek/common/templates");
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(false);
    cfg.setWrapUncheckedExceptions(true);
    return cfg;
}
 
Example #15
Source File: FreeMarkerTemplateHander.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
public FreeMarkerTemplateHander(Vertx vertx, String templateDirectory, String contentType) {
	super(DEFAULT_TEMPLATE_EXTENSION, DEFAULT_MAX_CACHE_SIZE);
	this.contentType = contentType;
	config = new Configuration(Configuration.VERSION_2_3_28);
	try {
		config.setDirectoryForTemplateLoading(new File(templateDirectory));
	} catch (IOException e) {
		throw new FileSystemException("not found template directory:" + templateDirectory);
	}
	config.setObjectWrapper(new VertxWebObjectWrapper(config.getIncompatibleImprovements()));
	config.setCacheStorage(new NullCacheStorage());
}
 
Example #16
Source File: FeedTaskProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected String processFreemarker(Map<String, Template> templateCache, String fmTemplate, Configuration cfg, Map<String, Object> model) throws IOException, TemplateException, Exception
{
    // Save on lots of modification date checking by caching templates locally
    Template myTemplate = templateCache.get(fmTemplate);
    if (myTemplate == null)
    {
        myTemplate = cfg.getTemplate(fmTemplate);
        templateCache.put(fmTemplate, myTemplate);
    }
    
    StringWriter textWriter = new StringWriter();
    myTemplate.process(model, textWriter);
    
    return textWriter.toString();
}
 
Example #17
Source File: MailService.java    From abixen-platform with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Async
public void sendMail(String to, Map<String, String> parameters, String template, String subject) {
    log.debug("sendMail() - to: " + to);
    MimeMessage message = mailSender.createMimeMessage();
    try {
        String stringDir = MailService.class.getResource("/templates/freemarker").getPath();
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setDefaultEncoding("UTF-8");

        File dir = new File(stringDir);
        cfg.setDirectoryForTemplateLoading(dir);
        cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_22));

        StringBuffer content = new StringBuffer();
        Template temp = cfg.getTemplate(template + ".ftl");
        content.append(FreeMarkerTemplateUtils.processTemplateIntoString(temp, parameters));

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content.toString(), "text/html;charset=\"UTF-8\"");

        MimeMultipart multipart = new MimeMultipart("related");
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);
        message.setFrom(new InternetAddress(platformMailConfigurationProperties.getUser().getUsername(), platformMailConfigurationProperties.getUser().getName()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        mailSender.send(message);

        log.info("Message has been sent to: " + to);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #18
Source File: TemplateConfig.java    From extentreports-java with Apache License 2.0 5 votes vote down vote up
public Configuration getFreemarkerConfig(Class<?> clazz, String basePackagePath, String encoding) {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
    cfg.setClassForTemplateLoading(clazz, basePackagePath);
    cfg.setDefaultEncoding(encoding);
    cfg.setAPIBuiltinEnabled(true);
    return cfg;
}
 
Example #19
Source File: FtlCacheRegistry.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public void registerCache(String cacheType, Configuration config, UtilCache<String, Template> cache) {
    synchronized(syncObj) {
        Map<CacheKey, UtilCache<String, Template>> newCaches = new HashMap<>(this.caches);
        newCaches.put(new CacheKey(cacheType, config), cache);
        this.caches = Collections.unmodifiableMap(newCaches);
    }
}
 
Example #20
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 #21
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 #22
Source File: FacetManager.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
/**
 * indicate the table name to query + facet on
 * @param onTable
 */
public FacetManager(String onTable){
  this.table = onTable;
  if(FacetManager.cfg == null){
    //do this ONLY ONCE
    FacetManager.cfg = new Configuration(new Version(2, 3, 26));
    // Where do we load the templates from:
    cfg.setClassForTemplateLoading(FacetManager.class, "/templates/facets");
    cfg.setDefaultEncoding("UTF-8");
    cfg.setLocale(Locale.US);
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
  }
}
 
Example #23
Source File: UserDataBuilderTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException, TemplateException {
    FreeMarkerConfigurationFactoryBean factoryBean = new FreeMarkerConfigurationFactoryBean();
    factoryBean.setPreferFileSystemAccess(false);
    factoryBean.setTemplateLoaderPath("classpath:/");
    factoryBean.afterPropertiesSet();
    Configuration configuration = factoryBean.getObject();
    underTest.setFreemarkerConfiguration(configuration);

    UserDataBuilderParams params = new UserDataBuilderParams();
    params.setCustomData("date >> /tmp/time.txt");

    ReflectionTestUtils.setField(underTest, "userDataBuilderParams", params);
}
 
Example #24
Source File: MailComposer.java    From kaif with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
MailComposer(MessageSource messageSource,
    Configuration configuration,
    MailProperties mailProperties) {
  this.messageSource = messageSource;
  this.configuration = configuration;
  this.mailProperties = mailProperties;
}
 
Example #25
Source File: RuleCreator.java    From support-rulesengine with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() throws IOException {
  try {
    cfg = new Configuration(Configuration.getVersion());
    cfg.setDirectoryForTemplateLoading(new File(templateLocation));
    cfg.setDefaultEncoding(templateEncoding);
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
  } catch (IOException e) {
    logger.error("Problem getting rule template location." + e.getMessage());
    throw e;
  }
}
 
Example #26
Source File: HelpTemplateWrapperFactory.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public HelpTemplateWrapperFactory(String templatesPackagePath) throws IOException {
    configuration = new Configuration(Configuration.VERSION_2_3_24);

    configuration.setTemplateLoader(new ClassTemplateLoader(HelpBuilder.class, templatesPackagePath));
    configuration.setDefaultEncoding("UTF-8");
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    configuration.setAPIBuiltinEnabled(true);
    configuration.setRecognizeStandardFileExtensions(true);
}
 
Example #27
Source File: FreemarkerUtil.java    From wetech-cms with MIT License 5 votes vote down vote up
public static FreemarkerUtil getInstance(String pname) {
	if(util==null) {
		cfg = new Configuration();
		cfg.setClassForTemplateLoading(FreemarkerUtil.class, pname);
		cfg.setDefaultEncoding("utf-8");
		util = new FreemarkerUtil();
	}
	return util;
}
 
Example #28
Source File: DefaultEmailService.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Override
public void sendEmail(String to, String subject, String templateName, Map<String, Object> templateData) {
    // create a copy of mail message:
    SimpleMailMessage message = new SimpleMailMessage(emailServiceMailMessage);
    message.setSubject(subject);
    message.setTo(to);
    // set body text:
    Configuration configuration = freemarkerMailConfiguration.getObject();
    String text = parseTemplate(configuration, templateData, templateName);
    message.setText(text);
    // send email:
    mailSender.send(message);
}
 
Example #29
Source File: TemplateConfiguration.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
private void init() {
	try {
		Configuration configuration = new Configuration(Configuration.getVersion());
		configuration.setDefaultEncoding("UTF-8");
		configuration.setObjectWrapper(new DefaultObjectWrapper(configuration.getIncompatibleImprovements()));

		this.setConfiguration(configuration);
	} catch (Exception e) {
		_log.error(e);
	}
}
 
Example #30
Source File: FreeMarkerConfigurerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void freeMarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath() throws Exception {
	FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
	fcfb.setTemplateLoaderPath("file:/mydir");
	Properties settings = new Properties();
	settings.setProperty("localized_lookup", "false");
	fcfb.setFreemarkerSettings(settings);
	fcfb.setResourceLoader(new ResourceLoader() {
		@Override
		public Resource getResource(String location) {
			if (!("file:/mydir".equals(location) || "file:/mydir/test".equals(location))) {
				throw new IllegalArgumentException(location);
			}
			return new ByteArrayResource("test".getBytes(), "test");
		}
		@Override
		public ClassLoader getClassLoader() {
			return getClass().getClassLoader();
		}
	});
	fcfb.afterPropertiesSet();
	assertThat(fcfb.getObject(), instanceOf(Configuration.class));
	Configuration fc = fcfb.getObject();
	Template ft = fc.getTemplate("test");
	assertEquals("test", FreeMarkerTemplateUtils.processTemplateIntoString(ft, new HashMap()));
}