Java Code Examples for freemarker.template.Configuration#VERSION_2_3_23

The following examples show how to use freemarker.template.Configuration#VERSION_2_3_23 . 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: 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 3
Source File: TrasformazioniUtils.java    From govpay with GNU General Public License v3.0 6 votes vote down vote up
private static void _convertFreeMarkerTemplate(String name, byte[] template, Map<String,Object> dynamicMap, Writer writer) throws TrasformazioneException {
	try {
		// ** Aggiungo utility per usare metodi statici ed istanziare oggetti

		// statici
		BeansWrapper wrapper = new BeansWrapper(Configuration.VERSION_2_3_23);
		TemplateModel classModel = wrapper.getStaticModels();
		dynamicMap.put(Costanti.MAP_CLASS_LOAD_STATIC, classModel);

		// newObject
		dynamicMap.put(Costanti.MAP_CLASS_NEW_INSTANCE, new freemarker.template.utility.ObjectConstructor());


		// ** costruisco template
		Template templateFTL = TemplateUtils.buildTemplate(name, template);
		templateFTL.process(dynamicMap, writer);
		writer.flush();

	}catch(Exception e) {
		throw new TrasformazioneException(e.getMessage(),e);
	}
}
 
Example 4
Source File: FreemarkerStaticModels.java    From cms with Apache License 2.0 6 votes vote down vote up
public static TemplateHashModel useStaticPackage(String packageName) {
	try {
		// BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
		// Create the builder:
	    BeansWrapperBuilder builder = new BeansWrapperBuilder(Configuration.VERSION_2_3_23);
	    // Set desired BeansWrapper configuration properties:
	    builder.setUseModelCache(true);
	    builder.setExposeFields(true);
	    
	    // Get the singleton:
	    BeansWrapper wrapper = builder.build();
	    // You don't need the builder anymore.
		TemplateHashModel staticModels = wrapper.getStaticModels();
		TemplateHashModel fileStatics = (TemplateHashModel) staticModels.get(packageName);
		return fileStatics;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 5
Source File: PluginStatusReportViewBuilder.java    From kubernetes-elastic-agents with Apache License 2.0 5 votes vote down vote up
private PluginStatusReportViewBuilder() {
    configuration = new Configuration(Configuration.VERSION_2_3_23);
    configuration.setTemplateLoader(new ClassTemplateLoader(getClass(), "/"));
    configuration.setDefaultEncoding("UTF-8");
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    configuration.setLogTemplateExceptions(false);
    configuration.setDateTimeFormat("iso");
}
 
Example 6
Source File: Environment.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
private Environment() {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
    // Specify the data source where the template files come from.
    cfg.setClassForTemplateLoading(getClass(), "/templates/");
    DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_23);
    builder.setExposeFields(true);
    cfg.setObjectWrapper(builder.build());
    freemarkerConfig = cfg;

    fmHelper = new FreeMarkerHelper();
    templateCache = new ConcurrentHashMap<String, Template>();

    symbols = new ConcurrentHashMap<String, String>();

    textFormatter = new TextFormatter();

    xmlFormatter = new XMLFormatter();
    nsContext = new NamespaceContextImpl();
    fillNamespaceContext();
    xPathHelper = new XPathHelper();

    jsonPathHelper = new JsonPathHelper();
    jsonHelper = new JsonHelper();

    htmlCleaner = new HtmlCleaner();

    httpClient = new HttpClient();

    programHelper = new ProgramHelper();
    programHelper.setTimeoutHelper(timeoutHelper);
    configDatesHelper();

    driverManager = new DriverManager();
    cookieConverter = new CookieConverter();
}
 
Example 7
Source File: CreateFileUtil.java    From Spring-generator with MIT License 5 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);
	// 打包成jar包使用的路径
	String tempPath = Paths.get(Constant.TEMPLATE_DIR_NAME).toFile().getName();
	// 在项目运行的模板路径
	// String tempPath =
	// Thread.currentThread().getContextClassLoader().getResource(Constant.TEMPLATE_DIR_NAME).getFile();
	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 8
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 9
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 10
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 11
Source File: PluginStatusReportViewBuilder.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 5 votes vote down vote up
private PluginStatusReportViewBuilder() {
    configuration = new Configuration(Configuration.VERSION_2_3_23);
    configuration.setTemplateLoader(new ClassTemplateLoader(getClass(), "/"));
    configuration.setDefaultEncoding("UTF-8");
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    configuration.setLogTemplateExceptions(false);
    configuration.setDateTimeFormat("iso");
}
 
