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

The following examples show how to use freemarker.template.Configuration#setLocale() . 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: Freemarker.java    From freeacs with MIT License 6 votes vote down vote up
/**
 * Inits the freemarker.
 *
 * @return the configuration
 */
public static Configuration initFreemarker() {
  try {
    Configuration config = new Configuration();
    config.setTemplateLoader(new ClassTemplateLoader(Freemarker.class, "/templates"));
    config.setTemplateUpdateDelay(0);
    config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
    config.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
    config.setDefaultEncoding("ISO-8859-1");
    config.setOutputEncoding("ISO-8859-1");
    config.setNumberFormat("0");
    config.setSetting("url_escaping_charset", "ISO-8859-1");
    config.setLocale(Locale.ENGLISH);
    setAutoImport(config);
    setSharedVariables(config);
    return config;
  } catch (Throwable e) {
    throw new RuntimeException("Could not initialise Freemarker configuration", e);
  }
}
 
Example 2
Source File: TemplateProcessor.java    From contribution with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Generates output file with release notes using FreeMarker.
 *
 * @param variables the map which represents template variables.
 * @param outputFile output file.
 * @param templateFileName the optional file name of the template.
 * @param defaultResource the resource file name to use if no file name was given.
 * @throws IOException if I/O error occurs.
 * @throws TemplateException if an error occurs while generating freemarker template.
 */
public static void generateWithFreemarker(Map<String, Object> variables, String outputFile,
        String templateFileName, String defaultResource) throws IOException, TemplateException {

    final Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
    configuration.setDefaultEncoding("UTF-8");
    configuration.setLocale(Locale.US);
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    configuration.setNumberFormat("0.######");

    final StringTemplateLoader loader = new StringTemplateLoader();
    loader.putTemplate(TEMPLATE_NAME, loadTemplate(templateFileName, defaultResource));
    configuration.setTemplateLoader(loader);

    final Template template = configuration.getTemplate(TEMPLATE_NAME);
    try (Writer fileWriter = new OutputStreamWriter(
            new FileOutputStream(outputFile), StandardCharsets.UTF_8)) {
        template.process(variables, fileWriter);
    }
}
 
Example 3
Source File: GatekeeperConfig.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
@Bean
public Configuration freemarkerConfig() {
    Configuration configuration = new Configuration(Configuration.VERSION_2_3_29);
    configuration.setClassForTemplateLoading(EmailService.class, "/emails");
    configuration.setDefaultEncoding("UTF-8");
    configuration.setLocale(Locale.US);
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

    return configuration;
}
 
Example 4
Source File: AppConfig.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
@Bean
public freemarker.template.Configuration freemarkerConfig() {
    Configuration configuration = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_29);
    configuration.setClassForTemplateLoading(EmailService.class, "/emails");
    configuration.setDefaultEncoding("UTF-8");
    configuration.setLocale(Locale.US);
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

    return configuration;
}
 
Example 5
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 6
Source File: FreeMarkerService.java    From freemarker-online-tester with Apache License 2.0 5 votes vote down vote up
private FreeMarkerService(Builder bulder) {
     maxOutputLength = bulder.getMaxOutputLength();
     maxThreads = bulder.getMaxThreads();
     maxQueueLength = bulder.getMaxQueueLength();
     maxTemplateExecutionTime = bulder.getMaxTemplateExecutionTime();

     int actualMaxQueueLength = maxQueueLength != null
             ? maxQueueLength
             : Math.max(
                     MIN_DEFAULT_MAX_QUEUE_LENGTH,
                     (int) (MAX_DEFAULT_MAX_QUEUE_LENGTH_MILLISECONDS / maxTemplateExecutionTime));
     ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
             maxThreads, maxThreads,
             THREAD_KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS,
             new BlockingArrayQueue<Runnable>(actualMaxQueueLength));
     threadPoolExecutor.allowCoreThreadTimeOut(true);
     templateExecutor = threadPoolExecutor;

     // Avoid ERROR log for using the actual current version. This application is special in that regard.
     Version latestVersion = new Version(Configuration.getVersion().toString());

     freeMarkerConfig = new Configuration(latestVersion);
     freeMarkerConfig.setNewBuiltinClassResolver(TemplateClassResolver.ALLOWS_NOTHING_RESOLVER);
     freeMarkerConfig.setObjectWrapper(new SimpleObjectWrapperWithXmlSupport(latestVersion));
     freeMarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
     freeMarkerConfig.setLogTemplateExceptions(false);
     freeMarkerConfig.setAttemptExceptionReporter(new AttemptExceptionReporter() {
@Override
public void report(TemplateException te, Environment env) {
	// Suppress it
}
     });
     freeMarkerConfig.setLocale(AllowedSettingValues.DEFAULT_LOCALE);
     freeMarkerConfig.setTimeZone(AllowedSettingValues.DEFAULT_TIME_ZONE);
     freeMarkerConfig.setOutputFormat(AllowedSettingValues.DEFAULT_OUTPUT_FORMAT);
     freeMarkerConfig.setOutputEncoding("UTF-8");
 }
 
Example 7
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 8
Source File: TrainModule.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
/**
 * TrainModule
 */
