/** * 根据模板生成文件 * @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; } }
private void sendEmail(final String fromEmail, final IUser to, final String inSubject, final String inTemplate, final Map<String, Object> values) { final Properties props = new Properties(); props.setProperty("resource.loader", "class"); props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); final VelocityEngine engine = new VelocityEngine(props); final VelocityContext context = new VelocityContext(); engine.init(); for(final String key : values.keySet()) { LOGGER.debug(() -> String.format("\t -- %s=%s", key, values.get(key))); context.put(key, values.get(key)); } final StringWriter writer = new StringWriter(); final Template template = engine.getTemplate("templates/" + inTemplate); template.merge(context, writer); final String inBody = writer.toString(); sendEmail(fromEmail, to.getEmail(), inSubject, inBody); }
private static StringWriter buildStringWriter(List<Node> nodes, List<Edge> edges, Map<EVMEnvironment, SymExecutor> executions) throws ReportException { 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_FILE); VelocityContext velocityContext = new VelocityContext(); ObjectMapper objectMapper = new ObjectMapper(); try { velocityContext.put("nodes", objectMapper.writeValueAsString(nodes)); velocityContext.put("edges", objectMapper.writeValueAsString(edges)); velocityContext.put("executions", executions); } catch (IOException e) { logger.error("Error building the report: " + e); throw new ReportException("Failed creating ReportItem"); } StringWriter stringWriter = new StringWriter(); template.merge(velocityContext, stringWriter); return stringWriter; }
@Before public void setUp() throws TikaException, IOException, SAXException { VelocityEngine engine = new VelocityEngine(); engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); engine.init(); Templater templater = new Templater(); templater.setEngine(engine); exporter = new HtmlExporter(); exporter.setTemplater(templater); TikaProvider provider = new TikaProvider(); Tika tika = provider.tika(); transformer = new TikaTransformer(); transformer.setTika(tika); }
@Before public void setUp() throws TikaException, IOException, SAXException { VelocityEngine engine = new VelocityEngine(); engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); engine.init(); Templater templater = new Templater(); templater.setEngine(engine); exporter = new PdfExporter(); exporter.setTemplater(templater); TikaProvider provider = new TikaProvider(); Tika tika = provider.tika(); transformer = new TikaTransformer(); transformer.setTika(tika); }
protected VelocityEngine getInternalEngine() throws IOException{ VelocityEngine engine = new VelocityEngine(); Properties ps = new Properties(); ps.setProperty(";runtime.log", Docx4jProperties.getProperty("docx4j.velocity.runtime.log", "velocity.log")); ps.setProperty(";runtime.log.logsystem.class", Docx4jProperties.getProperty("docx4j.velocity.runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem")); ps.setProperty("resource.loader", Docx4jProperties.getProperty("docx4j.velocity.resource.loader", "file")); ps.setProperty("file.resource.loader.cache", Docx4jProperties.getProperty("docx4j.velocity.file.resource.loader.cache", "true")); ps.setProperty("file.resource.loader.class ", Docx4jProperties.getProperty("docx4j.velocity.file.resource.loader.class", "Velocity.Runtime.Resource.Loader.FileResourceLoader") ); ps.setProperty(";resource.loader", Docx4jProperties.getProperty("docx4j.velocity.resource.loader", "webapp")); ps.setProperty(";webapp.resource.loader.class", Docx4jProperties.getProperty("docx4j.velocity.webapp.resource.loader.class", "org.apache.velocity.tools.view.servlet.WebappLoader")); ps.setProperty(";webapp.resource.loader.cache", Docx4jProperties.getProperty("docx4j.velocity.webapp.resource.loader.cache", "true")); ps.setProperty(";webapp.resource.loader.modificationCheckInterval", Docx4jProperties.getProperty("docx4j.velocity.webapp.resource.loader.modificationCheckInterval", "3") ); ps.setProperty(";directive.foreach.counter.name", Docx4jProperties.getProperty("docx4j.velocity.directive.foreach.counter.name", "velocityCount")); ps.setProperty(";directive.foreach.counter.initial.value", Docx4jProperties.getProperty("docx4j.velocity.directive.foreach.counter.initial.value", "1")); ps.setProperty("file.resource.loader.path", this.getClass().getResource(Docx4jProperties.getProperty("docx4j.velocity.file.resource.loader.path", "/template")).getPath()); //模板输入输出编码格式 String input_charset = Docx4jProperties.getProperty("docx4j.velocity.input.encoding", Docx4jConstants.DEFAULT_CHARSETNAME); String output_charset = Docx4jProperties.getProperty("docx4j.velocity.output.encoding", Docx4jConstants.DEFAULT_CHARSETNAME ); ps.setProperty("input.encoding", input_charset); ps.setProperty("output.encoding", output_charset); engine.init(ps); return engine; }
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; }
/** * Provides a ClasspathResourceLoader in addition to any default or user-defined * loader in order to load the spring Velocity macros from the class path. * @see org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader */ @Override protected void postProcessVelocityEngine(VelocityEngine velocityEngine) { velocityEngine.setApplicationAttribute(ServletContext.class.getName(), this.servletContext); velocityEngine.setProperty( SPRING_MACRO_RESOURCE_LOADER_CLASS, ClasspathResourceLoader.class.getName()); velocityEngine.addProperty( VelocityEngine.RESOURCE_LOADER, SPRING_MACRO_RESOURCE_LOADER_NAME); velocityEngine.addProperty( VelocityEngine.VM_LIBRARY, SPRING_MACRO_LIBRARY); if (logger.isInfoEnabled()) { logger.info("ClasspathResourceLoader with name '" + SPRING_MACRO_RESOURCE_LOADER_NAME + "' added to configured VelocityEngine"); } }
/** * Build the WebSSO handler for sending and receiving SAML2 messages. * * @param ctx the ctx * @param spssoDescriptor the spsso descriptor * @return the encoder instance */ private MessageEncoder getMessageEncoder(final SAML2MessageContext ctx) { final Pac4jSAMLResponse adapter = ctx.getProfileRequestContextOutboundMessageTransportResponse(); if (SAMLConstants.SAML2_POST_BINDING_URI.equals(destinationBindingType)) { final VelocityEngine velocityEngine = VelocityEngineFactory.getEngine(); final Pac4jHTTPPostEncoder encoder = new Pac4jHTTPPostEncoder(adapter); encoder.setVelocityEngine(velocityEngine); return encoder; } if (SAMLConstants.SAML2_REDIRECT_BINDING_URI.equals(destinationBindingType)) { return new Pac4jHTTPRedirectDeflateEncoder(adapter, forceSignRedirectBindingAuthnRequest); } throw new UnsupportedOperationException("Binding type - " + destinationBindingType + " is not supported"); }
public static VelocityEngine getEngine() { try { final Properties props = new Properties(); props.putAll(net.shibboleth.utilities.java.support.velocity.VelocityEngine.getDefaultProperties()); props.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8"); props.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8"); props.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); props.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, SLF4JLogChute.class.getName()); final VelocityEngine velocityEngine = net.shibboleth.utilities.java.support.velocity.VelocityEngine .newVelocityEngine(props); return velocityEngine; } catch (final Exception e) { throw new TechnicalException("Error configuring velocity", e); } }
public static String format(VelocityEngine ve,Reader reader, Object dataModel){ if(ve == null){ ve = VlocityFormat.ve; } Context context = createVelocityContext(dataModel); //raw return if(context == null){ return reader.toString(); } StringWriter writer = new StringWriter(); ve.evaluate(context, writer, "logTag", reader); return writer.toString(); }
@Test public void renderNonWebAppTemplate() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( VelocityAutoConfiguration.class); try { VelocityEngine velocity = context.getBean(VelocityEngine.class); StringWriter writer = new StringWriter(); Template template = velocity.getTemplate("message.vm"); template.process(); VelocityContext velocityContext = new VelocityContext(); velocityContext.put("greeting", "Hello World"); template.merge(velocityContext, writer); assertThat(writer.toString()).contains("Hello World"); } finally { context.close(); } }
@Test public void velocityEngineFactoryBeanWithVelocityProperties() throws VelocityException, IOException { VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean(); Properties props = new Properties(); props.setProperty("myprop", "/mydir"); vefb.setVelocityProperties(props); Object value = new Object(); Map<String, Object> map = new HashMap<>(); map.put("myentry", value); vefb.setVelocityPropertiesMap(map); vefb.afterPropertiesSet(); assertThat(vefb.getObject(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vefb.getObject(); assertEquals("/mydir", ve.getProperty("myprop")); assertEquals(value, ve.getProperty("myentry")); }
private void renderSchema(PrismSchema schema, PrismContext prismContext, VelocityEngine velocityEngine, PathGenerator pathGenerator) throws IOException { getLog().info("Processing schema: "+schema); VelocityContext velocityContext = new VelocityContext(); populateVelocityContextBase(velocityContext, prismContext, pathGenerator, schema, ".."); Template template = velocityEngine.getTemplate(TEMPLATE_SCHEMA_NAME); Writer writer = new FileWriter(pathGenerator.prepareSchemaOutputFile(schema)); template.merge(velocityContext, writer); writer.close(); // Object Definitions for (PrismObjectDefinition objectDefinition: schema.getObjectDefinitions()) { renderObjectDefinition(objectDefinition, schema, prismContext, velocityEngine, pathGenerator); } // Types for (ComplexTypeDefinition typeDefinition : schema.getComplexTypeDefinitions()) { renderComplexTypeDefinition(typeDefinition, schema, prismContext, velocityEngine, pathGenerator); } }
public static String fromTemplate(String velocityTemplate, Map<String, String> mapVariables) { StringWriter stringWriter = new StringWriter(); try { VelocityEngine velocityEngine = getVelocityEngine(); VelocityContext velocityContext = new VelocityContext(); for (Map.Entry<String, String> entry : mapVariables.entrySet()) { velocityContext.put(entry.getKey(), entry.getValue()); } velocityEngine.evaluate(velocityContext, stringWriter, "PackageTemplatesVelocity", velocityTemplate); } catch (Exception e) { Logger.log("fromTemplate Error in Velocity code generator"); return null; } return stringWriter.getBuffer().toString(); }
public VelocityGenerator(String packageName ) { this.packageName = packageName; this.javaClassGenerator = new JavaClassGenerator(); velocityEngine = new VelocityEngine(); velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); try { velocityEngine.init(); } catch (Exception e) { e.printStackTrace(); System.out.println("VelocityEngine can not initialize."); System.exit(0); } }
public SQLGenerator(String type) { this.type = type; this.javaClassGenerator = new JavaClassGenerator(); velocityEngine = new VelocityEngine(); velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); try { velocityEngine.init(); } catch (Exception e) { e.printStackTrace(); System.out.println("VelocityEngine can not initialize."); System.exit(0); } }
/** * Render the http auth properties file to be used with openfire * * @param request * the request to use * @return the rendered properties */ public static String getOpenfireHttpAuthProperties(HttpServletRequest request) { // TODO change JSPs to VM and parse the http_auth.properties template VelocityEngine engine = ServiceLocator.findService(VelocityEngine.class); Map<String, Object> context = new HashMap<String, Object>(); context.put("defaultHost", ApplicationProperty.WEB_SERVER_HOST_NAME.getValue()); context.put("defaultPort", ApplicationProperty.WEB_HTTP_PORT.getValue()); context.put("internalHost", request.getServerName()); context.put("internalPort", request.getServerPort()); if (request.isSecure()) { context.put("internalProtocol", "https"); } else { context.put("internalProtocol", "http"); } context.put("defaultPortHttps", ApplicationProperty.WEB_HTTPS_PORT.getValue()); context.put("context", request.getContextPath()); String render = VelocityEngineUtils.mergeTemplateIntoString(engine, VELOCITY_TEMPLATE_HTTP_AUTH_PROPERTIES, context); return render; }
private Processor createProcessor(MediaType mediaType, VelocityEngine velocityEngine) { Processor processor = null; switch (mediaType) { case HTML: { processor = new HtmlProcessor(velocityEngine); break; } case JSON: { processor = new JsonProcessor(); break; } default: { processor = new HtmlProcessor(velocityEngine); } } return processor; }
/** * Creates and returns the website's index page. * * <p>This is not private only so that it can be unit-tested. * * @param redirectUrl the Url of the booking page for the current date. * @param showRedirectMessage whether to show a redirect error message to the user */ protected String createIndexPage(String redirectUrl, Boolean showRedirectMessage) { logger.log("About to create the index page"); // Create the page by merging the data with the page template VelocityEngine engine = new VelocityEngine(); // Use the classpath loader so Velocity finds our template Properties properties = new Properties(); properties.setProperty("resource.loader", "class"); properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); engine.init(properties); VelocityContext context = new VelocityContext(); context.put("redirectUrl", redirectUrl); context.put("showRedirectMessage", showRedirectMessage); // Render the page StringWriter writer = new StringWriter(); Template template = engine.getTemplate("squash/booking/lambdas/IndexPage.vm", "utf-8"); template.merge(context, writer); logger.log("Rendered index page: " + writer); return writer.toString(); }
@Override public void writeTo(String templateReference, Viewable viewable, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream out) throws IOException { // 获取 模板引擎 VelocityEngine velocityEngine = getVelocityEngine(); // 实例化一个VelocityContext VelocityContext context = (VelocityContext) viewable.getModel(); Enumeration<String> enums = request.getParameterNames(); while (enums.hasMoreElements()) { String key = enums.nextElement(); context.put(key, request.getParameter(key)); } // 把request放进模板上下文里 context.put("request", request); // 渲染并输出 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out); velocityEngine.mergeTemplate(templateReference, "utf8", context, outputStreamWriter); outputStreamWriter.flush(); outputStreamWriter.close(); // 有必要关闭吗? 关闭了是否对jax-rs拦截器,servlet有影响,需要继续学习,参考jsp模板实现 }
private VelocityEngine getVelocityEngine() throws IOException { // 当前servletContext环境有没有 Object ve = request.getServletContext().getAttribute("velocityEngine"); if (ve != null) { return (VelocityEngine) ve; } // 注册velocity String path = request.getServletContext().getRealPath("/WEB-INF/classes/velocity.properties"); Properties properties = new Properties(); try (FileInputStream in = new FileInputStream(path)) { properties.load(in); properties.setProperty("file.resource.loader.path", request.getServletContext().getRealPath("/WEB-INF/vm")); } catch (IOException e) { throw e; } VelocityEngine velocityEngine = new VelocityEngine(properties); request.getServletContext().setAttribute("velocityEngine", velocityEngine); return velocityEngine; }
public static String sqlTemplateService(String template,Map paramMap,List placeList){ VelocityEngine ve = new VelocityEngine(); ve.addProperty("userdirective", "com.minxin.micro.template.vext.MicroSqlReplace"); ve.init(); VelocityContext context = new VelocityContext(); context.put("param", paramMap); context.put("placeList", placeList); StringWriter writer = new StringWriter(); ve.evaluate(context, writer, "", template); return writer.toString(); }
private static VelocityEngine initVMEngine() { VelocityEngine ret = new VelocityEngine(); ret.setProperty("file.resource.loader.path", VM_PATH); try { ret.init(); } catch (Exception e) { e.printStackTrace(); } return ret; }
@PostConstruct public void init() { // create velocity engine velocityEngine = new VelocityEngine(); velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); velocityEngine.init(); }
@Bean public VelocityEngine getVelocityEngine() throws VelocityException, IOException { Properties props = new Properties(); props.setProperty("resource.loader", "class"); props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); return new VelocityEngine(props); }
@Before public void setUp() { VelocityEngine engine = new VelocityEngine(); engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); engine.init(); templater = new Templater(); templater.setEngine(engine); }
@Before public void setUp() throws IOException, TikaException, SAXException { MockitoAnnotations.initMocks(this); createDirectories(Paths.get("fileTestFiles")); docxExporter = new DocxExporter(); xlsxExporter = new XlsxExporter(); VelocityEngine engine = new VelocityEngine(); engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); engine.init(); templater = new Templater(); templater.setEngine(engine); pdfExporter = new PdfExporter(); pdfExporter.setTemplater(templater); ObjectMapperProducer objectMapperProducer = new ObjectMapperProducer(); mapper = objectMapperProducer.objectMapper(false, false); TikaProvider provider = new TikaProvider(); Tika tika = provider.tika(); transformer = new TikaTransformer(); transformer.setTika(tika); }
@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext=applicationContext; ve = new VelocityEngine(); ve.setProperty(Velocity.RESOURCE_LOADER, "class"); ve.setProperty("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); ve.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM,new NullLogChute()); ve.init(); }