Java Code Examples for org.apache.velocity.Template#merge()
The following examples show how to use
org.apache.velocity.Template#merge() .
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: TestUtils.java From knox with Apache License 2.0 | 6 votes |
public static String merge( String resource, Properties properties ) { ClasspathResourceLoader loader = new ClasspathResourceLoader(); loader.getResourceStream( resource ); VelocityEngine engine = new VelocityEngine(); Properties config = new Properties(); config.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.NullLogSystem" ); config.setProperty( RuntimeConstants.RESOURCE_LOADER, "classpath" ); config.setProperty( "classpath.resource.loader.class", ClasspathResourceLoader.class.getName() ); engine.init( config ); VelocityContext context = new VelocityContext( properties ); Template template = engine.getTemplate( resource ); StringWriter writer = new StringWriter(); template.merge( context, writer ); return writer.toString(); }
Example 2
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 3
Source File: VelocityTest.java From snake-yaml with Apache License 2.0 | 6 votes |
public void testTemplate1() throws Exception { VelocityContext context = new VelocityContext(); MyBean bean = createBean(); context.put("bean", bean); Yaml yaml = new Yaml(); context.put("list", yaml.dump(bean.getList())); VelocityEngine ve = new VelocityEngine(); ve.setProperty("file.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); Template t = ve.getTemplate("template/mybean1.vm"); StringWriter writer = new StringWriter(); t.merge(context, writer); String output = writer.toString().trim().replaceAll("\\r\\n", "\n"); // System.out.println(output); String etalon = Util.getLocalResource("template/etalon2-template.yaml").trim(); assertEquals(etalon.length(), output.length()); assertEquals(etalon, output); // parse the YAML document Yaml loader = new Yaml(); MyBean parsedBean = loader.loadAs(output, MyBean.class); assertEquals(bean, parsedBean); }
Example 4
Source File: VelocityEngine.java From velocity-engine with Apache License 2.0 | 6 votes |
/** * merges a template and puts the rendered stream into the writer * * @param templateName name of template to be used in merge * @param encoding encoding used in template * @param context filled context to be used in merge * @param writer writer to write template into * * @return true if successful, false otherwise. Errors * logged to velocity log * @throws ResourceNotFoundException * @throws ParseErrorException * @throws MethodInvocationException * @since Velocity v1.1 */ public boolean mergeTemplate( String templateName, String encoding, Context context, Writer writer ) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException { Template template = ri.getTemplate(templateName, encoding); if ( template == null ) { String msg = "VelocityEngine.mergeTemplate() was unable to load template '" + templateName + "'"; getLog().error(msg); throw new ResourceNotFoundException(msg); } else { template.merge(context, writer); return true; } }
Example 5
Source File: ParameterServletHandler.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()); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); Template template=ve.getTemplate("html/parameter-editor.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
Example 6
Source File: VelocityView.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Merge the template with the context. * Can be overridden to customize the behavior. * @param template the template to merge * @param context the Velocity context to use for rendering * @param response servlet response (use this to get the OutputStream or Writer) * @throws Exception if thrown by Velocity * @see org.apache.velocity.Template#merge */ protected void mergeTemplate( Template template, Context context, HttpServletResponse response) throws Exception { try { template.merge(context, response.getWriter()); } catch (MethodInvocationException ex) { Throwable cause = ex.getWrappedThrowable(); throw new NestedServletException( "Method invocation failed during rendering of Velocity view with name '" + getBeanName() + "': " + ex.getMessage() + "; reference [" + ex.getReferenceName() + "], method '" + ex.getMethodName() + "'", cause==null ? ex : cause); } }
Example 7
Source File: ScorecardEditorServletHandler.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/scorecard-editor.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
Example 8
Source File: FileGenerator.java From Asqatasun with GNU Affero General Public License v3.0 | 5 votes |
public void writeInstallGenerate(VelocityContext context, Template temp) throws IOException { StringWriter wr = new StringWriter(); temp.merge(context, wr); File installFile = new File(vpc.getDestinationFolder() + "/src/main/resources/" + "deploy.sh"); FileUtils.writeStringToFile(installFile, wr.toString()); }
Example 9
Source File: Generator.java From erp-framework with MIT License | 5 votes |
public void generateModel(String targetDir, Table table) { VelocityEngine velocityEngine = createVelocityEngine(); VelocityContext context = createContext(table); Writer writer = createWriter(targetDir, configure.getEntityPackage() .replace(".", "/") + "/" + table.getBeanName() + ".java"); Template t = velocityEngine.getTemplate("beanTemplate.vm"); t.merge(context, writer); flushWriter(writer); }
Example 10
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 11
Source File: VelocityUtils.java From JavaPackager with GNU General Public License v3.0 | 5 votes |
private static String render(String templatePath, Object info) throws MojoExecutionException { VelocityContext context = new VelocityContext(); context.put("features", new ArrayList<String>()); context.put("GUID", UUID.class); context.put("StringUtils", StringUtils.class); context.put("info", info); Template template = getVelocityEngine().getTemplate(templatePath, "UTF-8"); StringBuilderWriter writer = new StringBuilderWriter(); template.merge(context, writer); return writer.toString(); }
Example 12
Source File: ThrottlePolicyTemplateBuilder.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Generate policy for subscription level. * @param policy policy with level 'sub'. Multiple pipelines are not allowed. Can define more than one condition * as set of conditions. all these conditions should be passed as a single pipeline * @return * @throws APITemplateException */ public String getThrottlePolicyForSubscriptionLevel(SubscriptionPolicy policy) throws APITemplateException { StringWriter writer = new StringWriter(); if (log.isDebugEnabled()) { log.debug("Generating policy for subscriptionLevel :" + policy.toString()); } if (!(policy instanceof SubscriptionPolicy)) { throw new APITemplateException("Invalid policy level : Has to be 'sub'"); } try { VelocityEngine velocityengine = new VelocityEngine(); velocityengine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, CommonsLogLogChute.class.getName()); if (!"not-defined".equalsIgnoreCase(getVelocityLogger())) { velocityengine.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath"); velocityengine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); } velocityengine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome()); velocityengine.init(); Template t = velocityengine.getTemplate(getTemplatePathForSubscription()); VelocityContext context = new VelocityContext(); setConstantContext(context); context.put("policy", policy); context.put("quotaPolicy", policy.getDefaultQuotaPolicy()); t.merge(context, writer); if (log.isDebugEnabled()) { log.debug("Policy : " + writer.toString()); } } catch (Exception e) { log.error("Velocity Error", e); throw new APITemplateException("Velocity Error", e); } return writer.toString(); }
Example 13
Source File: AbstractGenerator.java From sc-generator with Apache License 2.0 | 5 votes |
protected void writeApplicationConfig(String srcApplication, String destApplication, String project, String packagePath) throws IOException { Template tempate = VelocityUtil.getTempate(srcApplication); VelocityContext ctx = new VelocityContext(); ctx.put("project", project); ctx.put("driverClass", driverClass); ctx.put("username", username); ctx.put("password", password); ctx.put("packagePath", packagePath); ctx.put("url", url); StringWriter writer = new StringWriter(); tempate.merge(ctx, writer); writer.close(); write(writer.toString(), destApplication); }
Example 14
Source File: GenServiceImpl.java From ruoyiplus with MIT License | 5 votes |
/** * 生成代码 */ private void generatorCode(TableInfo table, ZipOutputStream zip) { // 设置主键 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, Constants.UTF8); tpl.merge(context, sw); try { // 添加到zip zip.putNextEntry(new ZipEntry(GenUtils.getFileName(template, table, moduleName))); IOUtils.write(sw.toString(), zip, Constants.UTF8); IOUtils.closeQuietly(sw); zip.closeEntry(); } catch (IOException e) { log.error("渲染模板失败,表名:" + table.getTableName(), e); } } }
Example 15
Source File: Velocity537TestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
protected Template executeTest(final String templateName) throws Exception { Template template = velocityEngine.getTemplate(templateName); FileOutputStream fos = new FileOutputStream(getFileName(RESULTS_DIR, templateName, RESULT_FILE_EXT)); Writer writer = new BufferedWriter(new OutputStreamWriter(fos)); VelocityContext context = new VelocityContext(); template.merge(context, writer); writer.flush(); writer.close(); if (!isMatch(RESULTS_DIR, COMPARE_DIR, templateName, RESULT_FILE_EXT, CMP_FILE_EXT)) { // just to be useful, output the output in the fail message StringWriter out = new StringWriter(); template.merge(context, out); String compare = getFileContents(COMPARE_DIR, templateName, CMP_FILE_EXT); fail("Output incorrect for Template: " + templateName + ": \""+out+"\""+ "; it did not match: \""+compare+"\""); } return template; }
Example 16
Source File: StringResourceLoaderRepositoryTestCase.java From velocity-engine with Apache License 2.0 | 4 votes |
protected String render(Template template) throws Exception { StringWriter out = new StringWriter(); template.merge(this.context, out); return out.toString(); }
Example 17
Source File: GeneratorUtils.java From springboot-admin with Apache License 2.0 | 4 votes |
/** * 生成代码 */ public static void generatorCode(Map<String, String> table, List<Map<String, String>> columns, ZipOutputStream zip){ //配置信息 Configuration config = getConfig(); //表信息 SysTable sysTable = new SysTable(); sysTable.setTableName(table.get("tableName")); sysTable.setComments(table.get("tableComment")); //表名转换成Java类名 String className = tableToJava(sysTable.getTableName(), config.getString("tablePrefix")); sysTable.setClassName(className); sysTable.setClassname(StringUtils.uncapitalize(className)); //列信息 List<SysColumn> columsList = new ArrayList<>(); for(Map<String, String> column : columns){ SysColumn sysColumn = new SysColumn(); sysColumn.setColumnName(column.get("columnName")); sysColumn.setDataType(column.get("dataType")); sysColumn.setComments(column.get("columnComment")); sysColumn.setExtra(column.get("extra")); //列名转换成Java属性名 String attrName = columnToJava(sysColumn.getColumnName()); sysColumn.setAttrName(attrName); sysColumn.setAttrname(StringUtils.uncapitalize(attrName)); //列的数据类型,转换成Java类型 String attrType = config.getString(sysColumn.getDataType(), "unknowType"); sysColumn.setAttrType(attrType); //是否主键 if("PRI".equalsIgnoreCase(column.get("columnKey")) && sysTable.getPk() == null){ sysTable.setPk(sysColumn); } columsList.add(sysColumn); } sysTable.setColumns(columsList); //没主键,则第一个字段为主键 if(sysTable.getPk() == null){ sysTable.setPk(sysTable.getColumns().get(0)); } //设置velocity资源加载器 Properties prop = new Properties(); prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocity.init(prop); String entityPrefix=config.getString("entityPrefix"); String classNameTemp=entityPrefix+sysTable.getClassName(); String classnameTmep=sysTable.getClassname(); String pathPrefix=config.getString("pathPrefix"); //封装模板数据 Map<String, Object> map = new HashMap<>(); map.put("tableName", sysTable.getTableName()); map.put("comments", sysTable.getComments()); map.put("pk", sysTable.getPk()); map.put("className", classNameTemp); map.put("classname", classnameTmep); map.put("pathPrefix", pathPrefix); map.put("pathName", "/"+ sysTable.getClassname().toLowerCase()); map.put("columns", sysTable.getColumns()); map.put("package", config.getString("package")); map.put("author", config.getString("author")); map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN)); VelocityContext context = new VelocityContext(map); //获取模板列表 List<String> templates = getTemplates(); for(String template : templates){ //渲染模板 StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(template, "UTF-8"); tpl.merge(context, sw); try { //添加到zip zip.putNextEntry(new ZipEntry(getFileName(template, classNameTemp, classnameTmep, config.getString("package")))); IOUtils.write(sw.toString(), zip, "UTF-8"); IOUtils.closeQuietly(sw); zip.closeEntry(); } catch (IOException e) { throw new AppException("渲染模板失败,表名:" + sysTable.getTableName(), e); } } }
Example 18
Source File: VMLibraryTestCase.java From velocity-engine with Apache License 2.0 | 4 votes |
/** * Runs the tests with local namespace. */ public void testVelociMacroLibWithLocalNamespace() throws Exception { assureResultsDirectoryExists(RESULT_DIR); /** * Clear the file before proceeding */ File file = new File(getFileName( RESULT_DIR, "vm_library_local", RESULT_FILE_EXT)); if (file.exists()) { file.delete(); } /** * Create a file output stream for appending */ FileOutputStream fos = new FileOutputStream (getFileName( RESULT_DIR, "vm_library_local", RESULT_FILE_EXT), true); List templateList = new ArrayList(); VelocityContext context = new VelocityContext(); Writer writer = new BufferedWriter(new OutputStreamWriter(fos)); templateList.add("vm_library1.vm"); Template template = ve1.getTemplate("vm_library_local.vm"); template.merge(context, writer, templateList); /** * remove the first template library and includes a new library * with a new definition for macros */ templateList.remove(0); templateList.add("vm_library2.vm"); template = ve1.getTemplate("vm_library_local.vm"); template.merge(context, writer, templateList); /* *Show that caching is working */ Template t1 = ve1.getTemplate("vm_library_local.vm"); Template t2 = ve1.getTemplate("vm_library_local.vm"); assertEquals("Both templates refer to the same object", t1, t2); /** * Remove the libraries */ template = ve1.getTemplate("vm_library_local.vm"); template.merge(context, writer); /** * Write to the file */ writer.flush(); writer.close(); if (!isMatch(RESULT_DIR, COMPARE_DIR, "vm_library_local", RESULT_FILE_EXT,CMP_FILE_EXT)) { fail("Processed template did not match expected output"); } }
Example 19
Source File: ParseWithMacroLibsTestCase.java From velocity-engine with Apache License 2.0 | 4 votes |
/** * Test that if a macro is duplicated, the second one takes precendence * * @throws Exception */ public void testDuplicateDefinitions() throws Exception { /* * ve1: local scope, cache on */ VelocityEngine ve1 = new VelocityEngine(); ve1.setProperty( Velocity.VM_PERM_INLINE_LOCAL, Boolean.TRUE); ve1.setProperty("velocimacro.permissions.allow.inline.to.replace.global", Boolean.FALSE); ve1.setProperty("file.resource.loader.cache", Boolean.TRUE); ve1.setProperty( Velocity.RUNTIME_LOG_INSTANCE, new TestLogger()); ve1.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file"); ve1.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TEST_COMPARE_DIR + "/parsemacros"); ve1.init(); assureResultsDirectoryExists(RESULT_DIR); FileOutputStream fos = new FileOutputStream (getFileName( RESULT_DIR, "parseMacro3", RESULT_FILE_EXT)); VelocityContext context = new VelocityContext(); Writer writer = new BufferedWriter(new OutputStreamWriter(fos)); Template template = ve1.getTemplate("parseMacro3.vm"); template.merge(context, writer); /** * Write to the file */ writer.flush(); writer.close(); if (!isMatch(RESULT_DIR, COMPARE_DIR, "parseMacro3", RESULT_FILE_EXT,CMP_FILE_EXT)) { fail("Processed template did not match expected output"); } }
Example 20
Source File: GeneratorUtils.java From hdw-dubbo with Apache License 2.0 | 4 votes |
/** * 生成代码 */ public static void generatorCode(Map<String, String> table, List<Map<String, String>> columns, ZipOutputStream zip) { //配置信息 Configuration config = getConfig(); boolean hasBigDecimal = false; //表信息 TableEntity tableEntity = new TableEntity(); tableEntity.setTableName(table.get("tableName" )); tableEntity.setComments(table.get("tableComment" )); //表名转换成Java类名 String className = tableToJava(tableEntity.getTableName(), config.getString("tablePrefix" )); tableEntity.setClassName(className); tableEntity.setClassname(StringUtils.uncapitalize(className)); //列信息 List<ColumnEntity> columsList = new ArrayList<>(); for(Map<String, String> column : columns){ ColumnEntity columnEntity = new ColumnEntity(); columnEntity.setColumnName(column.get("columnName" )); columnEntity.setDataType(column.get("dataType" )); columnEntity.setComments(column.get("columnComment" )); columnEntity.setExtra(column.get("extra" )); //列名转换成Java属性名 String attrName = columnToJava(columnEntity.getColumnName()); columnEntity.setAttrName(attrName); columnEntity.setAttrname(StringUtils.uncapitalize(attrName)); //列的数据类型,转换成Java类型 String attrType = config.getString(columnEntity.getDataType(), "unknowType" ); columnEntity.setAttrType(attrType); if (!hasBigDecimal && attrType.equals("BigDecimal" )) { hasBigDecimal = true; } //是否主键 if ("PRI".equalsIgnoreCase(column.get("columnKey" )) && tableEntity.getPk() == null) { tableEntity.setPk(columnEntity); } columsList.add(columnEntity); } tableEntity.setColumns(columsList); //没主键,则第一个字段为主键 if (tableEntity.getPk() == null) { tableEntity.setPk(tableEntity.getColumns().get(0)); } //设置velocity资源加载器 Properties prop = new Properties(); prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader" ); Velocity.init(prop); String mainPath = config.getString("mainPath" ); mainPath = StringUtils.isBlank(mainPath) ? "io.renren" : mainPath; //封装模板数据 Map<String, Object> map = new HashMap<>(); map.put("tableName", tableEntity.getTableName()); map.put("comments", tableEntity.getComments()); map.put("pk", tableEntity.getPk()); map.put("className", tableEntity.getClassName()); map.put("classname", tableEntity.getClassname()); map.put("pathName", tableEntity.getClassname()); map.put("columns", tableEntity.getColumns()); map.put("hasBigDecimal", hasBigDecimal); map.put("mainPath", mainPath); map.put("package", config.getString("package" )); map.put("moduleName", config.getString("moduleName" )); map.put("author", config.getString("author" )); map.put("email", config.getString("email" )); map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN)); VelocityContext context = new VelocityContext(map); //获取模板列表 List<String> templates = getTemplates(); for (String template : templates) { //渲染模板 StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(template, "UTF-8" ); tpl.merge(context, sw); try { //添加到zip zip.putNextEntry(new ZipEntry(getFileName(template, tableEntity.getClassName(), config.getString("package" ), config.getString("moduleName" )))); IOUtils.write(sw.toString(), zip, "UTF-8" ); IOUtils.closeQuietly(sw); zip.closeEntry(); } catch (IOException e) { throw new BaseException("渲染模板失败,表名:" + tableEntity.getTableName(), e); } } }