org.apache.velocity.Template Java Examples
The following examples show how to use
org.apache.velocity.Template.
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: MailUtil.java From springboot-learn with MIT License | 6 votes |
/** * 获取velocity邮件模板内容 * * @param map 模板中需替换的参数内容 * @return */ public static String getTemplateText(String templatePath, String charset, Map<String, Object> map) { String templateText; // 设置velocity资源加载器 Properties prop = new Properties(); prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocity.init(prop); VelocityContext context = new VelocityContext(map); // 渲染模板 StringWriter sw = new StringWriter(); Template template = Velocity.getTemplate(templatePath, charset); template.merge(context, sw); try { templateText = sw.toString(); sw.close(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("模板渲染失败"); } return templateText; }
Example #2
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 #3
Source File: VelocityTemplate.java From XBatis-Code-Generator with Apache License 2.0 | 6 votes |
/** * 根据模版和参数生成指定的文件 * @param template * @param outfileName * @param context * @throws Exception */ private static void mergeTemplate(Template template, String outfileName, VelocityContext context) throws Exception { /* * Now have the template engine process your template using the data * placed into the context. Think of it as a 'merge' of the template and * the data to produce the output stream. */ BufferedWriter writer = new BufferedWriter(new FileWriter(outfileName)); if (template != null) template.merge(context, writer); /* * flush and cleanup */ writer.flush(); writer.close(); }
Example #4
Source File: GenTableServiceImpl.java From supplierShop with MIT License | 6 votes |
/** * 预览代码 * * @param tableId 表编号 * @return 预览数据列表 */ 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 #5
Source File: AbstractGenerator.java From sc-generator with Apache License 2.0 | 6 votes |
protected void writePom(String srcPom, String destPom, String project, String packagePath) throws IOException { Template tempate = VelocityUtil.getTempate(srcPom); VelocityContext ctx = new VelocityContext(); ctx.put("packagePath", packagePath); ctx.put("project", project); ctx.put("application", packagePath + "." + this.applicationName); ctx.put("driverClass", driverClass); ctx.put("serviceProject", serviceProject); ctx.put("serviceApiProject", serviceApiProject); ctx.put("parentProject", parentProject); ctx.put("springCloudVersion", springCloudVersion); ctx.put("springBootVersion", springBootVersion); for (Map.Entry<String, Object> entry : options.entrySet()) { ctx.put(entry.getKey(), entry.getValue()); } StringWriter writer = new StringWriter(); tempate.merge(ctx, writer); writer.close(); write(writer.toString(), destPom); }
Example #6
Source File: Test3.java From java-course-ee with MIT License | 6 votes |
public Test3() throws Exception { //init Velocity.init("Velocity/GS_Velocity_1/src/main/java/velocity.properties"); // get Template Template template = Velocity.getTemplate("Test3.vm"); // getContext Context context = new VelocityContext(); String name = "Vova"; int age = 21; boolean flag = true; context.put("name", name); context.put("age", age); context.put("flag", flag); context.put("today", new Date()); context.put("product", new Product("Book", 12.3)); // get Writer Writer writer = new StringWriter(); // merge template.merge(context, writer); System.out.println(writer.toString()); }
Example #7
Source File: VelocityViewTag.java From velocity-tools with Apache License 2.0 | 6 votes |
protected void renderContent(Writer out) throws Exception { if (getTemplate() != null) { VelocityView view = getVelocityView(); ViewToolContext context = getViewToolContext(); // get the actual Template Template template = view.getTemplate(getTemplate()); if (getBodyContent() != null) { context.put(getBodyContentKey(), getRenderedBody()); } // render the template into the writer template.merge(context, out); } else { // render the body into the writer renderBody(out); } }
Example #8
Source File: CustomParserTestCase.java From velocity-engine with Apache License 2.0 | 6 votes |
@Test public void testMarkdownTemplate() throws Exception { VelocityContext ctx = new VelocityContext(); ctx.put("some", "value"); Template tmpl = engine.getTemplate("test.md", "UTF-8"); String resultFile = RESULTS_DIR + File.separator + "test.md"; String referenceFile = REFERENCE_DIR + File.separator + "test.md"; new File(resultFile).getParentFile().mkdirs(); FileWriter writer = new FileWriter(resultFile); tmpl.merge(ctx, writer); writer.flush(); writer.close(); String result = IOUtils.toString(new FileInputStream(resultFile), "UTF-8"); String reference = IOUtils.toString(new FileInputStream(referenceFile), "UTF-8"); assertEquals(reference, result); }
Example #9
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 #10
Source File: SubstituteSwaggerGenerator.java From api-layer with Eclipse Public License 2.0 | 6 votes |
public String generateSubstituteSwaggerForService(InstanceInfo service, ApiInfo api, String gatewayScheme, String gatewayHost) { String title = service.getMetadata().get(SERVICE_TITLE); String description = service.getMetadata().get(SERVICE_DESCRIPTION); String basePath = (api.getGatewayUrl().startsWith("/") ? "" : "/") + api.getGatewayUrl() + (api.getGatewayUrl().endsWith("/") ? "" : "/") + service.getAppName().toLowerCase(); Template t = ve.getTemplate("substitute_swagger.json"); VelocityContext context = new VelocityContext(); context.put("title", title); context.put("description", description); context.put("version", api.getVersion()); context.put("scheme", gatewayScheme); context.put("host", gatewayHost); context.put("basePath", basePath); context.put("documentationUrl", api.getDocumentationUrl()); StringWriter w = new StringWriter(); t.merge(context, w); return w.toString(); }
Example #11
Source File: ScenarioExecutor.java From testgrid with Apache License 2.0 | 6 votes |
/** * This method prepares the content of the run-scenario script which will include complete shell commands including * script file names. * @param files sorted list of files needs to be added to the script * @return content of the run-scenario.sh script */ private String prepareScriptContent(List<String> files) { VelocityEngine velocityEngine = new VelocityEngine(); //Set velocity class loader as to refer templates from resources directory. velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); velocityEngine.init(); VelocityContext context = new VelocityContext(); context.put("scripts", files); Template template = velocityEngine.getTemplate(RUN_SCENARIO_SCRIPT_TEMPLATE); StringWriter writer = new StringWriter(); template.merge(context, writer); return writer.toString(); }
Example #12
Source File: ScriptDecisiontableEditorServletHandler.java From urule with Apache License 2.0 | 6 votes |
@Override public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method=retriveMethod(req); if(method!=null){ invokeMethod(method, req, resp); }else{ VelocityContext context = new VelocityContext(); context.put("contextPath", req.getContextPath()); String file=req.getParameter("file"); String project = buildProjectNameFromFile(file); if(project!=null){ context.put("project", project); } resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); Template template=ve.getTemplate("html/scriptdecisiontable-editor.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
Example #13
Source File: PermissionConfigServletHandler.java From urule with Apache License 2.0 | 6 votes |
@Override public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if(!((PermissionService)permissionStore).isAdmin()){ throw new NoPermissionException(); } String method=retriveMethod(req); if(method!=null){ invokeMethod(method, req, resp); }else{ VelocityContext context = new VelocityContext(); context.put("contextPath", req.getContextPath()); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); Template template=ve.getTemplate("html/permission-config-editor.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
Example #14
Source File: RuleFlowDesignerServletHandler.java From urule with Apache License 2.0 | 6 votes |
@Override public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method=retriveMethod(req); if(method!=null){ invokeMethod(method, req, resp); }else{ VelocityContext context = new VelocityContext(); context.put("contextPath", req.getContextPath()); String file=req.getParameter("file"); String project = buildProjectNameFromFile(file); if(project!=null){ context.put("project", project); } resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); Template template=ve.getTemplate("html/rule-flow-designer.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
Example #15
Source File: VelocityHelloWorld.java From java-tutorial with Creative Commons Attribution Share Alike 4.0 International | 6 votes |
public static void main(String args[]) { /* 1.初始化 Velocity */ VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.setProperty(VelocityEngine.RESOURCE_LOADER, "file"); velocityEngine.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "D:/01_Workspace/Project/zp/javaparty/src/toolbox/template/src/main/resources"); velocityEngine.init(); /* 2.创建一个上下文对象 */ VelocityContext context = new VelocityContext(); /* 3.添加你的数据对象到上下文 */ context.put("name", "Victor Zhang"); context.put("project", "Velocity"); /* 4.选择一个模板 */ Template template = velocityEngine.getTemplate("template/hello.vm"); /* 5.将你的数据与模板合并,产生输出内容 */ StringWriter sw = new StringWriter(); template.merge(context, sw); System.out.println("final output:\n" + sw); }
Example #16
Source File: MacroForwardDefineTestCase.java From velocity-engine with Apache License 2.0 | 6 votes |
public void testLogResult() throws Exception { VelocityContext context = new VelocityContext(); Template template = Velocity.getTemplate("macros.vm"); // try to get only messages during merge logger.startCapture(); template.merge(context, new StringWriter()); logger.stopCapture(); String resultLog = logger.getLog(); if ( !isMatch(resultLog, COMPARE_DIR, "velocity.log", "cmp")) { String compare = getFileContents(COMPARE_DIR, "velocity.log", CMP_FILE_EXT); String msg = "Log output was incorrect\n"+ "-----Result-----\n"+ resultLog + "----Expected----\n"+ compare + "----------------"; fail(msg); } }
Example #17
Source File: OTPService.java From sunbird-lms-service with MIT License | 6 votes |
public static String getSmsBody(String templateFile, Map<String, String> smsTemplate) { try { String sms = getOTPSMSTemplate(templateFile); RuntimeServices rs = RuntimeSingleton.getRuntimeServices(); SimpleNode sn = rs.parse(sms, "Sms Information"); Template t = new Template(); t.setRuntimeServices(rs); t.setData(sn); t.initDocument(); VelocityContext context = new VelocityContext(); context.put(JsonKey.OTP, smsTemplate.get(JsonKey.OTP)); context.put( JsonKey.OTP_EXPIRATION_IN_MINUTES, smsTemplate.get(JsonKey.OTP_EXPIRATION_IN_MINUTES)); context.put( JsonKey.INSTALLATION_NAME, ProjectUtil.getConfigValue(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME)); StringWriter writer = new StringWriter(); t.merge(context, writer); return writer.toString(); } catch (Exception ex) { ProjectLogger.log( "OTPService:getSmsBody: Exception occurred with error message = " + ex.getMessage(), ex); } return ""; }
Example #18
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 #19
Source File: AbstractGenerator.java From sc-generator with Apache License 2.0 | 6 votes |
protected void writeBin(String destDir, String project, String packagePath) throws IOException { String binPath = getBinPath(); List<String> files = getBinFiles(); for (String fileName : files) { String file = binPath + fileName; Template template = VelocityUtil.getTempate(file); VelocityContext ctx = new VelocityContext(); ctx.put("packagePath", packagePath); ctx.put("project", project); if (file.contains("shutdown")) { ctx.put("application", this.applicationName); } else { ctx.put("application", packagePath + "." + this.applicationName); } StringWriter writer = new StringWriter(); template.merge(ctx, writer); writer.close(); write(writer.toString(), destDir + fileName); } }
Example #20
Source File: VelocitySqlSource.java From mybatis with Apache License 2.0 | 5 votes |
public VelocitySqlSource(Configuration configuration, String scriptText) { this.configuration = configuration; try { RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices(); StringReader reader = new StringReader(scriptText); SimpleNode node = runtimeServices.parse(reader, "Template name"); script = new Template(); script.setRuntimeServices(runtimeServices); script.setData(node); script.initDocument(); } catch (Exception ex) { throw new BuilderException("Error parsing velocity script", ex); } }
Example #21
Source File: SpringBootThymeleafNoBaseGeneratorMybatis.java From sc-generator with Apache License 2.0 | 5 votes |
@Override protected void writeUIOther(String destResourcePath, List<String> tables, List<String> modelNames,List<String> varModelNames) throws IOException { Template indexHtml = VelocityUtil.getTempate("/templates/pom/ui/thymeleaf/index.vm"); Template indexJs = VelocityUtil.getTempate("/templates/pom/ui/thymeleaf/indexjs.vm"); Template commonJs = VelocityUtil.getTempate("/templates/pom/ui/thymeleaf/common.vm"); VelocityContext ctx= new VelocityContext(); ctx.put("modelNames",modelNames); ctx.put("tables",tables); ctx.put("varModelNames",varModelNames); ctx.put("project", VelocityUtil.tableNameConvertModelName(this.project.split("-")[0])); ctx.put("miniProject", VelocityUtil.tableNameConvertModelName(this.project.split("-")[0]).substring(0, 1)); write(merge(indexHtml,ctx),destResourcePath+"/static/index.html"); write(merge(indexJs,ctx),destResourcePath+"/static/js/index.js"); write(merge(commonJs,ctx),destResourcePath+"/static/js/common.js"); }
Example #22
Source File: AbstractGenerator.java From sc-generator with Apache License 2.0 | 5 votes |
protected void writeDockerfile(String srcDockerfile, String destDockerfile, String project, String packagePath) throws IOException { Template tempate = VelocityUtil.getTempate(srcDockerfile); VelocityContext ctx = new VelocityContext(); ctx.put("package", packagePath); ctx.put("project", project); ctx.put("username", this.username); ctx.put("password", this.password); String host = url.substring(0, url.lastIndexOf("/")).substring(url.substring(0, url.lastIndexOf("/")).lastIndexOf("/") + 1); int port = 3306; String database = project; try { database = url.substring(url.lastIndexOf("/") + 1); if (host.contains(":")) { String[] split = host.split(":"); port = Integer.parseInt(split[1]); } } catch (Exception e) { } ctx.put("port",port); ctx.put("database",database); ctx.put("application", packagePath + "." + this.applicationName); StringWriter writer = new StringWriter(); tempate.merge(ctx, writer); writer.close(); write(writer.toString(), destDockerfile); }
Example #23
Source File: VelocityUtil.java From sc-generator with Apache License 2.0 | 5 votes |
public static String writerGeneratorConfig(String url, String username, String password, String driverClass, String packagePath, String targetPath, List<String> tables) throws IOException, SQLException { VelocityContext ctx = new VelocityContext(); Template template = getTempate("templates/generatorConfig.vm"); ctx.put("url", url); ctx.put("username", username); ctx.put("password", password); ctx.put("driverClass", driverClass); ctx.put("tables", tables); Map<String, String> primaryKeys = new HashMap<>(); Connection connection = DriverManager.getConnection(url, username, password); for (String tableName : tables) { String primaryKey = TblUtil.getPrimaryKey(connection, tableName); String key = toHump(primaryKey); primaryKeys.put(tableName, key); } ctx.put("primaryKeys", primaryKeys); List<String> models = new ArrayList<String>(); for (String table : tables) { String modelName = tableNameConvertModelName(table); models.add(modelName); } ctx.put("models", models); ctx.put("packagePath", packagePath); ctx.put("targetPath", targetPath); StringWriter writer = new StringWriter(); template.merge(ctx, writer); writer.flush(); writer.close(); return writer.toString(); }
Example #24
Source File: FileGenerator.java From Asqatasun with GNU Affero General Public License v3.0 | 5 votes |
public void writeAuditResultConsoleBeanGenerate(VelocityContext context, Template temp) throws IOException { StringWriter wr = new StringWriter(); context.put("themes", vpc.getThemes()); temp.merge(context, wr); File beansAuditResultConsoleFile = new File(vpc.getDestinationFolder() + "/src/main/resources/conf/context/" + vpc.getReferential().replace(".", "").toLowerCase() + "/web-app/mvc/form/" + "tgol-beans-" + vpc.getReferential().replace(".", "").toLowerCase() + "-audit-result-console-form.xml"); FileUtils.writeStringToFile(beansAuditResultConsoleFile, wr.toString()); }
Example #25
Source File: VelocityTemplateTest.java From eagle with Apache License 2.0 | 5 votes |
@Test public void testVelocityTemplate() { String templateString = "This alert ($category) was generated because $reason and $REASON from $source at $created_time"; String resultString = "This alert ($category) was generated because timeout and IO error from localhost at 2016-11-30 05:52:47,053"; VelocityEngine engine = new VelocityEngine(); engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute"); engine.setProperty("runtime.log.logsystem.log4j.logger", LOG.getName()); engine.setProperty(Velocity.RESOURCE_LOADER, "string"); engine.addProperty("string.resource.loader.class", StringResourceLoader.class.getName()); engine.addProperty("string.resource.loader.repository.static", "false"); // engine.addProperty("runtime.references.strict", "true"); engine.init(); StringResourceRepository repo = (StringResourceRepository) engine.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT); repo.putStringResource("alert_template", ""); repo.putStringResource("alert_template", templateString); Assert.assertEquals(templateString, repo.getStringResource("alert_template").getBody()); VelocityContext context = new VelocityContext(); context.put("reason", "timeout"); context.put("REASON", "IO error"); context.put("source","localhost"); context.put("created_time", "2016-11-30 05:52:47,053"); Template velocityTemplate = engine.getTemplate("alert_template"); ASTprocess data = (ASTprocess) velocityTemplate.getData(); ReferenceContext referenceContext = new ReferenceContext(); data.jjtAccept(referenceContext,null); Assert.assertEquals(5, referenceContext.getReferences().size()); StringWriter writer = new StringWriter(); velocityTemplate.merge(context, writer); velocityTemplate.process(); Assert.assertEquals(resultString, writer.toString()); }
Example #26
Source File: SpringBootThymeleafBaseGeneratorMybatis.java From sc-generator with Apache License 2.0 | 5 votes |
@Override protected void writeUIOther(String destResourcePath, List<String> tables, List<String> modelNames,List<String> varModelNames) throws IOException { Template indexHtml = VelocityUtil.getTempate("/templates/pom/ui/thymeleaf/index.vm"); Template indexJs = VelocityUtil.getTempate("/templates/pom/ui/thymeleaf/indexjs.vm"); Template commonJs = VelocityUtil.getTempate("/templates/pom/ui/thymeleaf/common.vm"); VelocityContext ctx= new VelocityContext(); ctx.put("modelNames",modelNames); ctx.put("tables",tables); ctx.put("varModelNames",varModelNames); ctx.put("project", VelocityUtil.tableNameConvertModelName(this.project.split("-")[0])); ctx.put("miniProject", VelocityUtil.tableNameConvertModelName(this.project.split("-")[0]).substring(0, 1)); write(merge(indexHtml,ctx),destResourcePath+"/static/index.html"); write(merge(indexJs,ctx),destResourcePath+"/static/js/index.js"); write(merge(commonJs,ctx),destResourcePath+"/static/js/common.js"); }
Example #27
Source File: SpaceGobblingTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
private void testTemplate(VelocityEngine engine, String templateFile, SpaceGobbling mode) throws Exception { assureResultsDirectoryExists(RESULT_DIR); FileOutputStream fos = new FileOutputStream (getFileName(RESULT_DIR, templateFile, mode.toString())); VelocityContext context = new VelocityContext(); Writer writer = new BufferedWriter(new OutputStreamWriter(fos)); Template template = engine.getTemplate(templateFile); template.merge(context, writer); /** * Write to the file */ writer.flush(); writer.close(); if (!isMatch(RESULT_DIR, COMPARE_DIR, templateFile, mode.toString(), mode.toString())) { String result = getFileContents(RESULT_DIR, templateFile, mode.toString()); String compare = getFileContents(COMPARE_DIR, templateFile, mode.toString()); String msg = "Processed template did not match expected output for template " + templateFile + " and mode " + mode + "\n"+ "-----Result-----\n"+ result + "----Expected----\n"+ compare + "----------------"; fail(msg); } }
Example #28
Source File: DBContextTest.java From velocity-engine with Apache License 2.0 | 5 votes |
public DBContextTest(String templateFile) { try { RuntimeSingleton.init( new Properties() ); Template template = RuntimeSingleton.getTemplate(templateFile); DBContext dbc = new DBContext(); Hashtable h = new Hashtable(); h.put("Bar", "this is from a hashtable!"); dbc.put( "string", "Hello!"); dbc.put( "hashtable", h ); Writer writer = new BufferedWriter(new OutputStreamWriter(System.out)); template.merge(dbc, writer); writer.flush(); writer.close(); } catch( Exception e ) { RuntimeSingleton.getLog().error("Something funny happened", e); } }
Example #29
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 #30
Source File: VelocityView.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Retrieve the Velocity template to be rendered by this view. * <p>By default, the template specified by the "url" bean property will be * retrieved: either returning a cached template instance or loading a fresh * instance (according to the "cacheTemplate" bean property) * @return the Velocity template to render * @throws Exception if thrown by Velocity * @see #setUrl * @see #setCacheTemplate * @see #getTemplate(String) */ protected Template getTemplate() throws Exception { // We already hold a reference to the template, but we might want to load it // if not caching. Velocity itself caches templates, so our ability to // cache templates in this class is a minor optimization only. if (isCacheTemplate() && this.template != null) { return this.template; } else { return getTemplate(getUrl()); } }