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); }
/** * 根据模板生成文件 * @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 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/decisiontable-editor.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
private void processDynamicWebProject(VelocityContext context, String rootPath, String projectName) throws Exception { File file = new File(rootPath + File.separator + projectName); file.renameTo(new File(rootPath + File.separator + projectName + "-bak")); WizardFileUtils.copyDirectiory(dynamicWebTemplatePath, rootPath + File.separator + projectName); String destProjectFilePath = rootPath + File.separator + projectName + File.separator + ".project"; VelocityUtils.velocityEvaluate(context, dynamicWebProjectVmFile, destProjectFilePath); String wstCommonComponentFilePath = rootPath + File.separator + projectName + File.separator + ".settings" + File.separator + "org.eclipse.wst.common.component"; VelocityUtils.velocityEvaluate(context, wstCommonComponentVmFile, wstCommonComponentFilePath); StringWriter writer = new StringWriter(); String outputDirectory = rootPath + File.separator + projectName + File.separator + "web" + File.separator + "WEB-INF" + File.separator + "lib"; context.put("outputDirectory", outputDirectory); VelocityUtils.velocityEvaluate(context, pomBuildVmFile, writer); String pomPath = rootPath + File.separator + projectName + "-bak" + File.separator + "pom.xml"; this.addPomFileBuildElement(writer.toString(), pomPath); mavenCompiler.execute(pomPath); }
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); }
@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/constant-editor.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
@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(); } }
@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(); } }
@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/decisiontree-editor.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
@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/variable-editor.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
@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(); } }
@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(); } }
@Override public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String key=req.getParameter("key"); String msg=null; if(StringUtils.isBlank(key)){ msg="<h2 style='color:red'>请指定要查看的调试消息的key值</h2>"; }else{ msg=debugMessageHolder.getDebugMessage(key); } VelocityContext context = new VelocityContext(); context.put("title", "URule Console"); context.put("msg", msg); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); Template template=ve.getTemplate("html/console.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); }
@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/client-config-editor.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
@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/ul-editor.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
@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("uflo-html/calendar.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
@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()); context.put("welcomePage", welcomePage); context.put("title", title); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); Template template=ve.getTemplate("html/frame.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
private boolean processMailSending(Map<String, Object> reportDbInfo) { Map<String, Object> templateMap = new HashMap<>(); templateMap.put(JsonKey.ACTION_URL, reportDbInfo.get(JsonKey.FILE_URL)); templateMap.put(JsonKey.NAME, reportDbInfo.get(JsonKey.FIRST_NAME)); templateMap.put(JsonKey.BODY, "Please Find Attached Report for " + reportDbInfo.get(JsonKey.RESOURCE_ID) + " for the Period " + reportDbInfo.get(JsonKey.PERIOD) + " as requested on : " + reportDbInfo.get(JsonKey.CREATED_DATE)); templateMap.put(JsonKey.ACTION_NAME, "DOWNLOAD REPORT"); VelocityContext context = ProjectUtil.getContext(templateMap); return SendMail.sendMail(new String[] {(String) reportDbInfo.get(JsonKey.EMAIL)}, reportDbInfo.get(JsonKey.TYPE) + " for " + reportDbInfo.get(JsonKey.RESOURCE_ID), context, ProjectUtil.getTemplate(new HashMap())); }
@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/package-editor.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
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); } }
/** * Base64 and POST encodes the outbound message and writes it to the outbound transport. * * @param messageContext current message context * @param endpointURL endpoint URL to which to encode message * * @throws MessageEncodingException thrown if there is a problem encoding the message */ protected void postEncode(SAMLMessageContext messageContext, String endpointURL) throws MessageEncodingException { log.debug("Invoking Velocity template to create POST body"); try { VelocityContext context = new VelocityContext(); populateVelocityContext(context, messageContext, endpointURL); HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport(); HTTPTransportUtils.addNoCacheHeaders(outTransport); HTTPTransportUtils.setUTF8Encoding(outTransport); HTTPTransportUtils.setContentType(outTransport, "text/html"); Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), "UTF-8"); velocityEngine.mergeTemplate(velocityTemplateId, "UTF-8", context, out); out.flush(); } catch (Exception e) { log.error("Error invoking Velocity template", e); throw new MessageEncodingException("Error creating output document", e); } }
private static List<String> generateHtmlChunks(List<ReportItem> reportItemList) { List<String> htmlChunks = new ArrayList<>(); VelocityEngine velocityEngine = new VelocityEngine(); Properties p = new Properties(); p.setProperty("resource.loader", "class"); p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); velocityEngine.init(p); Template template = velocityEngine.getTemplate("template/report_template.html"); int maxItemsInReport = CliHelper.getMaxItemsInReport(); List<List<ReportItem>> reportItemsChunks = Lists.partition(reportItemList, maxItemsInReport); for (List<ReportItem> reportItemsChunk : reportItemsChunks ) { VelocityContext velocityContext = new VelocityContext(); velocityContext.put("jarPath", CliHelper.getPathToAnalyze()); velocityContext.put("ruleName", reportItemsChunk.get(0).getRuleName()); velocityContext.put("reportItems", reportItemsChunk); StringWriter stringWriter = new StringWriter(); template.merge(velocityContext, stringWriter); htmlChunks.add(stringWriter.toString()); } return htmlChunks; }
protected void writeApplicationConfigs(String destApplicationPath, String project, String packagePath) throws IOException { String applicationPath = getSrcApplicationFilesPath(); List<String> applicationFiles = getApplicationFiles(); for (String filename : applicationFiles) { if (filename.contains("/")) { String parentPath = filename.substring(0, filename.lastIndexOf("/")); new File(destApplicationPath + "/" + parentPath).mkdirs(); } Template tempate = VelocityUtil.getTempate((applicationPath + "/" + filename).replaceAll("[/]+", "/")); 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("realPath", packagePath.replace(".", "/")); ctx.put("url", url); StringWriter writer = new StringWriter(); tempate.merge(ctx, writer); writer.close(); write(writer.toString(), destApplicationPath + "/" + filename); } }
@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("uflo-html/central.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
@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("uflo-html/todo.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
/** * Overridden to create a ChainedContext, which is part of the view package * of Velocity Tools, as special context. ChainedContext is needed for * initialization of ViewTool instances. * @see #initTool */ @Override protected Context createVelocityContext( Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { // Create a ChainedContext instance. ChainedContext velocityContext = new ChainedContext( new VelocityContext(model), getVelocityEngine(), request, response, getServletContext()); // Load a Velocity Tools toolbox, if necessary. if (getToolboxConfigLocation() != null) { ToolboxManager toolboxManager = ServletToolboxManager.getInstance( getServletContext(), getToolboxConfigLocation()); Map<String, Object> toolboxContext = toolboxManager.getToolbox(velocityContext); velocityContext.setToolbox(toolboxContext); } return velocityContext; }
@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("uflo-html/designer.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); } }
@Test public void testMailTemplateContextCheckOrgImageUrl(){ Map<String , Object> templateMap = new HashMap<>(); templateMap.put(JsonKey.ACTION_URL, "googli.com"); templateMap.put(JsonKey.NAME, "userName"); boolean envVal = !ProjectUtil.isStringNullOREmpty(System.getenv(JsonKey.SUNBIRD_ENV_LOGO_URL)); boolean cacheVal = propertiesCache.getProperty(JsonKey.SUNBIRD_ENV_LOGO_URL)!=null; VelocityContext context = ProjectUtil.getContext(templateMap); if(envVal){ Assert.assertEquals(System.getenv(JsonKey.SUNBIRD_ENV_LOGO_URL) , (String)context.internalGet(JsonKey.ORG_IMAGE_URL)); }else if(cacheVal){ Assert.assertEquals(propertiesCache.getProperty(JsonKey.SUNBIRD_ENV_LOGO_URL) , (String)context.internalGet(JsonKey.ORG_IMAGE_URL)); } }
/** * This method will send forgot password email * * @param name String * @param email String * @param userId String */ private void sendForgotPasswordEmail(String name, String email, String userId) { VelocityContext context = new VelocityContext(); context.put(JsonKey.NAME, name); context.put(JsonKey.TEMPORARY_PASSWORD, ProjectUtil.generateRandomPassword()); context.put(JsonKey.NOTE, propertiesCache.getProperty(JsonKey.MAIL_NOTE)); context.put(JsonKey.ORG_NAME, propertiesCache.getProperty(JsonKey.ORG_NAME)); String appUrl = System.getenv(JsonKey.SUNBIRD_APP_URL); if (ProjectUtil.isStringNullOREmpty(appUrl)) { appUrl = propertiesCache.getProperty(JsonKey.SUNBIRD_APP_URL); } context.put(JsonKey.WEB_URL, ProjectUtil.isStringNullOREmpty(System.getenv(SUNBIRD_WEB_URL)) ? propertiesCache.getProperty(SUNBIRD_WEB_URL) : System.getenv(SUNBIRD_WEB_URL)); if (!ProjectUtil.isStringNullOREmpty(appUrl)) { if (!JsonKey.SUNBIRD_APP_URL.equalsIgnoreCase(appUrl)) { context.put(JsonKey.APP_URL, appUrl); } } ProjectLogger.log("Starting to update password inside cassandra", LoggerEnum.INFO.name()); updatePassword(userId, (String) context.get(JsonKey.TEMPORARY_PASSWORD)); ProjectLogger.log("Password updated in cassandra and start sending email", LoggerEnum.INFO.name()); boolean response = SendMail.sendMail(new String[] {email}, "Forgot password", context, "forgotpassword.vm"); ProjectLogger.log("email sent resposne==" + response, LoggerEnum.INFO.name()); }
protected void postEncode(final MessageContext<SAMLObject> messageContext, final String endpointURL) throws MessageEncodingException { log.debug("Invoking Velocity template to create POST body"); try { final VelocityContext e = new VelocityContext(); this.populateVelocityContext(e, messageContext, endpointURL); responseAdapter.setContentType("text/html"); responseAdapter.init(); final OutputStreamWriter out = responseAdapter.getOutputStreamWriter(); this.getVelocityEngine().mergeTemplate(this.getVelocityTemplateId(), "UTF-8", e, out); out.flush(); } catch (Exception var6) { throw new MessageEncodingException("Error creating output document", var6); } }
private Alarm buildAlarm(RuleContext ctx, FromDeviceMsg msg) throws RuleException { VelocityContext context = VelocityUtils.createContext(ctx.getDeviceMetaData(), msg); String alarmType = VelocityUtils.merge(alarmTypeTemplate, context); String alarmDetails = VelocityUtils.merge(alarmDetailsTemplate, context); Alarm alarm = new Alarm(); alarm.setOriginator(ctx.getDeviceMetaData().getDeviceId()); alarm.setType(alarmType); alarm.setStatus(status); alarm.setSeverity(severity); alarm.setPropagate(configuration.isAlarmPropagateFlag()); try { alarm.setDetails(mapper.readTree(alarmDetails)); } catch (IOException e) { log.debug("[{}] Failed to parse alarm details {} as json string after evaluation.", ctx.getRuleId(), e); throw new RuleException("Failed to parse alarm details as json string after evaluation!", e); } return alarm; }
protected void writeConfiguration(String destProject, String project, String packagePath) throws IOException { String configurationPath = getSrcConfigurationPath(); if (configurationPath == null) return; for (String filename : getSrcConfigurationFiles()) { String vmFile = (configurationPath + "/" + filename).replaceAll("[/]+", "/"); VelocityContext ctx = new VelocityContext(); ctx.put("packagePath", packagePath); ctx.put("project", project); for (Map.Entry<String, Object> entry : options.entrySet()) { ctx.put(entry.getKey(), entry.getValue()); } String destFileName = destProject + "/" + (packagePath + "/config/").replace(".", "/") + "/" + filename.replace(".vm", ".java"); Template tempate = VelocityUtil.getTempate(vmFile); String merge = merge(tempate, ctx); write(merge, destFileName); } }
@Override public Optional<RuleToPluginMsg<?>> convert(RuleContext ctx, ToDeviceActorMsg toDeviceActorMsg, RuleProcessingMetaData metadata) { String sendFlag = configuration.getSendFlag(); if (StringUtils.isEmpty(sendFlag) || (Boolean) metadata.get(sendFlag).orElse(Boolean.FALSE)) { VelocityContext context = VelocityUtils.createContext(metadata); SendMailActionMsg.SendMailActionMsgBuilder builder = SendMailActionMsg.builder(); fromTemplate.ifPresent(t -> builder.from(VelocityUtils.merge(t, context))); toTemplate.ifPresent(t -> builder.to(VelocityUtils.merge(t, context))); ccTemplate.ifPresent(t -> builder.cc(VelocityUtils.merge(t, context))); bccTemplate.ifPresent(t -> builder.bcc(VelocityUtils.merge(t, context))); subjectTemplate.ifPresent(t -> builder.subject(VelocityUtils.merge(t, context))); bodyTemplate.ifPresent(t -> builder.body(VelocityUtils.merge(t, context))); return Optional.of(new SendMailRuleToPluginActionMsg(toDeviceActorMsg.getTenantId(), toDeviceActorMsg.getCustomerId(), toDeviceActorMsg.getDeviceId(), builder.build())); } else { return Optional.empty(); } }
/** * * @param template 模板字符串 * @param map <关键字,替换值> <$YEAR,2017> * @return */ public static String evaluate(String template, Map<String, Object> map) { VelocityContext context = new VelocityContext(); map.forEach(context::put); StringWriter writer = new StringWriter(); velocityEngine.evaluate(context, writer, "", template); return writer.toString(); }
@Override public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { VelocityContext context = new VelocityContext(); context.put("contextPath", req.getContextPath()); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); Template template=ve.getTemplate("ureport-html/searchform.html","utf-8"); PrintWriter writer=resp.getWriter(); template.merge(context, writer); writer.close(); }
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); }
public String evaluate(String templatePath, Map<String, Object> variableMap) { String output = null; try { // logging LOG.info("Evaluating velocity template with path '{}' and variable map '{}'", templatePath, variableMap); // create velocity context and string writer VelocityContext velocityContext = new VelocityContext(variableMap); StringWriter stringWriter = new StringWriter(); // evaluate velocity code velocityEngine.mergeTemplate(templatePath, encoding, velocityContext, stringWriter); // get string output = stringWriter.toString(); // close string writer stringWriter.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } return output; }