public void usage1(String inputFile) throws FileNotFoundException { Velocity.init(); VelocityContext context = new VelocityContext(); context.put("author", "Elliot A."); context.put("address", "217 E Broadway"); context.put("phone", "555-1337"); FileInputStream file = new FileInputStream(inputFile); //Evaluate StringWriter swOut = new StringWriter(); Velocity.evaluate(context, swOut, "test", file); String result = swOut.getBuffer().toString(); System.out.println(result); }
@Inject public VelocityDefaultConfigurationFactory(@Optional final ServletContext servletContext) { String loader = "class"; Velocity.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName()); Velocity.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true"); if (servletContext != null) { Velocity.setProperty("webapp.resource.loader.class", WebappResourceLoader.class.getName()); Velocity.setProperty("webapp.resource.loader.path", "/"); Velocity.setApplicationAttribute("javax.servlet.ServletContext", servletContext); loader += ",webapp"; } Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, loader); configuration = new Configuration(); }
/** * 根据模板生成文件 * @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; } }
@Override public String createTable(Grammar grammar) { Velocity.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8"); Velocity.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8"); Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); Velocity.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("grammar", grammar); context.put("nonterminalSymbols", grammar.getLhsSymbols()); Template template = Velocity.getTemplate("/grammartools/PredictiveParsingTable.velo"); StringWriter stringWriter = new StringWriter(); template.merge(context, stringWriter); return stringWriter.toString().replaceAll("\n", ""); }
public void outputCode(String codePath, String templatePath) throws IOException { VelocityContext context = new VelocityContext(); context.put("cModule", cModule); Template template = null; try { template = Velocity.getTemplate(templatePath, TEMPLATE_ENCODING); } catch (ResourceNotFoundException e) { throw e; } File file = new File(codePath); logger.info("Generating {} ({})", file.getName(), templatePath); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), OUTPUT_ENCODING))); template.merge(context, pw); pw.close(); }
/** * Gets the template by viewname, the viewname is relative path * * @param viewname * the relative view path name * @param allowEmpty * if not presented, allow using a empty * @return Template * @throws IOException */ private Template getTemplate(File f) throws IOException { String fullname = f.getCanonicalPath(); T t = cache.get(fullname); if (t == null || t.last != f.lastModified()) { /** * get the template from the top */ Template t1 = Velocity.getTemplate(fullname, "UTF-8"); t = T.create(t1, f.lastModified()); cache.put(fullname, t); } return t == null ? null : t.template; }
private void showTasks(HttpServletRequest request, HttpServletResponse response, Collection<TaskRecord> tasks, String title, boolean showDbStats) throws IOException { if ("json".equals(request.getParameter("format"))) { response.setContentType("text/plain"); } else { response.setContentType("text/html"); } int offset = getOffset(request); int length = getLength(request); // Create Velocity context VelocityContext context = new VelocityContext(); context.put("tasks", tasks); context.put("title", title); context.put("reportStore", metadata); context.put("request", request); context.put("offset", offset); context.put("length", length); context.put("lastResultNum", offset + length - 1); context.put("prevOffset", Math.max(0, offset - length)); context.put("nextOffset", offset + length); context.put("showStats", showDbStats); context.put("JSON_DATE_FORMAT", JSON_DATE_FORMAT); context.put("HTML_DATE_FORMAT", HTML_DATE_FORMAT); context.put("PAGE_LENGTH", PAGE_LENGTH); // Return Velocity results try { Velocity.mergeTemplate("tasks.vm", "UTF-8", context, response.getWriter()); response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { LOG.warn("Failed to display tasks.vm", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to display tasks.vm"); } }
@Inject public VelocityViewProcessor(final javax.ws.rs.core.Configuration config, final ServiceLocator serviceLocator, @Optional final ServletContext servletContext) { super(config, servletContext, "velocity", "vm"); this.factory = getTemplateObjectFactory(serviceLocator, VelocityConfigurationFactory.class, new Value<VelocityConfigurationFactory>() { @Override public VelocityConfigurationFactory get() { Configuration configuration = getTemplateObjectFactory(serviceLocator, Configuration.class, Values.<Configuration>empty()); if (configuration == null) { return new VelocityDefaultConfigurationFactory(servletContext); } else { return new VelocitySuppliedConfigurationFactory(configuration); } } }); Velocity.init(); }
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); }
@Override protected void __doViewInit(IWebMvc owner) { super.__doViewInit(owner); // 初始化Velocity模板引擎配置 if (!__inited) { __velocityConfig.setProperty(Velocity.ENCODING_DEFAULT, owner.getModuleCfg().getDefaultCharsetEncoding()); __velocityConfig.setProperty(Velocity.INPUT_ENCODING, owner.getModuleCfg().getDefaultCharsetEncoding()); __velocityConfig.setProperty(Velocity.OUTPUT_ENCODING, owner.getModuleCfg().getDefaultCharsetEncoding()); // if (__baseViewPath.startsWith("/WEB-INF")) { __velocityConfig.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, new File(RuntimeUtils.getRootPath(), StringUtils.substringAfter(__baseViewPath, "/WEB-INF/")).getPath()); } else { __velocityConfig.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, __baseViewPath); } // Velocity.init(__velocityConfig); // __inited = true; } }
private Set<String> prepareVelocityTemplate(String template) throws PIPException { VelocityContext vctx = new VelocityContext(); EventCartridge vec = new EventCartridge(); VelocityParameterReader reader = new VelocityParameterReader(); vec.addEventHandler(reader); vec.attachToContext(vctx); try { Velocity.evaluate(vctx, new StringWriter(), "LdapResolver", template); } catch (ParseErrorException pex) { throw new PIPException("Velocity template preparation failed", pex); } catch (MethodInvocationException mix) { throw new PIPException("Velocity template preparation failed", mix); } catch (ResourceNotFoundException rnfx) { throw new PIPException("Velocity template preparation failed", rnfx); } if (this.logger.isTraceEnabled()) { this.logger.trace("(" + id + ") " + template + " with parameters " + reader.parameters); } return reader.parameters; }
private String evaluateVelocityTemplate(String template, final Map<String, PIPRequest> templateParameters, final PIPFinder pipFinder) throws PIPException { StringWriter out = new StringWriter(); VelocityContext vctx = new VelocityContext(); EventCartridge vec = new EventCartridge(); VelocityParameterWriter writer = new VelocityParameterWriter(pipFinder, templateParameters); vec.addEventHandler(writer); vec.attachToContext(vctx); try { Velocity.evaluate(vctx, out, "LdapResolver", template); } catch (ParseErrorException pex) { throw new PIPException("Velocity template evaluation failed", pex); } catch (MethodInvocationException mix) { throw new PIPException("Velocity template evaluation failed", mix); } catch (ResourceNotFoundException rnfx) { throw new PIPException("Velocity template evaluation failed", rnfx); } this.logger.warn("(" + id + ") " + " template yields " + out.toString()); return out.toString(); }
public static String doMerge(String strToMerge, Map map) { if (strToMerge == null) return null; try { // ask Velocity to evaluate it. Velocity.init(); StringWriter w = new StringWriter(); VelocityContext context = new VelocityContext(map); Velocity.evaluate(context, w, "logTag", strToMerge); return w.getBuffer().toString(); } catch (Exception e) { return null; } }
/** * Wrapper for {@link Velocity#evaluate(org.apache.velocity.context.Context, java.io.Writer, String, java.io.InputStream)} * * @param templateReader A {@link Reader} of a Velocity template. * @param variables Variables to add to context * @param logTag The log tag * * @return {@link String} result of evaluation */ public String evaluate(Reader templateReader, Map<String, Object> variables, String logTag) { VelocityContext velocityContext = new VelocityContext(variables); StringWriter writer = new StringWriter(); if (!Velocity.evaluate(velocityContext, writer, logTag, templateReader)) { // Although the Velocity.evaluate method's Javadoc states that it will return false to indicate a failure when the template couldn't be // processed and to see the Velocity log messages for more details, upon examining the method's implementation, it doesn't look like // it will ever return false. Instead, other RuntimeExceptions will be thrown (e.g. ParseErrorException). // Nonetheless, we'll leave this checking here to honor the method's contract in case the implementation changes in the future. // Having said that, there will be no way to JUnit test this flow. throw new IllegalStateException("Error evaluating velocity template. See velocity log message for more details."); } return writer.toString(); }
/** * Simply initialize the Velocity engine */ @PostConstruct public void start() throws Exception { try { Velocity.setProperty(Velocity.RESOURCE_LOADER, "cp"); Velocity.setProperty("cp.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocity.setProperty("cp.resource.loader.cache", "true"); Velocity.setProperty("cp.resource.loader.modificationCheckInterval ", "0"); Velocity.setProperty("input.encoding", "UTF-8"); Velocity.setProperty("output.encoding", "UTF-8"); // Very busy servers should increase this value. Default: 20 // Velocity.setProperty("velocity.pool.size", "20"); Velocity.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.JdkLogChute"); Velocity.init(); log.log(Level.FINE,"Velocity initialized!"); } catch (Exception ex) { log.log(Level.SEVERE,"Unable to initialize Velocity", ex); throw new RuntimeException(ex); } }
@Test public void renderMatrixTemplateTest() throws Exception { //when: String result = templateService.renderTemplate(pof, "Title", "default", riskIssues); //then: verify(pof, times(1)).isFilter(); verify(pof, times(1)).isProject(); verify(pof, times(1)).getName(); verify(webResourceUrlProvider, times(1)).getBaseUrl(); StringWriter sw = new StringWriter(); Writer writer = new BufferedWriter(sw); VelocityContext context = new VelocityContext(); Velocity.mergeTemplate("src/main/resources/templates/matrixTemplate.vm", "UTF-8", context, writer); writer.close(); sw.close(); String expectedResults = sw.getBuffer().toString(); assertEquals("Template service result is not what expected", expectedResults, result); }
/** * 生成代码 by velocity * @param map 变量 * @param destPath 目的地址 * @param destFile 目的文件名 * @param tmpPath 模版地址 * @param tmpFile 模版文件名 * @return */ public static boolean generateCodeByVelocity(Map<String, Object> map, String destPath, String destFile, String tmpPath, String tmpFile){ try { // 1.初始化 Properties properties = new Properties(); properties.put("file.resource.loader.path", tmpPath); properties.put("input.encoding", "UTF-8"); properties.put("output.encoding", "UTF-8"); Velocity.init(properties); VelocityContext context = new VelocityContext(map); // 2.生成代码 FileUtil.mkdir(destPath); BufferedWriter sw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(destPath, destFile)), "UTF-8")); Velocity.getTemplate(tmpFile).merge(context, sw); sw.flush(); sw.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
@SuppressWarnings({ "unchecked", "rawtypes" }) public static boolean formatTemplate(String templateName, Map<?,?> context, Writer output) { try { if (!context.containsKey("esc")) { Map untyped = (Map)context; untyped.put("esc", new VelocityEscaper()); } Reader input = new InputStreamReader(TemplateFormatter.class.getResourceAsStream( templateName + "." + "vm.properties"), Charset.forName("utf-8")); VelocityContext cntx = new VelocityContext(context); boolean ret = Velocity.evaluate(cntx, output, "Template " + templateName, input); input.close(); output.flush(); return ret; } catch (Exception ex) { throw new IllegalStateException("Problems with template evaluation (" + templateName + ")", ex); } }
@Bean VelocityViewResolver velocityViewResolver() { VelocityViewResolver resolver = new VelocityViewResolver(); resolver.setSuffix(this.environment.getProperty("suffix", ".vm")); resolver.setPrefix(this.environment.getProperty("prefix", "/public/")); // Needs to come before any fallback resolver (e.g. a // InternalResourceViewResolver) resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 20); Properties p = new Properties(); p.put(Velocity.FILE_RESOURCE_LOADER_PATH, "/public/"); p.put("input.encoding", "utf-8"); p.put("output.encoding", "utf-8"); resolver.setAttributes(p); resolver.setContentType("text/html;charset=utf-8"); return resolver; }
private void createTemplatePage(Content content, String templateFileName, Path outFilePath) throws IOException { // template name content.put("template", Config.getTemplate()); Properties p = new Properties(); p.setProperty("input.encoding", "UTF-8"); p.setProperty("output.encoding", "UTF-8"); p.setProperty("file.resource.loader.path", Config.getTemplateBaseDir()); Velocity.init(p); VelocityContext context = content.getVelocityContext(); org.apache.velocity.Template template = Velocity.getTemplate(Config.getTemplateFile(lang, templateFileName).toString(), "UTF-8"); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFilePath.toFile()), "UTF-8")); template.merge(context, bw); bw.close(); }
public static boolean configure(File file) { boolean result = false; try { if (file != null) { Velocity.init(file.getAbsolutePath()); } else { // default // org/apache/velocity/runtime/defaults/velocity.properties Velocity.init(); } result = true; } catch (Exception ex) { ex.printStackTrace(); } return result; }
public static boolean configure(Properties properties) { boolean result = false; try { if (properties != null) { Velocity.init(properties); } else { // default // org/apache/velocity/runtime/defaults/velocity.properties Velocity.init(); } result = true; } catch (Exception ex) { ex.printStackTrace(); } return result; }
/** * Load the urist.js template and compile it with project information. */ public static void compileUristJs() { Log.info("TemplateRenderer", "Writing urist.js"); VelocityContext context = new VelocityContext(); context.put("conf", Uristmaps.conf); context.put("version",Uristmaps.VERSION); Template uristJs = Velocity.getTemplate("templates/js/urist.js.vm"); File targetFile = OutputFiles.getUristJs(); targetFile.getParentFile().mkdirs(); try (FileWriter writer = new FileWriter(targetFile)) { uristJs.merge(context, writer); } catch (IOException e) { Log.warn("TemplateRenderer", "Could not write js file: " + targetFile); if (Log.DEBUG) Log.debug("TemplateRenderer", "Exception", e); } }
public static void init() { if (_isInitialized) { return; } Properties veloProp = new Properties(); try { veloProp.load(instance().getClass().getResourceAsStream("/velocity.properties")); //$NON-NLS-1$ Velocity.init(veloProp); _isInitialized = true; } catch (Exception ex) { StatusUtil.log(ex); } }
private static void createReportFromValidationResult(ValidationResult result, Path outputPath) { Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); Velocity.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); Velocity.init(); try { Template template = Velocity.getTemplate("reporting/ValidationResult.vm"); VelocityContext context = new VelocityContext(); context.put("validationResult", result); context.put("resourcesWithWarnings", getResourcesWithWarnings(result)); StringWriter sw = new StringWriter(); template.merge(context, sw); try (FileWriter fw = new FileWriter(outputPath.toFile())) { fw.write(sw.toString()); fw.flush(); } catch (IOException ioe) { LOGGER.error("Creation of HTML Report file {} failed.", outputPath.toString(), ioe); } } catch (VelocityException e) { LOGGER.error("Creation of HTML report failed due to a Velocity Exception", e); } }
/** * Intializes the Apache Velocity template engine. * * @throws ConfigurationException thrown if there is a problem initializing Velocity */ protected static void initializeVelocity() throws ConfigurationException { try { log.debug("Initializing Velocity template engine"); Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.NullLogChute"); Velocity.setProperty(RuntimeConstants.ENCODING_DEFAULT, "UTF-8"); Velocity.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8"); Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); Velocity.setProperty("classpath.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocity.init(); } catch (Exception e) { throw new ConfigurationException("Unable to initialize Velocity template engine", e); } }
@Secured({"ROLE_ADMIN","ROLE_SURVEY_ADMIN"}) @RequestMapping(produces = "text/html") public String getHelpPage(Model uiModel) { try { StringWriter sw = new StringWriter(); VelocityContext velocityContext = new VelocityContext(); Velocity.evaluate(velocityContext, sw, "velocity-log" , surveySettingsService.velocityTemplate_findById(HELP_VELOCITY_TEMPLATE_ID).getDefinition()); uiModel.addAttribute("helpContent", sw.toString().trim()); return "help/index"; } catch (Exception e) { log.error(e.getMessage(),e); throw (new RuntimeException(e)); } }
@Override public void sendTplEmail(final String from, final List<String> to, final List<String> cc, final String subject, final String tpl, final Map<String, Object> model) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(to.toArray(new String[to.size()])); message.setCc(cc.toArray(new String[cc.size()])); message.setFrom(from); message.setSubject(subject); VelocityContext context = new VelocityContext(model); StringWriter w = new StringWriter(); Velocity.evaluate(context, w, "emailString", tpl); message.setText(w.toString(), true); } }; JavaMailSenderImpl javaMailSenderImpl = (JavaMailSenderImpl) mailSender; javaMailSenderImpl.send(preparator); }
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); }
public static void main(String[] args) throws Exception{ VelocityContext context=new VelocityContext(); context.put("zdt", new ZeusDateTool()); String s="abc${zdt.addDay(-1).format(\"yyyyMMdd\")} ${zdt.addDay(1).format(\"yyyyMMdd\")}"; Pattern pt = Pattern.compile("\\$\\{zdt.*\\}"); Matcher matcher=pt.matcher(s); while(matcher.find()){ String m= s.substring(matcher.start(),matcher.end()); System.out.println(m); StringWriter sw=new StringWriter(); Velocity.evaluate(context, sw, "", m); System.out.println(sw.toString()); s=s.replace(m, sw.toString()); } System.out.println("result:"+s); }