Java Code Examples for org.apache.velocity.app.Velocity#getTemplate()
The following examples show how to use
org.apache.velocity.app.Velocity#getTemplate() .
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: Test1.java From java-course-ee with MIT License | 6 votes |
public Test1() throws Exception { //init Velocity.init("Velocity/GS_Velocity_1/src/main/java/velocity.properties"); // get Template Template template = Velocity.getTemplate("Test1.vm"); // getContext Context context = new VelocityContext(); // get Writer Writer writer = new StringWriter(); // merge template.merge(context, writer); System.out.println(writer.toString()); }
Example 2
Source File: AbstractPOJOGenMojo.java From olingo-odata4 with Apache License 2.0 | 6 votes |
protected void parseObj( final File base, final boolean append, final String pkg, final String name, final String out, final Map<String, Object> objs) throws MojoExecutionException { final VelocityContext ctx = newContext(); ctx.put("package", pkg); if (objs != null) { for (Map.Entry<String, Object> obj : objs.entrySet()) { if (StringUtils.isNotBlank(obj.getKey()) && obj.getValue() != null) { ctx.put(obj.getKey(), obj.getValue()); } } } final Template template = Velocity.getTemplate(name + ".vm"); writeFile(out, base, ctx, template, append); }
Example 3
Source File: CodeGenerator.java From ueboot with BSD 3-Clause "New" or "Revised" License | 6 votes |
private String getTemplateString(String templateName, VelocityContext context) { Properties p = new Properties(); String path = Thread.currentThread().getContextClassLoader().getResource("velocity").getFile(); p.setProperty(Velocity.RESOURCE_LOADER, "class"); p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path); p.setProperty("class.resource.loader.path", path); p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); p.setProperty(Velocity.INPUT_ENCODING, "UTF-8"); p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8"); Velocity.init(p); Template template = Velocity.getTemplate("velocity" + separator + "uebootv2" + separator + templateName, "UTF-8"); StringWriter writer = new StringWriter(); template.merge(context, writer); return writer.toString(); }
Example 4
Source File: AbstractTitanAssemblyIT.java From titan1withtp3.1 with Apache License 2.0 | 6 votes |
protected void parseTemplateAndRunExpect(String expectTemplateName, Map<String, String> contextVars) throws IOException, InterruptedException { VelocityContext context = new VelocityContext(); for (Map.Entry<String, String> ent : contextVars.entrySet()) { context.put(ent.getKey(), ent.getValue()); } Template template = Velocity.getTemplate(expectTemplateName); String inputPath = EXPECT_DIR + File.separator + expectTemplateName; String outputPath = inputPath.substring(0, inputPath.length() - 3); Writer output = new FileWriter(outputPath); template.merge(context, output); output.close(); expect(ZIPFILE_EXTRACTED, outputPath); }
Example 5
Source File: GenTableServiceImpl.java From RuoYi-Vue with MIT License | 6 votes |
/** * 预览代码 * * @param tableId 表编号 * @return 预览数据列表 */ @Override public Map<String, String> previewCode(Long tableId) { Map<String, String> dataMap = new LinkedHashMap<>(); // 查询表信息 GenTable table = genTableMapper.selectGenTableById(tableId); // 查询列信息 List<GenTableColumn> columns = table.getColumns(); setPkColumn(table, columns); VelocityInitializer.initVelocity(); VelocityContext context = VelocityUtils.prepareContext(table); // 获取模板列表 List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory()); for (String template : templates) { // 渲染模板 StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(template, Constants.UTF8); tpl.merge(context, sw); dataMap.put(template, sw.toString()); } return dataMap; }
Example 6
Source File: VelocityUtil.java From zheng with MIT License | 6 votes |
/** * 根据模板生成文件 * @param inputVmFilePath 模板路径 * @param outputFilePath 输出文件路径 * @param context * @throws Exception */ public static void generate(String inputVmFilePath, String outputFilePath, VelocityContext context) throws Exception { try { Properties properties = new Properties(); properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, getPath(inputVmFilePath)); Velocity.init(properties); //VelocityEngine engine = new VelocityEngine(); Template template = Velocity.getTemplate(getFile(inputVmFilePath), "utf-8"); File outputFile = new File(outputFilePath); FileWriterWithEncoding writer = new FileWriterWithEncoding(outputFile, "utf-8"); template.merge(context, writer); writer.close(); } catch (Exception ex) { throw ex; } }
Example 7
Source File: Main.java From java-course-ee with MIT License | 6 votes |
private static void sendUpdatesEmail() { Category news = new Category("News"); news.getContent().add(new Content("News number 1", "Text blah-blah-blah", new Date())); news.getContent().add(new Content("News number 2", "Text2 blah-blah-blah", new Date())); news.getContent().add(new Content("News number 3", "Text3 blah-blah-blah", new Date())); Category events = new Category("Events"); events.getContent().add(new Content("Event number 1", "Text blah-blah-blah", new Date())); events.getContent().add(new Content("Event number 2", "Text2 blah-blah-blah", new Date())); events.getContent().add(new Content("Event number 3", "Text3 blah-blah-blah", new Date())); Template template = Velocity.getTemplate("updates.vm"); Context context = new VelocityContext(); context.put("currentDate", new Date()); context.put("categories", Arrays.asList(news, events)); Writer writer = new StringWriter(); template.merge(context, writer); EmailUtil.send("[email protected]", "News updates", writer.toString(), EmailUtil.EmailType.HTML); }
Example 8
Source File: VelocityConfigFileWriter.java From oodt with Apache License 2.0 | 6 votes |
@Override public File generateFile(String filePath, Metadata metadata, Logger logger, Object... args) throws IOException { File configFile = new File(filePath); VelocityMetadata velocityMetadata = new VelocityMetadata(metadata); // Velocity requires you to set a path of where to look for // templates. This path defaults to . if not set. int slashIndex = ((String) args[0]).lastIndexOf('/'); String templatePath = ((String) args[0]).substring(0, slashIndex); Velocity.setProperty("file.resource.loader.path", templatePath); // Initialize Velocity and set context up Velocity.init(); VelocityContext context = new VelocityContext(); context.put("metadata", velocityMetadata); context.put("env", System.getenv()); // Load template from templatePath String templateName = ((String) args[0]).substring(slashIndex); Template template = Velocity.getTemplate(templateName); // Fill out template and write to file StringWriter sw = new StringWriter(); template.merge(context, sw); FileUtils.writeStringToFile(configFile, sw.toString()); return configFile; }
Example 9
Source File: GenServiceImpl.java From RuoYi with Apache License 2.0 | 5 votes |
/** * 根据表信息生成代码 * @param zip 生成后的压缩包 * @param tableName 表名 */ private void generatorCode(ZipOutputStream zip, String tableName) { // 查询表信息 TableInfo table = genMapper.selectTableByName(tableName); // 查询列信息 List<ColumnInfo> columns = genMapper.selectTableColumnsByName(tableName); // 表名转换成Java属性名 String className = GenUtils.tableToJava(table.getTableName()); table.setClassName(className); table.setClassname(StrUtil.lowerFirst(className)); // 列信息 table.setColumns(GenUtils.transColums(columns)); // 设置主键 table.setPrimaryKey(table.getColumnsLast()); VelocityInitializer.initVelocity(); String packageName = Global.getPackageName(); String moduleName = GenUtils.getModuleName(packageName); VelocityContext context = GenUtils.getVelocityContext(table); // 获取模板列表 List<String> templates = GenUtils.getTemplates(); for (String template : templates) { // 渲染模板 StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(template, CharsetKit.UTF8); tpl.merge(context, sw); try { // 添加到zip zip.putNextEntry(new ZipEntry(Objects.requireNonNull(GenUtils.getFileName(template, table, moduleName)))); IOUtils.write(sw.toString(), zip, CharsetKit.UTF8); IOUtils.closeQuietly(sw); zip.closeEntry(); } catch (IOException e) { log.error("渲染模板失败,表名:" + table.getTableName(), e); } } }
Example 10
Source File: GeneratorServiceImpl.java From code-generator with MIT License | 5 votes |
private void generatorCode(TemplateContext context, ZipOutputStream zos) { VelocityContext velocityContext = new VelocityContext(context.toMap()); Map<String, String> outputPathMap = parseTemplateOutputPaths(context); for (Map.Entry<String, String> entry : outputPathMap.entrySet()) { Template template = Velocity.getTemplate(entry.getKey(), "UTF-8"); try (StringWriter writer = new StringWriter()) { template.merge(velocityContext, writer); zos.putNextEntry(new ZipEntry(entry.getValue())); IOUtils.write(writer.toString(), zos, "UTF-8"); zos.closeEntry(); } catch (IOException e) { e.printStackTrace(); } } }
Example 11
Source File: EncodingTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
public void testHighByteChinese2() throws Exception { VelocityContext context = new VelocityContext(); assureResultsDirectoryExists(RESULT_DIR); /* * a 'high-byte' chinese from Ilkka */ Template template = Velocity.getTemplate( getFileName( null, "encodingtest3", TMPL_FILE_EXT), "GBK"); FileOutputStream fos = new FileOutputStream ( getFileName(RESULT_DIR, "encodingtest3", RESULT_FILE_EXT)); Writer writer = new BufferedWriter(new OutputStreamWriter(fos, "GBK")); template.merge(context, writer); writer.flush(); writer.close(); if (!isMatch(RESULT_DIR,COMPARE_DIR,"encodingtest3", RESULT_FILE_EXT,CMP_FILE_EXT) ) { fail("Output 3 incorrect."); } }
Example 12
Source File: GenServiceImpl.java From NutzSite with Apache License 2.0 | 5 votes |
/** * 生成代码预览 * @param tableName * @param templates * @return */ @Override public Map<String, String> previewCode(String tableName, List<String> templates){ Map<String, String> dataMap = new LinkedHashMap<>(); // 查询表信息 TableInfo table = this.selectTableByName(tableName); // 查询列信息 List<ColumnInfo> columns = this.selectTableColumnsByName(tableName); if (Lang.isNotEmpty(table) && Lang.isNotEmpty(columns)) { // 生成代码 // 表名转换成Java属性名 String className = GenUtils.tableToJava(table.getTableName()); table.setClassName(className); table.setClassname(StringUtils.uncapitalize(className)); // 列信息 table.setColumns(GenUtils.transColums(columns)); // 设置主键 table.setPrimaryKey(table.getColumnsLast()); VelocityInitializer.initVelocity(); String packageName = GenConfig.getPackageName(); String moduleName = GenUtils.getModuleName(packageName); VelocityContext context = GenUtils.getVelocityContext(table); for (String template : templates) { // 渲染模板 StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(template, Globals.UTF8); tpl.merge(context, sw); dataMap.put(template, sw.toString()); } return dataMap; } return null; }
Example 13
Source File: Test4.java From java-course-ee with MIT License | 5 votes |
public Test4() throws Exception { Velocity.init("src/main/java/velocity.properties"); // get Template Template template = Velocity.getTemplate("Test4.vm"); // getContext Context context = new VelocityContext(); int a = 3; int b = 5; String s1 = "Hello"; String s2 = "World"; context.put("a", a); context.put("b", b); context.put("s1", s1); context.put("s2", s2); // get Writer Writer writer = new StringWriter(); // merge template.merge(context, writer); System.out.println(writer.toString()); }
Example 14
Source File: AbstractVelocityExporter.java From LicenseScout with Apache License 2.0 | 5 votes |
/** * Obtains the velocity template to use in the export method. * * @param reportConfiguration * @return the velocity template to use */ protected Template getTemplate(final ReportConfiguration reportConfiguration) { if (reportConfiguration.getTemplateFile() != null) { final String templateEncoding = ExporterUtil.getTemplateCharset(reportConfiguration).name(); return Velocity.getTemplate(reportConfiguration.getTemplateFile().getAbsolutePath(), templateEncoding); } else { return getDefaultTemplate(); } }
Example 15
Source File: GeneratorUtil.java From vaadinator with Apache License 2.0 | 5 votes |
public static void runVelocity(BeanDescription desc, Map<String, Object> commonMap, String pckg, String modelPckg, String presenterPckg, String viewPckg, String profileName, String templateName, File outFile, boolean mandatory, String templatePackage, Log log) throws IOException { Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); Velocity.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); Template template; // Issue #6: for optional templates check whether it's there boolean runTemplate; if (mandatory) { runTemplate = true; } else { runTemplate = isTemplateExisting(templateName, templatePackage); } if (!runTemplate) { return; } template = Velocity.getTemplate(templatePackage + templateName); String className = desc != null ? desc.getClassName() : "no description found "; log.debug("Create file with template: "+ template.getName() + " for bean " + className + " in profile: " + profileName); VelocityContext context = new VelocityContext(); context.put("bean", desc); context.put("common", commonMap); context.put("package", pckg); context.put("modelPackage", modelPckg); context.put("presenterPackage", presenterPckg); context.put("viewPackage", viewPckg); context.put("profileName", profileName); context.put("unicodeUtil", UnicodeUtil.SINGLETON); Writer writer = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"); template.merge(context, writer); writer.close(); log.info("Written file: " + outFile); }
Example 16
Source File: EncodingTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
public void testHighByteChinese() throws Exception { VelocityContext context = new VelocityContext(); assureResultsDirectoryExists(RESULT_DIR); /* * a 'high-byte' chinese example from Michael Zhou */ Template template = Velocity.getTemplate( getFileName( null, "encodingtest2", TMPL_FILE_EXT), "UTF-8"); FileOutputStream fos = new FileOutputStream ( getFileName(RESULT_DIR, "encodingtest2", RESULT_FILE_EXT)); Writer writer = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8")); template.merge(context, writer); writer.flush(); writer.close(); if (!isMatch(RESULT_DIR,COMPARE_DIR,"encodingtest2", RESULT_FILE_EXT,CMP_FILE_EXT) ) { fail("Output 2 incorrect."); } }
Example 17
Source File: GenTableServiceImpl.java From supplierShop with MIT License | 5 votes |
/** * 查询表信息并生成代码 */ private void generatorCode(String tableName, ZipOutputStream zip) { // 查询表信息 GenTable table = genTableMapper.selectGenTableByName(tableName); // 查询列信息 List<GenTableColumn> columns = table.getColumns(); setPkColumn(table, columns); VelocityInitializer.initVelocity(); VelocityContext context = VelocityUtils.prepareContext(table); // 获取模板列表 List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory()); for (String template : templates) { // 渲染模板 StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(template, Constants.UTF8); tpl.merge(context, sw); try { // 添加到zip zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table))); IOUtils.write(sw.toString(), zip, Constants.UTF8); IOUtils.closeQuietly(sw); zip.closeEntry(); } catch (IOException e) { log.error("渲染模板失败,表名:" + table.getTableName(), e); } } }
Example 18
Source File: TxtExporter.java From LicenseScout with Apache License 2.0 | 4 votes |
/** * {@inheritDoc} */ @Override protected Template getDefaultTemplate() { return Velocity.getTemplate(DEFAULT_TEMPLATES_LICENSE_REPORT_VM, DEFAULT_TEMPLATE_ENCODING); }
Example 19
Source File: Main.java From orcas with Apache License 2.0 | 4 votes |
private static void _writeHTML( String pHtmlOutDir, GraphRef pGraphRef, Schema pSchema, String pTableSourcefileFolder ) throws Exception { ArrayList<String> lSubGraphLinks = new ArrayList<String>(); ArrayList<String> lSubTableLinks = new ArrayList<String>(); ArrayList<String> lParentGraphLinks = new ArrayList<String>(); ArrayList<Table> lContainedTables = new ArrayList<Table>(); _createSubgraphListRecursive( lSubGraphLinks, pGraphRef, 0 ); for( Table lTable : pSchema.getTables() ) { if( pGraphRef.getGraph().containsTableRecursive( lTable ) ) { lContainedTables.add( lTable ); lSubTableLinks.add( _getHtmlLinkForGraph( pGraphRef.createForOtherGraph( new GraphForSingleTable( lTable, Collections.singletonList( pGraphRef.getGraph() ), null ) ) ) ); } } // Wurzelgraphnamen in Link umwandeln String lParentGraphLink; if( pGraphRef.getGraph().isRoot() || pGraphRef.getGraph().isSingleTable() ) { lParentGraphLink = null; if( pGraphRef.getGraph().isSingleTable() ) { _getHtmlLinksForDiagramsContainingTables( lParentGraphLinks, pGraphRef.createForOtherGraph( pGraphRef.getGraph().getParentGraph() ), lContainedTables.get( 0 ) ); lSubTableLinks.clear(); } } else { lParentGraphLink = ""; Graph lParent = pGraphRef.getGraph().getParentGraph(); do { lParentGraphLink = _getHtmlLinkForGraph( pGraphRef.createForOtherGraph( lParent ) ) + (lParentGraphLink.length() == 0 ? "" : " -> " + lParentGraphLink); if( lParent.isRoot() ) { break; } lParent = lParent.getParentGraph(); } while( true ); } String lGraphChangeLink = ""; for( GraphRef lGraphRef : pGraphRef.getOtherLinkedGraphRefs() ) { lGraphChangeLink += " " + _getHtmlLinkForGraph( lGraphRef ); } lGraphChangeLink = lGraphChangeLink.trim(); if( lGraphChangeLink.length() == 0 ) { lGraphChangeLink = null; } String lTableSource = null; if( pGraphRef.getGraph().isSingleTable() && pTableSourcefileFolder != null && pTableSourcefileFolder.length() > 0 ) { File lFile = new File( pTableSourcefileFolder + "/" + pGraphRef.getGraph().getLabel().toLowerCase() + ".sql" ); if( lFile.exists() ) { lTableSource = readFile( lFile ); } } VelocityEngine lVelocityEngine = new VelocityEngine(); lVelocityEngine.init(); Template lTemplate = Velocity.getTemplate( "graphtemplate.vm" ); VelocityContext lVelocityContext = new VelocityContext(); lVelocityContext.put( "pImageName", _getImgFileNameForGraph( pGraphRef ) ); lVelocityContext.put( "pSvgName", getFileNameForGraph( pGraphRef, "svg" ) ); lVelocityContext.put( "pGraphChangeLink", lGraphChangeLink ); lVelocityContext.put( "pTitle", pGraphRef.getGraph().getLabel() ); lVelocityContext.put( "pParentGraphLink", lParentGraphLink ); lVelocityContext.put( "pParentGraphLinks", lParentGraphLinks.isEmpty() ? null : lParentGraphLinks ); lVelocityContext.put( "pSubGraphLinks", lSubGraphLinks.isEmpty() ? null : lSubGraphLinks ); lVelocityContext.put( "pSubTableLinks", lSubTableLinks.isEmpty() ? null : lSubTableLinks ); lVelocityContext.put( "pTableSource", lTableSource ); FileWriter lFileWriter = new FileWriter( pHtmlOutDir + "/" + getHtmlFileNameForGraph( pGraphRef ) ); lTemplate.merge( lVelocityContext, lFileWriter ); lFileWriter.close(); }
Example 20
Source File: GenerateUtil.java From JavaWeb with Apache License 2.0 | 4 votes |
/** public static void generateZipFile(String tableNames[]) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(outputStream); for(String tableName : tableNames){ TableInfo tableInfo = new TableInfo(); tableInfo.setTableName("sys_user"); tableInfo.setTableComment("系统用户表"); tableInfo.setEngine("InnoDB"); tableInfo.setCreateTime(DateUtil.getDefaultDate()); List<ColumnInfo> tableColumns = new ArrayList<ColumnInfo>(); ColumnInfo columnInfo1 = new ColumnInfo();ColumnInfo columnInfo2 = new ColumnInfo(); columnInfo1.setColumnName("id");columnInfo2.setColumnName("address"); columnInfo1.setDataType("int");columnInfo2.setDataType("varchar"); columnInfo1.setColumnComment("主键ID");columnInfo2.setColumnComment("地址"); columnInfo1.setColumnKey("PRI");columnInfo2.setColumnKey(""); columnInfo1.setExtra("额外");columnInfo2.setExtra(""); tableColumns.add(columnInfo1);tableColumns.add(columnInfo2); GenerateConfigInfo generateConfigInfo = new GenerateConfigInfo(); generateConfigInfo.setAuthor("张三"); generateConfigInfo.setEmail("[email protected]"); generateConfigInfo.setPackageName("com.javaweb"); generatorCode(tableInfo, tableColumns, generateConfigInfo, zip); } IOUtils.closeQuietly(zip); byte[] bytes = outputStream.toByteArray(); OutputStream zipOutputStream = new FileOutputStream(new File("F:/a.zip")); zipOutputStream.write(bytes); zipOutputStream.close(); } */ public static void generatorCode(TableInfo tableInfo, List<ColumnInfo> tableColumns, GenerateConfigInfo generateConfigInfo, ZipOutputStream zip) { tableColumns.stream().forEach(each->{ String dataType = each.getDataType(); if("decimal".equals(dataType)){ tableInfo.setHasBigDecimal(true); } if("date".equals(dataType)||"datetime".equals(dataType)||"timestamp".equals(dataType)){ tableInfo.setHasDate(true); } each.setAttrType(Constant.MYSQL_COLUMN_TYPE_MAPPER.get(dataType)); each.setAttrName(getAttrName(each.getColumnName())); each.setAttrNameForTitleCase(getAttrNameForTitleCase(each.getAttrName())); }); tableInfo.setClassName(getAttrNameForTitleCase(getAttrName(tableInfo.getTableName()))); tableInfo.setClassNameForLowerCase(getClassNameForLowerCase(getAttrName(tableInfo.getTableName()))); //设置velocity资源加载器 Properties properties = new Properties(); properties.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocity.init(properties); //封装模板数据 Map<String, Object> map = new HashMap<>(); map.put("hasBigDecimal",tableInfo.isHasBigDecimal()); map.put("hasDate",tableInfo.isHasDate()); map.put("tableComment",tableInfo.getTableComment()); map.put("packageName",generateConfigInfo.getPackageName()); map.put("author",generateConfigInfo.getAuthor()); map.put("email",generateConfigInfo.getEmail()); map.put("dateTime",DateUtil.getDefaultDate()); map.put("className",tableInfo.getClassName()); map.put("classNameForLowerCase",tableInfo.getClassNameForLowerCase()); map.put("columns", tableColumns); VelocityContext velocityContext = new VelocityContext(map); //获取模板列表 List<String> templates = getTemplates(); for(String template:templates){ //渲染模板 StringWriter stringWriter = new StringWriter(); Template tpl = Velocity.getTemplate(template,"UTF-8"); tpl.merge(velocityContext,stringWriter); try { //添加到zip zip.putNextEntry(new ZipEntry(getFileName(template,tableInfo.getClassName(),generateConfigInfo.getPackageName()))); IOUtils.write(stringWriter.toString(),zip,"UTF-8"); IOUtils.closeQuietly(stringWriter); zip.closeEntry(); } catch (IOException e) { System.out.println("渲染模板失败,表名:["+tableInfo.getTableName()+"],异常信息为:"+e.getMessage()); } } }