Java Code Examples for freemarker.template.Configuration#setDirectoryForTemplateLoading()
The following examples show how to use
freemarker.template.Configuration#setDirectoryForTemplateLoading() .
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 |
/** * 执行创建文件 * * @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: WelcomePage.java From yuzhouwan with Apache License 2.0 | 5 votes |
/** * 创建 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 3
Source File: FreeMarkerUtils.java From seezoon-framework-all with Apache License 2.0 | 5 votes |
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 4
Source File: FreemarkerTemplateService.java From lemon with Apache License 2.0 | 5 votes |
@PostConstruct public void init() throws IOException { configuration = new Configuration(Configuration.VERSION_2_3_21); File templateDir = new File(baseDir); templateDir.mkdirs(); configuration.setDirectoryForTemplateLoading(templateDir); }
Example 5
Source File: TrainModule.java From deeplearning4j with Apache License 2.0 | 5 votes |
/** * 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 6
Source File: ServiceGenerator.java From fast-family-master with Apache License 2.0 | 5 votes |
private static void genServiceInterface(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//"; String savePath = filePath + className + "Service.java"; File dirPath = new File(filePath); if (!dirPath.exists()) { dirPath.mkdirs(); } try (FileWriter fileWriter = new FileWriter(new File(savePath))) { Template template = configuration.getTemplate("service.ftl"); template.process(paramMap, fileWriter); } } catch (Exception e) { e.printStackTrace(); } }
Example 7
Source File: FreeMarkerTemplateHander.java From VX-API-Gateway with MIT License | 5 votes |
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 8
Source File: Freemarker.java From admin-plus with Apache License 2.0 | 5 votes |
/** * 通过文件名加载模版 * @param ftlName */ public static Template getTemplate(String ftlName, String ftlPath) throws Exception{ try { Configuration cfg = new Configuration(); //通过Freemaker的Configuration读取相应的ftl cfg.setEncoding(Locale.CHINA, "utf-8"); cfg.setDirectoryForTemplateLoading(new File(PathsUtils.getClassResources()+ftlPath)); //设定去哪里读取相应的ftl模板文件 Template temp = cfg.getTemplate(ftlName); //在模板文件目录中找到名称为name的文件 return temp; } catch (IOException e) { e.printStackTrace(); } return null; }
Example 9
Source File: EntityGenerator.java From fast-family-master with Apache License 2.0 | 5 votes |
public static void generatorSingleEntity(String tableName, String className, String classComment, GeneratorConfig generatorConfig) { TableInfo tableInfo = AnalysisDB.getTableInfoByName(tableName, generatorConfig); Map<String, Object> paramMap = new HashMap<>(); paramMap.put("className", className); paramMap.put("tableInfo", tableInfo); paramMap.put("sysTime", new Date()); paramMap.put("classComment", classComment); paramMap.put("packageName", generatorConfig.getPackageName()); Version version = new Version("2.3.27"); Configuration configuration = new Configuration(version); try { configuration.setObjectWrapper(new DefaultObjectWrapper(version)); configuration.setDirectoryForTemplateLoading(new File(EntityGenerator.class.getClassLoader() .getResource("ftl").getPath())); String savePath = PackageDirUtils.getPackageEntityDir(generatorConfig.getSrcBasePath()); String filePath = generatorConfig.getSrcBasePath() + "entity//"; savePath = filePath + className + ".java"; File dirPath = new File(filePath); if (!dirPath.exists()) { dirPath.mkdirs(); } try (FileWriter fileWriter = new FileWriter(savePath)) { Template temporal = configuration.getTemplate("entity.ftl"); temporal.process(paramMap, fileWriter); } System.out.println("************" + savePath + "************"); } catch (Exception e) { e.printStackTrace(); } }
Example 10
Source File: ControllerGenerator.java From fast-family-master with Apache License 2.0 | 5 votes |
private static void genController(String className, String classComment, String urlStr, 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()); paramMap.put("url", urlStr); Version version = new Version("2.3.27"); Configuration configuration = new Configuration(version); try { URL url = ControllerGenerator.class.getClassLoader().getResource(resourcePath); configuration.setDirectoryForTemplateLoading(new File(url.getPath())); configuration.setObjectWrapper(new DefaultObjectWrapper(version)); String filePath = generatorConfig.getSrcBasePath() + "controller//"; String savePath = filePath + className + "Controller.java"; File dirPath = new File(filePath); if (!dirPath.exists()) { dirPath.mkdirs(); } try (FileWriter fileWriter = new FileWriter(new File(savePath))) { Template template = configuration.getTemplate("/controller.ftl"); template.process(paramMap, fileWriter); } } catch (Exception e) { e.printStackTrace(); } }
Example 11
Source File: CreateFileUtil.java From Spring-generator with MIT License | 5 votes |
/** * 执行创建文件 * * @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 12
Source File: MagicWebSiteGenerator.java From MtgDesktopCompanion with GNU General Public License v3.0 | 5 votes |
public MagicWebSiteGenerator(String template, String dest) throws IOException { cfg = new Configuration(MTGConstants.FREEMARKER_VERSION); cfg.setDirectoryForTemplateLoading(new File(MTGConstants.MTG_TEMPLATES_DIR, template)); cfg.setDefaultEncoding(MTGConstants.DEFAULT_ENCODING.displayName()); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setObjectWrapper(new DefaultObjectWrapperBuilder(MTGConstants.FREEMARKER_VERSION).build()); this.dest = dest; FileUtils.copyDirectory(new File(MTGConstants.MTG_TEMPLATES_DIR, template), new File(dest), pathname -> { if (pathname.isDirectory()) return true; return !pathname.getName().endsWith(".html"); }); }
Example 13
Source File: CodeGenerator.java From QuickProject with Apache License 2.0 | 5 votes |
public static void generateDaoGetMethod(boolean isReturnList, String beanNameRegex, String tableName, String attrs) throws IOException, TemplateException { File dir = resourceLoader.getResource("classpath:/tmpl/code").getFile(); Bean bean = new Bean(); bean.setTableName(tableName); String[] attrArray = attrs.replace(", ", ",").split(","); for (String attr : attrArray) { try { String[] splits = attr.split(" "); Property property = new Property(); property.setType(new PropertyType(splits[0])); property.setName(splits[1]); bean.addProperty(property); } catch (Exception e) { throw new RuntimeException("attr的格式应为$Javatype$ $attrName$"); } } Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(dir); cfg.setObjectWrapper(new DefaultObjectWrapper()); Template temp = cfg.getTemplate(isReturnList ? "daoGetForListMethodTmpl.ftl" : "daoGetForObjMethodTmpl.ftl"); Map dataMap = new HashMap(); dataMap.put("bean", bean); if (beanNameRegex != null) { // 根据用户设置修正beanName Pattern pattern = Pattern.compile(beanNameRegex); Matcher matcher = pattern.matcher(bean.getTableName()); matcher.find(); String group = matcher.group(matcher.groupCount()); bean.setName(StringUtils.uncapitalizeCamelBySeparator(group, "_")); } Writer out = new OutputStreamWriter(System.out); temp.process(dataMap, out); out.flush(); out.close(); }
Example 14
Source File: FreemarkerTemplateEngine.java From jbake with MIT License | 5 votes |
private void createTemplateConfiguration() { templateCfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); templateCfg.setDefaultEncoding(config.getRenderEncoding()); try { templateCfg.setDirectoryForTemplateLoading(config.getTemplateFolder()); } catch (IOException e) { e.printStackTrace(); } }
Example 15
Source File: ObjectRenderer.java From Repeat with Apache License 2.0 | 5 votes |
public ObjectRenderer(File templateDir) { config = new Configuration(Configuration.VERSION_2_3_28); try { config.setDirectoryForTemplateLoading(templateDir); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Error setting template directory to " + templateDir.getAbsolutePath(), e); } config.setDefaultEncoding("UTF-8"); config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); config.setLogTemplateExceptions(false); config.setWrapUncheckedExceptions(true); }
Example 16
Source File: NoticeService.java From JobX with Apache License 2.0 | 5 votes |
@PostConstruct public void initConfig() throws Exception { Configuration configuration = new Configuration(); File file = new File(servletContext.getRealPath("/WEB-INF/layouts")); configuration.setDirectoryForTemplateLoading(file); configuration.setDefaultEncoding("UTF-8"); this.template = configuration.getTemplate("email.html"); }
Example 17
Source File: TemplateParser.java From camunda-bpm-platform with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws IOException, TemplateException { if (args.length != 4) { throw new RuntimeException( "Must provide four arguments: " + "<source template directory> " + "<main template> " + "<output directory> " + "<intermediate output dir>"); } String sourceDirectory = args[0]; String mainTemplate = args[1]; String outputFile = args[2]; String debugFile = args[3]; Configuration cfg = new Configuration(Configuration.VERSION_2_3_29); cfg.setDirectoryForTemplateLoading(new File(sourceDirectory)); cfg.setDefaultEncoding("UTF-8"); Template template = cfg.getTemplate(mainTemplate); Map<String, Object> templateData = createTemplateData(sourceDirectory); try (StringWriter out = new StringWriter()) { template.process(templateData, out); // create intermediate json file before the formatting String path = createOutputFile(debugFile); FileUtils.forceMkdir(new File(debugFile)); Files.write(Paths.get(path), out.getBuffer().toString().getBytes()); // format json with Gson String jsonString = out.getBuffer().toString(); String formattedJson = formatJsonString(jsonString); File outFile = new File(outputFile); FileUtils.forceMkdir(outFile.getParentFile()); Files.write(outFile.toPath(), formattedJson.getBytes()); } }
Example 18
Source File: FreeMarkers.java From Shop-for-JavaWeb with MIT License | 4 votes |
public static Configuration buildConfiguration(String directory) throws IOException { Configuration cfg = new Configuration(); Resource path = new DefaultResourceLoader().getResource(directory); cfg.setDirectoryForTemplateLoading(path.getFile()); return cfg; }
Example 19
Source File: FreemarkerController.java From mogu_blog_v2 with Apache License 2.0 | 4 votes |
/** * 生成静态文件 * * @throws IOException * @throws TemplateException */ public void generateHtml(String uid) { try { //创建配置类 Configuration configuration = new Configuration(Configuration.getVersion()); String classpath = this.getClass().getResource("/").getPath(); //设置模板路径 configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/")); //设置字符集 configuration.setDefaultEncoding("utf-8"); //加载模板 Template template = configuration.getTemplate("info.ftl"); //数据模型 Map map = new HashMap(); List<Blog> sameBlog = blogService.getSameBlogByBlogUid(uid); sameBlog = setBlog(sameBlog); List<Blog> thirdBlog = blogService.getBlogListByLevel(ELevel.THIRD); thirdBlog = setBlog(thirdBlog); List<Blog> fourthBlog = blogService.getBlogListByLevel(ELevel.FOURTH); fourthBlog = setBlog(fourthBlog); map.put("vueWebBasePath", "http://localhost:9527/#/"); map.put("webBasePath", "http://localhost:8603"); map.put("staticBasePath", "http://localhost:8600"); map.put("webConfig", webConfigService.getWebConfig()); map.put("blog", blogService.getBlogByUid(uid)); map.put("sameBlog", sameBlog); map.put("hotBlogList", blogService.getBlogListByTop(SysConf.FIVE)); //静态化 String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map); InputStream inputStream = IOUtils.toInputStream(content); //输出文件 String savePath = fileUploadPath + "/blog/page/" + uid + ".html"; FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath)); int copy = IOUtils.copy(inputStream, fileOutputStream); } catch (Exception e) { e.getMessage(); } }
Example 20
Source File: FreeMarkerExportHandler.java From pcgen with GNU Lesser General Public License v2.1 | 4 votes |
/** * 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) { } } } }