Example 12
Source File: ViewBuilder.java    From docker-elastic-agents-plugin with Apache License 2.0 5 votes vote down vote up
private ViewBuilder() {
    configuration = new Configuration(Configuration.VERSION_2_3_23);
    configuration.setTemplateLoader(new ClassTemplateLoader(getClass(), "/"));
    configuration.setDefaultEncoding("UTF-8");
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    configuration.setLogTemplateExceptions(false);
    configuration.setDateTimeFormat("iso");
}
 
Example 13
Source File: WaltzEmailer.java    From waltz with Apache License 2.0 5 votes vote down vote up
public void sendEmail(String subject,
                      String body,
                      String[] to) {

    if (this.mailSender == null) {
        LOG.warn("Not sending email.  No mailer provided.");
        return;
    }
    Checks.checkNotEmpty(subject, "subject cannot be empty");
    Checks.checkNotEmpty(body, "body cannot be empty");
    Checks.checkNotEmpty(to, "to cannot be empty");
    Checks.checkAll(to, StringUtilities::notEmpty, "email address cannot be empty");

    MimeMessagePreparator preparator = mimeMessage -> {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
        message.setSubject(subject);
        message.setFrom(fromEmail);
        message.setBcc(to);
        message.addAttachment("waltz.png", IOUtilities.getFileResource("/images/waltz.png"));
        message.addAttachment("client-logo", IOUtilities.getFileResource("/templates/images/client-logo.png"));

        Map model = new HashMap();
        model.put("body", body);

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);

        try(InputStreamReader templateReader = new InputStreamReader(IOUtilities
                .getFileResource(DEFAULT_EMAIL_TEMPLATE_LOCATION)
                .getInputStream())) {
            Template template = new Template("template", templateReader, cfg);
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
            message.setText(text, true);
        }
    };

    this.mailSender.send(preparator);
}
 
Example 14
Source File: RefTypeEnumGenerator.java    From eveapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(final String[] args) throws IOException, TemplateException, ApiException {
    final RefTypesParser parser = new RefTypesParser();
    final RefTypesResponse response = parser.getResponse();
    final Collection<RefType> refTypes = response.getAll();
    final Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
    final Template tpl = cfg.getTemplate("src/test/resources/refType.ftl");
    final FileWriter output = new FileWriter("src/test/java/com/beimin/eveapi/shared/wallet/RefType.java");
    final HashMap<String, Object> model = new HashMap<String, Object>();
    model.put("refTypes", refTypes);
    tpl.process(model, output);
    output.flush();
    output.close();
}
 
Example 15
Source File: FreemarkerServiceImpl.java    From jframe with Apache License 2.0 5 votes vote down vote up
private Configuration createConfiguration(String id) throws IOException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
    File dir = new File(_conf.getConf(id, FtlPropsConf.P_ftl_dir));
    dir.mkdirs();
    cfg.setDirectoryForTemplateLoading(dir);
    cfg.setDefaultEncoding(_conf.getConf(id, FtlPropsConf.P_ftl_encoding, "UTF-8"));
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(false);
    return cfg;
}
 
Example 16
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 17
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 18
Source File: FreemarkerContext.java    From allure2 with Apache License 2.0 4 votes vote down vote up
public FreemarkerContext() {
    this.configuration = new Configuration(Configuration.VERSION_2_3_23);
    this.configuration.setLocalizedLookup(false);
    this.configuration.setTemplateUpdateDelayMilliseconds(0);
    this.configuration.setClassLoaderForTemplateLoading(getClass().getClassLoader(), BASE_PACKAGE_PATH);
}
 
Example 19
Source File: NotificationServiceImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
public void init() {
    configuration = new Configuration(Configuration.VERSION_2_3_23);
    configuration.setTimeZone(TimeZone.getTimeZone(getTemplateTimezone()));
    configuration.setObjectWrapper(new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_23).build());
}
 
Example 20
Source File: HtmlReportWriter.java    From vind with Apache License 2.0 3 votes vote down vote up
public HtmlReportWriter() {

        this.cfg = new Configuration(Configuration.VERSION_2_3_23);

        this.cfg.setDefaultEncoding(DEFAULT_ENCODING);
        this.cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER/*RETHROW_HANDLER*/);//TODO: update when finished
        this.cfg.setLogTemplateExceptions(false);

        this.reportTemplate = this.loadTemplate(DEFAULT_HTML_TEMPLATE);
    }