Java Code Examples for org.apache.velocity.app.VelocityEngine#getTemplate()
The following examples show how to use
org.apache.velocity.app.VelocityEngine#getTemplate() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VelocityTest.java From snake-yaml with Apache License 2.0 | 6 votes |
public void testTemplate1() throws Exception { VelocityContext context = new VelocityContext(); MyBean bean = createBean(); context.put("bean", bean); Yaml yaml = new Yaml(); context.put("list", yaml.dump(bean.getList())); VelocityEngine ve = new VelocityEngine(); ve.setProperty("file.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); Template t = ve.getTemplate("template/mybean1.vm"); StringWriter writer = new StringWriter(); t.merge(context, writer); String output = writer.toString().trim().replaceAll("\\r\\n", "\n"); // System.out.println(output); String etalon = Util.getLocalResource("template/etalon2-template.yaml").trim(); assertEquals(etalon.length(), output.length()); assertEquals(etalon, output); // parse the YAML document Yaml loader = new Yaml(); MyBean parsedBean = loader.loadAs(output, MyBean.class); assertEquals(bean, parsedBean); }
Example 2
Source File: PortalEntityProvider.java From sakai with Educational Community License v2.0 | 6 votes |
public void init() { VelocityEngine ve = new VelocityEngine(); ve.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new SLF4JLogChute()); ve.setProperty("resource.loader", "class"); ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); // No logging. (If you want to log, you need to set an approrpriate directory in an approrpriate // velocity.properties file, or the log will be created in the directory in which tomcat is started, or // throw an error if it can't create/write in that directory.) ve.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem"); try { ve.init(); formattedProfileTemplate = ve.getTemplate("org/sakaiproject/portal/entityprovider/profile-popup.vm"); } catch (Exception e) { log.error("Failed to load profile-popup.vm", e); } }
Example 3
Source File: VelocityParser.java From ApprovalTests.Java with Apache License 2.0 | 6 votes |
public static Writer parse(String template, Properties props, ContextAware process[], Writer out) { try { props.put("directive.foreach.counter.initial.value", "0"); props.put(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, NullLogChute.class.getName()); VelocityEngine engine = initializeEngine(props); VelocityContext context = new VelocityContext(); Template velocityTemplate = engine.getTemplate(template); for (int i = 0; i < process.length; i++) { if (process[i] != null) process[i].setupContext(context); } velocityTemplate.merge(context, out); return out; } catch (Exception e) { throw ObjectUtils.throwAsError(e); } }
Example 4
Source File: CucumberITGeneratorByFeature.java From cucumber-jvm-parallel-plugin with Apache License 2.0 | 6 votes |
private void initTemplate() { final Properties props = new Properties(); props.put("resource.loader", "class"); props.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); final String name; if (StringUtils.isNotBlank(config.getCustomVmTemplate())) { // Look for custom template on the classpath or as a relative file path props.put("resource.loader", "class, file"); props.put("file.resource.loader.path", config.getProjectBasedir().getAbsolutePath()); name = config.getCustomVmTemplate(); } else if (config.useTestNG()) { name = "cucumber-testng-runner.java.vm"; } else { name = "cucumber-junit-runner.java.vm"; } final VelocityEngine engine = new VelocityEngine(props); engine.init(); velocityTemplate = engine.getTemplate(name, config.getEncoding()); }
Example 5
Source File: RESTToSOAPMsgTemplate.java From carbon-apimgt with Apache License 2.0 | 6 votes |
/** * gets out sequence for the soap operation * * @return out sequence for the converted soap operation */ public String getMappingOutSequence() { ConfigContext configcontext = new SOAPToRESTConfigContext(); StringWriter writer = new StringWriter(); try { VelocityContext context = configcontext.getContext(); context.internalGetKeys(); VelocityEngine velocityengine = new VelocityEngine(); if (!SOAPToRESTConstants.Template.NOT_DEFINED.equalsIgnoreCase(getVelocityLogger())) { velocityengine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, CommonsLogLogChute.class.getName()); velocityengine.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath"); velocityengine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); } velocityengine.init(); org.apache.velocity.Template template = velocityengine.getTemplate(this.getOutSeqTemplatePath()); template.merge(context, writer); } catch (Exception e) { log.error("Velocity Error", e); } return writer.toString(); }
Example 6
Source File: ReportBuilder.java From custom-bytecode-analyzer with GNU General Public License v3.0 | 6 votes |
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; }
Example 7
Source File: Generator.java From erp-framework with MIT License | 5 votes |
public void generateMapper(String targetDir, Table table) { VelocityEngine velocityEngine = createVelocityEngine(); VelocityContext context = createContext(table); Writer writer = createWriter(targetDir, configure.getMapperPackage() .replace(".", "/") + "/" + table.getBeanName() + "Mapper.java"); Template t = velocityEngine.getTemplate("mapperTemplate.vm"); t.merge(context, writer); flushWriter(writer); }
Example 8
Source File: VelocityTemplateTest.java From eagle with Apache License 2.0 | 5 votes |
@Test public void testVelocityTemplate() { String templateString = "This alert ($category) was generated because $reason and $REASON from $source at $created_time"; String resultString = "This alert ($category) was generated because timeout and IO error from localhost at 2016-11-30 05:52:47,053"; VelocityEngine engine = new VelocityEngine(); engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute"); engine.setProperty("runtime.log.logsystem.log4j.logger", LOG.getName()); engine.setProperty(Velocity.RESOURCE_LOADER, "string"); engine.addProperty("string.resource.loader.class", StringResourceLoader.class.getName()); engine.addProperty("string.resource.loader.repository.static", "false"); // engine.addProperty("runtime.references.strict", "true"); engine.init(); StringResourceRepository repo = (StringResourceRepository) engine.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT); repo.putStringResource("alert_template", ""); repo.putStringResource("alert_template", templateString); Assert.assertEquals(templateString, repo.getStringResource("alert_template").getBody()); VelocityContext context = new VelocityContext(); context.put("reason", "timeout"); context.put("REASON", "IO error"); context.put("source","localhost"); context.put("created_time", "2016-11-30 05:52:47,053"); Template velocityTemplate = engine.getTemplate("alert_template"); ASTprocess data = (ASTprocess) velocityTemplate.getData(); ReferenceContext referenceContext = new ReferenceContext(); data.jjtAccept(referenceContext,null); Assert.assertEquals(5, referenceContext.getReferences().size()); StringWriter writer = new StringWriter(); velocityTemplate.merge(context, writer); velocityTemplate.process(); Assert.assertEquals(resultString, writer.toString()); }
Example 9
Source File: Scaffolder.java From yawp with MIT License | 5 votes |
private String parseTemplate(String scaffoldingTemplate, VelocityContext context) { VelocityEngine engine = createVelocityEngine(); Template template = engine.getTemplate(scaffoldingTemplate); StringWriter writer = new StringWriter(); template.merge(context, writer); return writer.toString(); }
Example 10
Source File: LoadVelocityDemo.java From java-tutorial with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
/** * 加载classpath目录下的vm文件 */ public static void loadByClasspath() { System.out.println("========== loadByClasspath =========="); Properties p = new Properties(); p.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); VelocityEngine ve = new VelocityEngine(); ve.init(p); Template t = ve.getTemplate("template/hello.vm"); System.out.println(fillTemplate(t)); }
Example 11
Source File: VelocityUtil.java From sc-generator with Apache License 2.0 | 5 votes |
public static Template getTempate(String path) { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); Template t = ve.getTemplate(path, "utf-8"); return t; }
Example 12
Source File: APITemplateBuilderImpl.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Sets the necessary variables to velocity context * * @param endpointType Type of the endpoint : production or sandbox * @return The string of endpoint file content * @throws APITemplateException Thrown if an error occurred */ @Override public String getConfigStringForEndpointTemplate(String endpointType) throws APITemplateException { StringWriter writer = new StringWriter(); try { ConfigContext configcontext = new APIConfigContext(this.api); configcontext = new EndpointBckConfigContext(configcontext, api); configcontext = new EndpointConfigContext(configcontext, api); configcontext = new TemplateUtilContext(configcontext); configcontext.validate(); VelocityContext context = configcontext.getContext(); context.internalGetKeys(); VelocityEngine velocityengine = new VelocityEngine(); if (!"not-defined".equalsIgnoreCase(getVelocityLogger())) { velocityengine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, CommonsLogLogChute.class.getName()); velocityengine.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath"); velocityengine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); } velocityengine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome()); initVelocityEngine(velocityengine); context.put("type", endpointType); Template template = velocityengine.getTemplate(this.getEndpointTemplatePath()); template.merge(context, writer); } catch (Exception e) { log.error("Velocity Error"); throw new APITemplateException("Velocity Error", e); } return writer.toString(); }
Example 13
Source File: HTMLMaker.java From neoprofiler with Apache License 2.0 | 5 votes |
public void html(DBProfile profile, Writer writer) throws IOException { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); Template t = null; if(ve.resourceExists("/template.html")) t = ve.getTemplate("/template.html"); else { try { t = ve.getTemplate("src/main/resources/template.html"); } catch(Exception exc) { System.err.println("The application could not find a needed HTML template."); System.err.println("This is an unusual problem; please report it as an issue, and provide details of your configuration."); throw new RuntimeException("Could not find HTML template as resource."); } } VelocityContext context = new VelocityContext(); StringWriter markdownContent = new StringWriter(); // Write markdown content.... new MarkdownMaker().markdown(profile, markdownContent); context.put("title", profile.getName()); context.put("markdown", markdownContent.getBuffer().toString()); context.put("links", generateGraph(profile)); //context.put("d3graph", d3graph.toString()); // Dump the contents of the template merged with the context. That's it! t.merge(context, writer); }
Example 14
Source File: Generator.java From erp-framework with MIT License | 5 votes |
public void generateService(String targetDir, Table table) { VelocityEngine velocityEngine = createVelocityEngine(); VelocityContext context = createContext(table); Writer writer = createWriter(targetDir, configure.getServicePackage() .replace(".", "/") + "/" + table.getBeanName() + "Service.java"); Template t = velocityEngine.getTemplate("serviceTemplate.vm"); t.merge(context, writer); flushWriter(writer); }
Example 15
Source File: SamlFederationResource.java From secure-data-service with Apache License 2.0 | 5 votes |
private Template getTemplate() { Properties props = new Properties(); props.setProperty("resource.loader", "class"); props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); VelocityEngine velocityEngine = new VelocityEngine(props); velocityEngine.init(); return velocityEngine.getTemplate(METADATA_TEMPLATE); }
Example 16
Source File: HAProxyConfigWriter.java From attic-stratos with Apache License 2.0 | 4 votes |
public boolean write(Topology topology) { // Prepare global parameters StringBuilder globalParameters = new StringBuilder(); globalParameters.append("stats socket "); globalParameters.append(statsSocketFilePath); StringBuilder frontendCollection = new StringBuilder(); StringBuilder backendCollection = new StringBuilder(); for (Service service : topology.getServices()) { for (Cluster cluster : service.getClusters()) { createConfig(cluster, frontendCollection, backendCollection); } } // Start velocity engine VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath); ve.init(); // Open the template Template t = ve.getTemplate(templateName); // Insert strings into the template VelocityContext context = new VelocityContext(); context.put("global_parameters", globalParameters.toString()); context.put("frontend_collection", frontendCollection.toString()); context.put("backend_collection", backendCollection.toString()); // Create a new string from the template StringWriter stringWriter = new StringWriter(); t.merge(context, stringWriter); String configuration = stringWriter.toString(); // Write configuration file try { BufferedWriter writer = new BufferedWriter(new FileWriter(confFilePath)); writer.write(configuration); writer.close(); if (log.isInfoEnabled()) { log.info(String.format("Configuration written to file: %s", confFilePath)); } return true; } catch (IOException e) { if (log.isErrorEnabled()) { log.error(String.format("Could not write configuration file: %s", confFilePath)); } throw new RuntimeException(e); } }
Example 17
Source File: SeleniumTestsReporter.java From seleniumtestsframework with Apache License 2.0 | 4 votes |
private void generateGlobalErrorsPanel(final SeleniumTestsPageListener abstractPageListener, final VelocityEngine ve, final StringBuffer res, final String style, final ITestContext tc, final StringBuffer sbCalcount) { int pageCount = 0; final Set<ITestResult> testResults = new HashSet<ITestResult>(); addAllTestResults(testResults, tc.getPassedTests()); addAllTestResults(testResults, failedTests.get(tc.getName())); addAllTestResults(testResults, tc.getFailedButWithinSuccessPercentageTests()); final Map<String, Map<String, List<String>>> pageListenerLogMap = TestLogging.getPageListenerLog( abstractPageListener.getClass().getCanonicalName()); if (pageListenerLogMap == null || pageListenerLogMap.isEmpty()) { res.append("<div class='method passed'><div class='yuk_goldgrad_tl'><div class='yuk_goldgrad_tr'>" + "<div class='yuk_goldgrad_m'></div></div></div>" + "<h3 class='yuk_grad_ltitle_passed'>No Errors found.</h3>" + "<div class='yuk_pnl_footerbar'></div>" + "<div class='yuk_grey_bm_footer'><div class='yuk_grey_br'>" + "<div class='yuk_grey_bl'></div></div></div></div>"); } else { for (final Entry<String, Map<String, List<String>>> pageEntry : pageListenerLogMap.entrySet()) { final StringBuilder contentBuffer = new StringBuilder(); contentBuffer.append( "<table class='ex' width='90%'><thead><tr><th>TestMethod</th><th>Errors</th></thead><tbody>"); final Map<String, List<String>> errorMap = pageEntry.getValue(); boolean found = false; for (final ITestResult testResult : testResults) { final Method method = testResult.getMethod().getConstructorOrMethod().getMethod(); final String methodInstance = StringUtility.constructMethodSignature(method, testResult.getParameters()); if (errorMap.containsKey(methodInstance)) { found = true; contentBuffer.append("<tr><td>" + methodInstance + "</td><td>"); for (final String message : errorMap.get(methodInstance)) { contentBuffer.append(message); contentBuffer.append("<br>"); } contentBuffer.append("</td><tr>"); } } if (found) { contentBuffer.append("</tbody></table>"); try { final Template t = ve.getTemplate("/templates/report.part.singlePageError.html"); final VelocityContext context = new VelocityContext(); context.put("status", style); context.put("pageName", pageEntry.getKey()); context.put("content", contentBuffer.toString()); final StringWriter writer = new StringWriter(); t.merge(context, writer); res.append(writer.toString()); } catch (final Exception e) { logger.error("errorLogger creating a singlePageError." + e.getMessage()); } pageCount++; } } } sbCalcount.append(pageCount); }
Example 18
Source File: ParseWithMacroLibsTestCase.java From velocity-engine with Apache License 2.0 | 4 votes |
/** * Test whether the literal text is given if a definition cannot be * found for a macro. * * @throws Exception */ public void testParseMacrosWithNoDefinition() throws Exception { /* * ve1: local scope, cache on */ VelocityEngine ve1 = new VelocityEngine(); ve1.setProperty( Velocity.VM_PERM_INLINE_LOCAL, Boolean.TRUE); ve1.setProperty("velocimacro.permissions.allow.inline.to.replace.global", Boolean.FALSE); ve1.setProperty("file.resource.loader.cache", Boolean.TRUE); ve1.setProperty( Velocity.RUNTIME_LOG_INSTANCE, new TestLogger()); ve1.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file"); ve1.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TEST_COMPARE_DIR + "/parsemacros"); ve1.init(); assureResultsDirectoryExists(RESULT_DIR); FileOutputStream fos = new FileOutputStream (getFileName( RESULT_DIR, "parseMacro2", RESULT_FILE_EXT)); VelocityContext context = new VelocityContext(); Writer writer = new BufferedWriter(new OutputStreamWriter(fos)); Template template = ve1.getTemplate("parseMacro2.vm"); template.merge(context, writer); /** * Write to the file */ writer.flush(); writer.close(); if (!isMatch(RESULT_DIR, COMPARE_DIR, "parseMacro2", RESULT_FILE_EXT,CMP_FILE_EXT)) { fail("Processed template did not match expected output"); } }
Example 19
Source File: ThrottlePolicyTemplateBuilder.java From carbon-apimgt with Apache License 2.0 | 4 votes |
/** * Generate policy for global level. * @param policy policy with level 'global'. Multiple pipelines are not allowed. Can define more than one condition * as set of conditions. all these conditions should be passed as a single pipeline * @return * @throws APITemplateException */ public String getThrottlePolicyForGlobalLevel(GlobalPolicy policy) throws APITemplateException { StringWriter writer = new StringWriter(); if (log.isDebugEnabled()) { log.debug("Generating policy for globalLevel :" + policy.toString()); } if (!(policy instanceof GlobalPolicy)) { throw new APITemplateException("Invalid policy level : Has to be 'global'"); } try { VelocityEngine velocityengine = new VelocityEngine(); velocityengine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, CommonsLogLogChute.class.getName()); if (!"not-defined".equalsIgnoreCase(getVelocityLogger())) { velocityengine.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath"); velocityengine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); } velocityengine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome()); velocityengine.init(); Template template = velocityengine.getTemplate(getTemplatePathForGlobal()); VelocityContext context = new VelocityContext(); setConstantContext(context); context.put("policy", policy); /* if (policy.getPipelines() != null && !policy.getPipelines().isEmpty()) { String conditionString = getPolicyCondition(policy.getPipelines().get(0).getConditions()); context.put("condition", conditionString); } else { context.put("condition", ""); }*/ if (log.isDebugEnabled()) { log.debug("Policy : " + writer.toString()); } template.merge(context, writer); } catch (Exception e) { log.error("Velocity Error", e); throw new APITemplateException("Velocity Error", e); } return writer.toString(); }
Example 20
Source File: SeleniumTestsReporter.java From seleniumtestsframework with Apache License 2.0 | 4 votes |
/** * Begin HTML stream. */ protected void startHtml(final ITestContext ctx, final PrintWriter out) { try { final VelocityEngine ve = new VelocityEngine(); ve.setProperty("resource.loader", "class"); ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); ve.init(); final Template t = ve.getTemplate("/templates/report.part.header.html"); final VelocityContext context = new VelocityContext(); final String userName = System.getProperty("user.name"); context.put("userName", userName); context.put("currentDate", new Date().toString()); final String mode = SeleniumTestsContextManager.getGlobalContext().getWebRunMode(); final String hubUrl = SeleniumTestsContextManager.getGlobalContext().getWebDriverGrid(); context.put("gridHub", "<a href='" + hubUrl + "' target=hub>" + hubUrl + "</a>"); context.put("mode", mode); final StringBuilder sbGroups = new StringBuilder(); sbGroups.append("envt,test"); final List<SeleniumTestsPageListener> pageListenerList = PluginsHelper.getInstance().getPageListeners(); if (pageListenerList != null && !pageListenerList.isEmpty()) { for (final SeleniumTestsPageListener abstractPageListener : pageListenerList) { sbGroups.append(",").append(abstractPageListener.getClass().getSimpleName()); } } context.put("groups", sbGroups.toString()); final StringWriter writer = new StringWriter(); t.merge(context, writer); out.write(writer.toString()); } catch (final Exception e) { logger.error(e.getMessage()); } }