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

The following examples show how to use freemarker.template.Configuration#setDefaultEncoding() . 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: CmsFreemarkerHelperNew.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/**
 * 解析ftl
 * @param tplContent 模板内容
 * @param encoding 编码
 * @param paras 参数
 * @return String 模板解析后内容
 */
public String parseTemplateContent(String tplContent,
		Map<String, Object> paras, String encoding) {
	Configuration cfg = new Configuration();    
    StringWriter writer = new StringWriter(); 
       cfg.setTemplateLoader(new StringTemplateLoader(tplContent));  
       encoding = encoding==null?"UTF-8":encoding;
       cfg.setDefaultEncoding(encoding);    
  
       Template template;
	try {
		template = cfg.getTemplate("");
        template.process(paras, writer);    
		} catch (Exception e) {
			e.printStackTrace();
		}
       return writer.toString();       
}
 
Example 2
Source File: FreeMarkerFormatter.java    From ofexport2 with Apache License 2.0 6 votes vote down vote up
public FreeMarkerFormatter(String templateName) throws IOException {
    // If the resource doesn't exist abort so we can look elsewhere
    try (
        InputStream in = this.getClass().getResourceAsStream(TEMPLATES + "/" + templateName)) {
        if (in == null) {
            throw new IOException("Resource not found:" + templateName);
        }
    }

    this.templateName = templateName;

    Configuration cfg = new Configuration(Configuration.VERSION_2_3_21);
    TemplateLoader templateLoader = new ClassTemplateLoader(this.getClass(), TEMPLATES);
    cfg.setTemplateLoader(templateLoader);
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

    // This is fatal - bomb out of application
    try {
        template = cfg.getTemplate(templateName);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 3
Source File: GifService.java    From sorryJava with Apache License 2.0 6 votes vote down vote up
private String renderAss(Subtitles subtitles) throws Exception {
    Path path = Paths.get(tempPath).resolve(UUID.randomUUID().toString().replace("-", "") + ".ass");
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);
    cfg.setDefaultEncoding("UTF-8");
    cfg.setDirectoryForTemplateLoading(Paths.get(tempPath).resolve(subtitles.getTemplateName()).toFile());
    Map<String, Object> root = new HashMap<>();
    Map<String, String> mx = new HashMap<>();
    List<String> list = Splitter.on(",").splitToList(subtitles.getSentence());
    for (int i = 0; i < list.size(); i++) {
        mx.put("sentences" + i, list.get(i));
    }
    root.put("mx", mx);
    Template temp = cfg.getTemplate("template.ftl");
    try (FileWriter writer = new FileWriter(path.toFile())) {
        temp.process(root, writer);
    } catch (Exception e) {
        logger.error("生成ass文件报错", e);
    }
    return path.toString();
}
 
Example 4
Source File: CCDAExporter.java    From synthea with Apache License 2.0 6 votes vote down vote up
private static Configuration templateConfiguration() {
  Configuration configuration = new Configuration(Configuration.VERSION_2_3_26);
  configuration.setDefaultEncoding("UTF-8");
  configuration.setLogTemplateExceptions(false);
  try {
    configuration.setSetting("object_wrapper",
        "DefaultObjectWrapper(2.3.26, forceLegacyNonListCollections=false, "
            + "iterableSupport=true, exposeFields=true)");
  } catch (TemplateException e) {
    e.printStackTrace();
  }
  configuration.setAPIBuiltinEnabled(true);
  configuration.setClassLoaderForTemplateLoading(ClassLoader.getSystemClassLoader(),
      "templates/ccda");
  return configuration;
}
 
Example 5
Source File: FreemarkerRenderer.java    From act with GNU General Public License v3.0 6 votes vote down vote up
private void init(String dbHost, Integer dbPort, String dbName, String dnaCollection, String pathwayCollection) throws IOException {
  cfg = new Configuration(Configuration.VERSION_2_3_23);

  cfg.setClassLoaderForTemplateLoading(
      this.getClass().getClassLoader(), "/act/installer/reachablesexplorer/templates");
  cfg.setDefaultEncoding("UTF-8");

  cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
  cfg.setLogTemplateExceptions(true);

  reachableTemplate = cfg.getTemplate(reachableTemplateName);
  pathwayTemplate = cfg.getTemplate(pathwayTemplateName);

  // TODO: move this elsewhere.
  MongoClient client = new MongoClient(new ServerAddress(dbHost, dbPort));
  DB db = client.getDB(dbName);

  dnaDesignCollection = JacksonDBCollection.wrap(db.getCollection(dnaCollection), DNADesign.class, String.class);
  Cascade.setCollectionName(pathwayCollection);
}
 
Example 6
Source File: FreemarkerUtils.java    From my_curd with Apache License 2.0 5 votes vote down vote up
/**
 * 通过模板文本字符串和数据获得渲染后的文本
 *
 * @param templateContent 模板文本内容
 * @param paramMap        数据
 * @return
 */
public static String renderAsText(String templateContent, Map<String, Object> paramMap) {
    StringWriter writer = new StringWriter();
    try {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
        cfg.setTemplateLoader(new StringTemplateLoader(templateContent));
        cfg.setDefaultEncoding(Constant.DEFAULT_ENCODEING);
        Template template = cfg.getTemplate("");
        template.process(paramMap, writer);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return writer.toString();
}
 
Example 7
Source File: GeneratorHelper.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
private Template getTemplate(String templateName) throws Exception {
    Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
    String templatePath = GeneratorHelper.class.getResource("/generator/templates/").getPath();
    File file = new File(templatePath);
    if (!file.exists()) {
        templatePath = System.getProperties().getProperty(FebsConstant.JAVA_TEMP_DIR);
        file = new File(templatePath + File.separator + templateName);
        FileUtils.copyInputStreamToFile(Objects.requireNonNull(GeneratorHelper.class.getClassLoader().getResourceAsStream("classpath:generator/templates/" + templateName)), file);
    }
    configuration.setDirectoryForTemplateLoading(new File(templatePath));
    configuration.setDefaultEncoding(FebsConstant.UTF8);
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
    return configuration.getTemplate(templateName);

}
 
Example 8
Source File: FreemarkerConfig.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
	 * 
	 * @param httpConfig
	 * @param root
	 * @return
	 * @throws IOException
	 */
	private Configuration createConfiguration(HttpConfig httpConfig, String root) throws IOException {
		if (httpConfig.getPageRoot() == null) {
			return null;
		}

		if (configurationCreater != null) {
			return configurationCreater.createConfiguration(httpConfig, root);
		}

		Configuration cfg = new Configuration(Configuration.getVersion());

		if (httpConfig.isPageInClasspath()) {
			cfg.setClassForTemplateLoading(this.getClass(), "/" + root/**.substring("classpath:".length())*/
			);
			//cfg.setClassForTemplateLoading(FreemarkerUtil.class, "/template");
		} else {
			cfg.setDirectoryForTemplateLoading(new File(root));
		}
		cfg.setDefaultEncoding(httpConfig.getCharset());
		//		cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		cfg.setLogTemplateExceptions(false);
		cfg.setWrapUncheckedExceptions(true);
		cfg.setTemplateExceptionHandler(ShortMessageTemplateExceptionHandler.me);
		cfg.setLocale(Locale.SIMPLIFIED_CHINESE);
		cfg.setNumberFormat("#");
//		cfg.setClassicCompatible(true);
		return cfg;
	}
 
Example 9
Source File: FreemarkerProcessor.java    From mxjc with MIT License 5 votes vote down vote up
/**
 * Get the freemarker configuration.
 *
 * @return the freemarker configuration.
 */
private Configuration getConfiguration() {
    Configuration configuration = new Configuration();
    configuration.setTemplateLoader(getTemplateLoader());
    configuration.setTemplateExceptionHandler(getTemplateExceptionHandler());
    configuration.setLocalizedLookup(false);
    configuration.setDefaultEncoding("UTF-8");
    return configuration;
}
 
Example 10
Source File: CqUtils.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
public static Configuration getTemplateConfig(Path basePath, String defaultUriBase, String templatesUriBase,
        String encoding) {
    final Configuration templateCfg = new Configuration(Configuration.VERSION_2_3_28);
    templateCfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    templateCfg.setTemplateLoader(createTemplateLoader(basePath, defaultUriBase, templatesUriBase));
    templateCfg.setDefaultEncoding(encoding);
    templateCfg.setInterpolationSyntax(Configuration.SQUARE_BRACKET_INTERPOLATION_SYNTAX);
    templateCfg.setTagSyntax(Configuration.SQUARE_BRACKET_TAG_SYNTAX);
    return templateCfg;
}
 
Example 11
Source File: FreeMarkerUtils.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
public static Configuration buildConfiguration(String directory) {
	// 1.创建配置实例Cofiguration
	Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
	cfg.setDefaultEncoding("utf-8");
	ClassPathResource cps = new ClassPathResource(directory);
	try {
		cfg.setDirectoryForTemplateLoading(cps.getFile());
		return cfg;
	} catch (IOException e) {
		throw new ServiceException(e);
	}
}
 
Example 12
Source File: WebMgr.java    From Summer with Apache License 2.0 5 votes vote down vote up
private void reloadTemplate() {
	freeMarkerConfig = new Configuration(Configuration.VERSION_2_3_23);
	freeMarkerConfig.setDefaultEncoding("UTF-8");
	try {
		freeMarkerConfig.setDirectoryForTemplateLoading(new File(templatePath));
	} catch (IOException e) {
		log.error(e.getMessage(), e);
	}
}
 
Example 13
Source File: AbstractHalProcessor.java    From core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public AbstractHalProcessor() {

        Version version = new Version(2, 3, 22);
        config = new Configuration(version);
        config.setDefaultEncoding("UTF-8");
        config.setClassForTemplateLoading(getClass(), "templates");
        config.setObjectWrapper(new DefaultObjectWrapperBuilder(version).build());
    }
 
Example 14
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 15
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 16
Source File: ReportNotificationManager.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
public ReportNotificationManager() {
	  	cfg = new Configuration(MTGConstants.FREEMARKER_VERSION);
        try {
			cfg.setClassForTemplateLoading(ReportNotificationManager.class, MTGConstants.MTG_REPORTS_DIR);
			cfg.setDefaultEncoding(MTGConstants.DEFAULT_ENCODING.displayName());
			cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
			cfg.setObjectWrapper(new DefaultObjectWrapperBuilder(MTGConstants.FREEMARKER_VERSION).build());
		} catch (Exception e) {
			errorLoading=true;
			logger.error("error init Freemarker ",e);
		}
		
}
 
Example 17
Source File: TemplateWrapperFactory.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public TemplateWrapperFactory(String templatesPackagePath) {
    configuration = new Configuration(Configuration.VERSION_2_3_24);

    configuration.setTemplateLoader(new ClassTemplateLoader(HtmlReport.class, templatesPackagePath));
    configuration.setDefaultEncoding("UTF-8");
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    configuration.setAPIBuiltinEnabled(true);
    configuration.setObjectWrapper(new BeansWrapperBuilder(Configuration.VERSION_2_3_24).build());
    configuration.setRecognizeStandardFileExtensions(true);
}
 
Example 18
Source File: WelcomePage.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * 创建 Configuration 实例.
 *
 * @return
 * @throws IOException
 */
private Configuration config(String ftlDir) throws IOException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
    cfg.setDirectoryForTemplateLoading(new File(ftlDir));
    cfg.setDefaultEncoding(StandardCharsets.UTF_8.name());
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    return cfg;
}
 
Example 19
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 20
Source File: MailTemplateProvider.java    From kylin with Apache License 2.0 4 votes vote down vote up
private MailTemplateProvider() {
    configuration = new Configuration(Configuration.getVersion());
    configuration.setClassForTemplateLoading(MailTemplateProvider.class, "/mail_templates");
    configuration.setDefaultEncoding("UTF-8");
}