public TrainModule() {
    String maxChartPointsProp = System.getProperty(DL4JSystemProperties.CHART_MAX_POINTS_PROPERTY);
    int value = DEFAULT_MAX_CHART_POINTS;
    if (maxChartPointsProp != null) {
        try {
            value = Integer.parseInt(maxChartPointsProp);
        } catch (NumberFormatException e) {
            log.warn("Invalid system property: {} = {}", DL4JSystemProperties.CHART_MAX_POINTS_PROPERTY, maxChartPointsProp);
        }
    }
    if (value >= 10) {
        maxChartPoints = value;
    } else {
        maxChartPoints = DEFAULT_MAX_CHART_POINTS;
    }

    configuration = new Configuration(new Version(2, 3, 23));
    configuration.setDefaultEncoding("UTF-8");
    configuration.setLocale(Locale.US);
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

    configuration.setClassForTemplateLoading(TrainModule.class, "");
    try {
        File dir = Resources.asFile("templates/TrainingOverview.html.ftl").getParentFile();
        configuration.setDirectoryForTemplateLoading(dir);
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}
 
Example 9
Source File: StaticPageUtil.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
public static String renderHTMLContent(Component... components) throws Exception {

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        Configuration cfg = new Configuration(new Version(2, 3, 23));

        // Where do we load the templates from:
        cfg.setClassForTemplateLoading(StaticPageUtil.class, "");

        // Some other recommended settings:
        cfg.setIncompatibleImprovements(new Version(2, 3, 23));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setLocale(Locale.US);
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        ClassPathResource cpr = new ClassPathResource("assets/dl4j-ui.js");
        String scriptContents = IOUtils.toString(cpr.getInputStream(), "UTF-8");

        Map<String, Object> pageElements = new HashMap<>();
        List<ComponentObject> list = new ArrayList<>();
        int i = 0;
        for (Component c : components) {
            list.add(new ComponentObject(String.valueOf(i), mapper.writeValueAsString(c)));
            i++;
        }
        pageElements.put("components", list);
        pageElements.put("scriptcontent", scriptContents);


        Template template = cfg.getTemplate("staticpage.ftl");
        Writer stringWriter = new StringWriter();
        template.process(pageElements, stringWriter);

        return stringWriter.toString();
    }
 
Example 10
Source File: FreeMarkerRenderer.java    From opoopress with Apache License 2.0 5 votes vote down vote up
public FreeMarkerRenderer(Site site) {
    super();
    this.site = site;
    templateDir = site.getTemplates();
    log.debug("Template directory: " + templateDir.getAbsolutePath());

    //Working directory
    workingTemplateDir = new File(site.getWorking(), "templates");
    PathUtils.checkDir(workingTemplateDir, PathUtils.Strategy.CREATE_IF_NOT_EXISTS);
    log.debug("Working template directory: {}", workingTemplateDir.getAbsolutePath());

    //config
    configuration = new Configuration();
    configuration.setObjectWrapper(new DefaultObjectWrapper());
    configuration.setTemplateLoader(buildTemplateLoader(site));

    Locale locale = site.getLocale();
    if (locale != null) {
        configuration.setLocale(site.getLocale());
    }

    //Add import i18n messages template.
    //config.addAutoImport("i18n", "i18n/messages.ftl");

    initializeAutoImportTemplates(site, configuration);
    initializeAutoIncludeTemplates(site, configuration);

    initializeTemplateModels();


    renderMethod = site.get(PROPERTY_PREFIX + "render_method");

    Boolean useMacroLayout = site.get(PROPERTY_PREFIX + "macro_layout");
    workingTemplateHolder = (useMacroLayout == null || useMacroLayout.booleanValue()) ?
            new MacroWorkingTemplateHolder() : new NonMacroWorkingTemplateHolder();
}
 
Example 11
Source File: EventEmail.java    From unitime with Apache License 2.0 4 votes vote down vote up
private String message() throws IOException, TemplateException {
	Configuration cfg = new Configuration(Configuration.VERSION_2_3_0);
	cfg.setClassForTemplateLoading(EventEmail.class, "");
	cfg.setLocale(Localization.getJavaLocale());
	cfg.setOutputEncoding("utf-8");
	Template template = cfg.getTemplate("confirmation.ftl");
	Map<String, Object> input = new HashMap<String, Object>();
	input.put("msg", MESSAGES);
	input.put("const", CONSTANTS);
	input.put("subject", subject());
	input.put("event", event());
	input.put("eventGridStartDay", ApplicationProperty.EventGridStartDay.intValue());
	input.put("operation", request().getOperation() == null ? "NONE" : request().getOperation().name());
	if (response().hasCreatedMeetings())
		input.put("created", EventInterface.getMultiMeetings(response().getCreatedMeetings(), true, false));
	if (response().hasDeletedMeetings())
		input.put("deleted", EventInterface.getMultiMeetings(response().getDeletedMeetings(), true, false));
	if (response().hasCancelledMeetings())
		input.put("cancelled", EventInterface.getMultiMeetings(response().getCancelledMeetings(), true, false));
	if (response().hasUpdatedMeetings())
		input.put("updated", EventInterface.getMultiMeetings(response().getUpdatedMeetings(), true, false));
	if (request().hasMessage())
		input.put("message", request().getMessage());
	if (request().getEvent().getId() != null) {
		if (event().hasMeetings()) {
			input.put("meetings", EventInterface.getMultiMeetings(event().getMeetings(), true, false));
		} else
			input.put("meetings", new TreeSet<MultiMeetingInterface>());
	}
	input.put("version", MESSAGES.pageVersion(Constants.getVersion(), Constants.getReleaseDate()));
	input.put("ts", new Date());
	input.put("link", ApplicationProperty.UniTimeUrl.value());
	if (iRequest.hasSessionId()) {
		Session session = SessionDAO.getInstance().get(iRequest.getSessionId());
		if (session != null)
			input.put("sessionId", session.getReference());
		else
			input.put("sessionId", iRequest.getSessionId());
	}
	
	
	
	StringWriter s = new StringWriter();
	template.process(input, new PrintWriter(s));
	s.flush(); s.close();

	return s.toString();
}