@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")); }
@Test @SuppressWarnings("deprecation") public void velocityConfigurerWithCsvPathAndNonFileAccess() throws IOException, VelocityException { VelocityConfigurer vc = new VelocityConfigurer(); vc.setResourceLoaderPath("file:/mydir,file:/yourdir"); vc.setResourceLoader(new ResourceLoader() { @Override public Resource getResource(String location) { if ("file:/yourdir/test".equals(location)) { return new DescriptiveResource(""); } return new ByteArrayResource("test".getBytes(), "test"); } @Override public ClassLoader getClassLoader() { return getClass().getClassLoader(); } }); vc.setPreferFileSystemAccess(false); vc.afterPropertiesSet(); assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vc.createVelocityEngine(); assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", Collections.emptyMap())); }
/** * Evaluates a template with a map of objects. <code>contextMap</code> can * be null if no keys/tokens are referenced in the <code>template</code> * * @param contextMap Map of objects to be used in the template * @param template Velocity Template * @return Evaluated template */ public String evaluate(final Map<String, Object> contextMap, final String template) throws VelocityException { Reader readerOut = null; try { readerOut = new BufferedReader(new StringReader(template)); return evaluate(contextMap, readerOut); } finally { if(readerOut != null) { try { readerOut.close(); } catch (IOException e) { throw new VelocityException(e); } } } }
/** * Send a simple message based on a Velocity template. * * @param msg * the message to populate * @param templateName * the Velocity template to use (relative to classpath) * @param model * a map containing key/value pairs */ @SuppressWarnings("unchecked") public void sendMessage(SimpleMailMessage msg, String templateName, Map model) { String result = null; try { result = VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, templateName, model); } catch (VelocityException e) { log.error(e.getMessage()); } msg.setText(result); send(msg); }
/** * Send a simple message based on a Velocity template. * @param msg the message to populate * @param templateName the Velocity template to use (relative to classpath) * @param model a map containing key/value pairs */ public void sendMessage(SimpleMailMessage msg, String templateName, Map model) { String result = null; try { result = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateName, "UTF-8", model); } catch (VelocityException e) { e.printStackTrace(); log.error(e.getMessage()); } msg.setText(result); send(msg); }
public void generateReports() throws VelocityException, IOException { listFilesForFolder(reportOutputDirectory); String jenkinsBasePath = ""; String buildNumber = "1"; String projectName = "cucumber-jvm"; boolean runWithJenkins = false; boolean parallelTesting = false; Configuration configuration = new Configuration(reportOutputDirectory, projectName); configuration.setParallelTesting(parallelTesting); configuration.setRunWithJenkins(runWithJenkins); configuration.setBuildNumber(buildNumber); ReportBuilder reportBuilder = new ReportBuilder(list, configuration); reportBuilder.generateReports(); }
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); } }
public void testVelocityConfigurerWithCsvPathAndNonFileAccess() throws IOException, VelocityException { VelocityConfigurer vc = new VelocityConfigurer(); vc.setResourceLoaderPath("file:/mydir,file:/yourdir"); vc.setResourceLoader(new ResourceLoader() { @Override public Resource getResource(String location) { if ("file:/yourdir/test".equals(location)) { return new DescriptiveResource(""); } return new ByteArrayResource("test".getBytes(), "test"); } @Override public ClassLoader getClassLoader() { return getClass().getClassLoader(); } }); vc.setPreferFileSystemAccess(false); vc.afterPropertiesSet(); assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vc.createVelocityEngine(); assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", new HashMap())); }
private static String mergeTemplate(String templateContent, final VelocityContext context, boolean useSystemLineSeparators) throws IOException { final StringWriter stringWriter = new StringWriter(); try { Velocity.evaluate(context, stringWriter, "", templateContent); } catch (final VelocityException e) { LOG.error("Error evaluating template:\n"+templateContent,e); ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { Messages.showErrorDialog(IdeBundle.message("error.parsing.file.template", e.getMessage()), IdeBundle.message("title.velocity.error")); } }); } final String result = stringWriter.toString(); if (useSystemLineSeparators) { final String newSeparator = CodeStyleSettingsManager.getSettings(ProjectManagerEx.getInstanceEx().getDefaultProject()).getLineSeparator(); if (!"\n".equals(newSeparator)) { return StringUtil.convertLineSeparators(result, newSeparator); } } return result; }
/** * Generates the mail message based on the file import status. * * @param importStatus The import status to generate file import mail message. * @return The file import mail message for the status. */ private String makeImportMailMessage(ImportStatus importStatus) { Map<String, Object> model = new HashMap<String, Object>(); model.put("importStatus", importStatus); model.put("dateTool", new DateTool()); model.put("mathTool", new MathTool()); model.put("numberTool", new NumberTool()); model.put("StringUtils", StringUtils.class); try { return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, fileImportMailTemplate, "utf-8", model); } catch (VelocityException ve) { logger.error("Error while making file import mail message", ve); // Use the log text instead... return logImportStatus(importStatus); } }
private static String mergeTemplate(String templateContent, final VelocityContext context, boolean useSystemLineSeparators) throws IOException { final StringWriter stringWriter = new StringWriter(); try { VelocityWrapper.evaluate(null, context, stringWriter, templateContent); } catch (final VelocityException e) { LOG.error("Error evaluating template:\n" + templateContent, e); ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(IdeBundle.message("error.parsing.file.template", e.getMessage()), IdeBundle.message("title.velocity.error"))); } final String result = stringWriter.toString(); if (useSystemLineSeparators) { final String newSeparator = CodeStyleSettingsManager.getSettings(ProjectManagerEx.getInstanceEx().getDefaultProject()).getLineSeparator(); if (!"\n".equals(newSeparator)) { return StringUtil.convertLineSeparators(result, newSeparator); } } return result; }
@Bean public VelocityConfig velocityConfig() throws IOException, VelocityException { Properties config = new Properties(); config.setProperty("input.encoding", "UTF-8"); config.setProperty("output.encoding", "UTF-8"); config.setProperty("default.contentType", "text/html;charset=UTF-8"); config.setProperty("resource.loader", "class"); config.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); VelocityConfigurer velocityConfigurer = new VelocityConfigurer(); velocityConfigurer.setVelocityProperties(config); velocityConfigurer.afterPropertiesSet(); return velocityConfigurer; }
private String geVelocityTemplateContent(Map<String, Object> model, String templateName) throws VelocityException { StringBuilder content = new StringBuilder(); try { content.append(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateName, "UTF-8", model)); return content.toString(); } catch (VelocityException e) { log.debug("Exception occured while processing velocity template: " + e.getMessage()); throw e; } }
@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); }
/** * Prepare the VelocityEngine instance and return it. * @return the VelocityEngine instance * @throws IOException if the config file wasn't found * @throws VelocityException on Velocity initialization failure */ public VelocityEngine createVelocityEngine() throws IOException, VelocityException { VelocityEngine velocityEngine = newVelocityEngine(); Map<String, Object> props = new HashMap<String, Object>(); // Load config file if set. if (this.configLocation != null) { if (logger.isInfoEnabled()) { logger.info("Loading Velocity config from [" + this.configLocation + "]"); } CollectionUtils.mergePropertiesIntoMap(PropertiesLoaderUtils.loadProperties(this.configLocation), props); } // Merge local properties if set. if (!this.velocityProperties.isEmpty()) { props.putAll(this.velocityProperties); } // Set a resource loader path, if required. if (this.resourceLoaderPath != null) { initVelocityResourceLoader(velocityEngine, this.resourceLoaderPath); } // Log via Commons Logging? if (this.overrideLogging) { velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new CommonsLogLogChute()); } // Apply properties to VelocityEngine. for (Map.Entry<String, Object> entry : props.entrySet()) { velocityEngine.setProperty(entry.getKey(), entry.getValue()); } postProcessVelocityEngine(velocityEngine); // Perform actual initialization. velocityEngine.init(); return velocityEngine; }
/** * Initialize VelocityEngineFactory's VelocityEngine * if not overridden by a pre-configured VelocityEngine. * @see #createVelocityEngine * @see #setVelocityEngine */ @Override public void afterPropertiesSet() throws IOException, VelocityException { if (this.velocityEngine == null) { this.velocityEngine = createVelocityEngine(); } }
@Bean public VelocityEngine getVelocityEngine() throws VelocityException, IOException { VelocityEngineFactory factory = new VelocityEngineFactory(); Properties props = new Properties(); props.put("resource.loader", "class"); props.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); factory.setVelocityProperties(props); return factory.createVelocityEngine(); }
@Test public void velocityEngineFactoryBeanWithConfigLocation() throws VelocityException { VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean(); vefb.setConfigLocation(new FileSystemResource("myprops.properties")); Properties props = new Properties(); props.setProperty("myprop", "/mydir"); vefb.setVelocityProperties(props); try { vefb.afterPropertiesSet(); fail("Should have thrown IOException"); } catch (IOException ex) { // expected } }
@Test public void velocityEngineFactoryBeanWithResourceLoaderPath() throws IOException, VelocityException { VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean(); vefb.setResourceLoaderPath("file:/mydir"); vefb.afterPropertiesSet(); assertThat(vefb.getObject(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vefb.getObject(); assertEquals(new File("/mydir").getAbsolutePath(), ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH)); }
@Test public void velocityConfigurer() throws IOException, VelocityException { VelocityConfigurer vc = new VelocityConfigurer(); vc.setResourceLoaderPath("file:/mydir"); vc.afterPropertiesSet(); assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vc.createVelocityEngine(); assertEquals(new File("/mydir").getAbsolutePath(), ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH)); }
@Test public void velocityConfigurerWithCsvPath() throws IOException, VelocityException { VelocityConfigurer vc = new VelocityConfigurer(); vc.setResourceLoaderPath("file:/mydir,file:/yourdir"); vc.afterPropertiesSet(); assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vc.createVelocityEngine(); Vector<String> paths = new Vector<>(); paths.add(new File("/mydir").getAbsolutePath()); paths.add(new File("/yourdir").getAbsolutePath()); assertEquals(paths, ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH)); }
/** * Prepare the VelocityEngine instance and return it. * * @return the VelocityEngine instance * @throws java.io.IOException if the config file wasn't found * @throws org.apache.velocity.exception.VelocityException on Velocity initialization failure */ public VelocityEngine createVelocityEngine() throws IOException, VelocityException { VelocityEngine velocityEngine = newVelocityEngine(); Map<String, Object> props = new HashMap<String, Object>(); // Load config file if set. if (this.configLocation != null) { if (logger.isInfoEnabled()) { logger.info("Loading Velocity config from [" + this.configLocation + "]"); } CollectionUtils.mergePropertiesIntoMap(PropertiesLoaderUtils.loadProperties(this.configLocation), props); } // Merge local properties if set. if (!this.velocityProperties.isEmpty()) { props.putAll(this.velocityProperties); } // Set a resource loader path, if required. if (this.resourceLoaderPath != null) { initVelocityResourceLoader(velocityEngine, this.resourceLoaderPath); } // Log via Commons Logging? if (this.overrideLogging) { velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new CommonsLogLogChute()); } // Apply properties to VelocityEngine. for (Map.Entry<String, Object> entry : props.entrySet()) { velocityEngine.setProperty(entry.getKey(), entry.getValue()); } postProcessVelocityEngine(velocityEngine); // Perform actual initialization. velocityEngine.init(); return velocityEngine; }
/** * Render a template and returns the resulting string which can than be used as note content. * * @param templateId * the ID of the template definition whose template should be rendered * @param templatePropertiesJSON * optional string in JSON which should be passed to the template engine and can * contain any additional data the template might need. The string is converted into * a nested map for easier processing within the template. The variable is called * 'props'. * @param renderContext * the render context to use when getting the actual template from the template * definition. The rendering context will also be put into the velocity context so it * can be used in the template. The variable is called 'context' * @param validateTemplateProperties * whether to call the validator of the template definition to validate the template * properties. In case the definition has no validator this argument is ignored. * @return the rendered template * @throws NoteTemplateNotFoundException * in case there is no template definition for the given ID * @throws NoteTemplateRenderException * in case of an error while rendering the template */ public String renderTemplate(String templateId, String templatePropertiesJSON, NoteRenderContext renderContext, boolean validateTemplateProperties) throws NoteTemplateNotFoundException, NoteTemplateRenderException { NoteTemplateDefinition definition = getDefinition(templateId); if (definition == null) { throw new NoteTemplateNotFoundException(templateId); } Context velocityContext = toolManager.createContext(); addTools(velocityContext); velocityContext.put("context", renderContext); HashMap<String, Object> jsonObject = prepareTemplateProperties(definition, templatePropertiesJSON, validateTemplateProperties); if (jsonObject != null) { velocityContext.put("props", jsonObject); } String velocityResourceName = buildVelocityResourceName(definition, renderContext.getMode(), renderContext.getLocale()); StringWriter result = new StringWriter(); try { velocityEngine.mergeTemplate(velocityResourceName, "UTF-8", velocityContext, result); } catch (VelocityException e) { LOGGER.error("VelocityEngine couldn't render the template", e); throw new NoteTemplateRenderException(templateId, "VelocityEngine couldn't render the template", e); } return result.toString(); }
@Override @SuppressWarnings("unchecked") public void writeTo(final Template template, final Viewable viewable, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream out) throws IOException { try { Object model = viewable.getModel(); if (!(model instanceof Map)) { model = new HashMap<String, Object>() {{ put("model", viewable.getModel()); }}; } VelocityContext velocityContext = new VelocityContext(); for (String key : ((Map<String, Object>) model).keySet()) { velocityContext.put(key, ((Map<String, Object>) model).get(key)); } Charset encoding = setContentType(mediaType, httpHeaders); VelocityWriter writer = new VelocityWriter(new OutputStreamWriter(out, encoding)); template.merge(velocityContext, writer); writer.flush(); } catch (VelocityException te) { throw new ContainerException(te); } }
/** * Initializes Velocity engine */ private void init() { velocityEngine.setProperty(VelocityEngine.RESOURCE_LOADER, "class"); velocityEngine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); setLogFile(); DateTool dateTool = new DateTool(); dateTool.configure(this.configMap); MathTool mathTool = new MathTool(); NumberTool numberTool = new NumberTool(); numberTool.configure(this.configMap); SortTool sortTool = new SortTool(); defaultContext = new VelocityContext(); defaultContext.put("dateTool", dateTool); defaultContext.put("dateComparisonTool", new ComparisonDateTool()); defaultContext.put("mathTool", mathTool); defaultContext.put("numberTool", numberTool); defaultContext.put("sortTool", sortTool); // Following tools need VelocityTools version 2.0+ //defaultContext.put("displayTool", new DisplayTool()); //defaultContext.put("xmlTool", new XmlTool()); try { velocityEngine.init(); } catch (Exception e) { throw new VelocityException(e); } }
/** * Evaluates a template with a map of objects. * * @param mapContext Map of Objects to be used in the template * @param template Velocity Template * @return Evaluated template */ public String evaluate(final Map<String, Object> mapContext, final Reader template) throws VelocityException { VelocityContext context = new VelocityContext(mapContext, defaultContext); StringWriter writerOut = new StringWriter(); try { velocityEngine.evaluate(context, writerOut, "VelocityEngine", template); return writerOut.toString(); } catch(Exception e) { throw new VelocityException(e); } }
@Test public void using_external_iterator__should_throw_exception() throws Exception { ExceptionVerifier.TestAction action=() -> generate( template(TEMPLATE_EXTERNAL_ITERATOR), createTemplateObjectFromAnnotation(UnlimitedGeneratorDecorator.class) ); ExceptionVerifier.on(action) .expect(VelocityException.class) .expect("Error invoking the method 'iterator' on class 'org.failearly.dataz.internal.template.generator.decorator.UnlimitedGeneratorDecorator'") .verify(); }
@Bean public VelocityEngine velocityEngine() throws VelocityException, IOException { VelocityEngineFactory factory = new VelocityEngineFactory(); Properties props = new Properties(); props.put("resource.loader", "class"); props.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); factory.setVelocityProperties(props); return factory.createVelocityEngine(); }
private static void createSummaryHtml(String baseFolder, Path summaryFile, int checkedFilesSum, int validResults, Map<String, Integer> violationsByConstraintCount, List<SingleValidationSummary> summaries) { Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); Velocity.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); Velocity.init(); try { Template template = Velocity.getTemplate("reporting/ValidationSummary.vm"); VelocityContext context = new VelocityContext(); context.put("baseFolder", baseFolder); context.put("checkedFilesSum", checkedFilesSum); context.put("directlyChecked", summaries.size()); context.put("importedFilesChecked", checkedFilesSum-summaries.size()); context.put("validResults", validResults); context.put("invalidResults", summaries.size()-validResults); context.put("violationsByConstraintCount", violationsByConstraintCount); context.put("summaries", summaries); StringWriter sw = new StringWriter(); template.merge(context, sw); try (FileWriter fw = new FileWriter(summaryFile.toFile())) { fw.write(sw.toString()); fw.flush(); } catch (IOException ioe) { LOGGER.error("Creation of HTML Report file {} failed.", summaryFile.toString(), ioe); } } catch (VelocityException e) { LOGGER.error("Creation of HTML report failed due to a Velocity Exception", e); } }
@Bean public VelocityEngine velocityEngine() throws VelocityException, IOException{ VelocityEngineFactoryBean factory = new VelocityEngineFactoryBean(); Properties props = new Properties(); props.put("resource.loader", "class"); props.put("class.resource.loader.class","org.apache.velocity.runtime.resource.loader." +"ClasspathResourceLoader"); factory.setVelocityProperties(props); return factory.createVelocityEngine(); }
public void testVelocityEngineFactoryBeanWithConfigLocation() throws VelocityException { VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean(); vefb.setConfigLocation(new FileSystemResource("myprops.properties")); Properties props = new Properties(); props.setProperty("myprop", "/mydir"); vefb.setVelocityProperties(props); try { vefb.afterPropertiesSet(); fail("Should have thrown IOException"); } catch (IOException ex) { // expected } }
public void testVelocityEngineFactoryBeanWithVelocityProperties() throws VelocityException, IOException { VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean(); Properties props = new Properties(); props.setProperty("myprop", "/mydir"); vefb.setVelocityProperties(props); Object value = new Object(); Map 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")); }
public void testVelocityEngineFactoryBeanWithResourceLoaderPath() throws IOException, VelocityException { VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean(); vefb.setResourceLoaderPath("file:/mydir"); vefb.afterPropertiesSet(); assertThat(vefb.getObject(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vefb.getObject(); assertEquals(new File("/mydir").getAbsolutePath(), ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH)); }
public void testVelocityConfigurer() throws IOException, VelocityException { VelocityConfigurer vc = new VelocityConfigurer(); vc.setResourceLoaderPath("file:/mydir"); vc.afterPropertiesSet(); assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vc.createVelocityEngine(); assertEquals(new File("/mydir").getAbsolutePath(), ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH)); }
public void testVelocityConfigurerWithCsvPath() throws IOException, VelocityException { VelocityConfigurer vc = new VelocityConfigurer(); vc.setResourceLoaderPath("file:/mydir,file:/yourdir"); vc.afterPropertiesSet(); assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vc.createVelocityEngine(); Vector paths = new Vector(); paths.add(new File("/mydir").getAbsolutePath()); paths.add(new File("/yourdir").getAbsolutePath()); assertEquals(paths, ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH)); }