Java Code Examples for org.apache.velocity.app.VelocityEngine#setProperty()
The following examples show how to use
org.apache.velocity.app.VelocityEngine#setProperty() .
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: VelocityInlineDispatcher.java From sakai with Educational Community License v2.0 | 6 votes |
public void init(ServletContext context) throws ServletException { inlineMacros = MACROS; try { vengine = new VelocityEngine(); vengine.setApplicationAttribute(ServletContext.class.getName(), context); vengine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new SLF4JLogChute()); Properties p = new Properties(); p.load(this.getClass().getResourceAsStream("rwikivelocity.config")); vengine.init(p); vengine.getTemplate(inlineMacros); } catch (Exception ex) { throw new ServletException(ex); } }
Example 2
Source File: JSONFuzzing.java From osmo with GNU Lesser General Public License v2.1 | 6 votes |
public static void main(String[] args) { VelocityEngine ve = new VelocityEngine(); ve.setProperty("resource.loader", "class"); ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); ve.init(); VelocityContext context = new VelocityContext(); Text text5 = new Text(1, 5); text5.setRandomToString(true).setSeed(55); Text numbers5 = new Text(1, 5).numbersOnly(); numbers5.setRandomToString(true).setSeed(55); context.put("username", text5); context.put("password", text5); context.put("sessionid", text5); context.put("hash", numbers5); Template template = ve.getTemplate("/osmo/tester/examples/fuzz/login_manual.vm"); StringWriter sw = new StringWriter(); template.merge(context, sw); System.out.println(sw); }
Example 3
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 4
Source File: BaseTestCase.java From velocity-tools with Apache License 2.0 | 6 votes |
protected void setUp() throws Exception { engine = new VelocityEngine(); //by default, make the engine's log output go to the test-report log = new MockLogger(false, false); log.setEnabledLevel(MockLogger.LOG_LEVEL_INFO); engine.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, log); // use string resource loader by default, instead of file engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file,string"); engine.addProperty("string.resource.loader.class", StringResourceLoader.class.getName()); engine.addProperty("string.resource.loader.repository.name", stringRepoName); engine.addProperty("string.resource.loader.repository.static", "false"); setUpEngine(engine); context = new VelocityContext(); setUpContext(context); }
Example 5
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 6
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 7
Source File: DefaultVelocityEngineProducer.java From krazo with Apache License 2.0 | 5 votes |
@Produces @ViewEngineConfig public VelocityEngine getVelocityEngine() { VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.setProperty("resource.loader", "webapp"); velocityEngine.setProperty("webapp.resource.loader.class", ServletContextResourceLoader.class.getCanonicalName()); velocityEngine.setApplicationAttribute("javax.servlet.ServletContext", servletContext); velocityEngine.init(); return velocityEngine; }
Example 8
Source File: IssuesReportListener.java From pitest-descartes with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void runStart() { VelocityEngine engine = new VelocityEngine(); engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); engine.init(); methodResportTemplate = engine.getTemplate("templates/method-report.vm", "UTF-8"); indexTemplate = engine.getTemplate("templates/index-report.vm", "UTF-8"); findings = new ArrayList<>(); }
Example 9
Source File: VelocityService.java From cloud-portal with MIT License | 5 votes |
@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(); }
Example 10
Source File: HollowUIRouter.java From hollow with Apache License 2.0 | 5 votes |
protected VelocityEngine initVelocity() { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SimpleLog4JLogSystem"); ve.setProperty("runtime.log.logsystem.log4j.category", "velocity"); ve.setProperty("runtime.log.logsystem.log4j.logger", "velocity"); ve.init(); return ve; }
Example 11
Source File: DefaultVelocityEngineProducer.java From ozark with Apache License 2.0 | 5 votes |
@Produces @ViewEngineConfig public VelocityEngine getVelocityEngine() { VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.setProperty("resource.loader", "webapp"); velocityEngine.setProperty("webapp.resource.loader.class", WebappResourceLoader.class.getCanonicalName()); velocityEngine.setApplicationAttribute("javax.servlet.ServletContext", servletContext); velocityEngine.init(); return velocityEngine; }
Example 12
Source File: VelocityEngineFactory.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * 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; }
Example 13
Source File: Velocity747TestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
protected void setUp() throws Exception { Properties props = new Properties(); /* The props file contains *spaces* at the end of the line: * velocimacro.permissions.allow.inline.local.scope = true * which caused the initial problem */ props.load(new FileReader(TEST_COMPARE_DIR + "/issues/velocity-747/vel.props")); props.setProperty("file.resource.loader.path", TEST_COMPARE_DIR + "/issues/velocity-747/"); engine1 = new VelocityEngine(props); //by default, make the engine's log output go to the test-report log = new TestLogger(false, false); engine1.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, log); engine2 = new VelocityEngine(); engine2.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file,string"); engine2.addProperty("file.resource.loader.path", TEST_COMPARE_DIR + "/issues/velocity-747/"); engine2.addProperty("file.resource.loader.cache", "true"); engine2.addProperty("file.resource.loader.modificationCheckInterval", "-1"); engine2.addProperty("velocimacro.permissions.allow.inline.local.scope", "true"); engine2.addProperty("velocimacro.max.depth", "-1"); engine2.addProperty("string.resource.loader.class", StringResourceLoader.class.getName()); engine2.addProperty("string.resource.loader.repository.name", "stringRepo"); engine2.addProperty("string.resource.loader.repository.static", "false"); log = new TestLogger(false, false); engine2.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, log); }
Example 14
Source File: EagleMailClient.java From eagle with Apache License 2.0 | 5 votes |
public EagleMailClient(final Properties config) { try { velocityEngine = new VelocityEngine(); velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,org.apache.velocity.runtime.log.Log4JLogChute.class.getName()); velocityEngine.setProperty("runtime.log.logsystem.log4j.logger", LOG.getName()); velocityEngine.init(); config.put("mail.transport.protocol", "smtp"); if (Boolean.parseBoolean(config.getProperty(AlertEmailConstants.CONF_MAIL_AUTH))) { session = Session.getInstance(config, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( config.getProperty(AlertEmailConstants.CONF_AUTH_USER), config.getProperty(AlertEmailConstants.CONF_AUTH_PASSWORD) ); } }); } else { session = Session.getInstance(config, new Authenticator() { }); } final String debugMode = config.getProperty(AlertEmailConstants.CONF_MAIL_DEBUG, "false"); final boolean debug = Boolean.parseBoolean(debugMode); LOG.info("Set email debug mode: " + debugMode); session.setDebug(debug); } catch (Exception e) { LOG.error("Failed to connect to smtp server", e); } }
Example 15
Source File: TmpBuilder.java From BigDataPlatform with GNU General Public License v3.0 | 5 votes |
public TmpBuilder(InputParams ip) { this.ip = ip; ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); }
Example 16
Source File: ParseWithMacroLibsTestCase.java From velocity-engine with Apache License 2.0 | 4 votes |
/** * Test that if a macro is duplicated, the second one takes precendence * * @throws Exception */ public void testDuplicateDefinitions() 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, "parseMacro3", RESULT_FILE_EXT)); VelocityContext context = new VelocityContext(); Writer writer = new BufferedWriter(new OutputStreamWriter(fos)); Template template = ve1.getTemplate("parseMacro3.vm"); template.merge(context, writer); /** * Write to the file */ writer.flush(); writer.close(); if (!isMatch(RESULT_DIR, COMPARE_DIR, "parseMacro3", RESULT_FILE_EXT,CMP_FILE_EXT)) { fail("Processed template did not match expected output"); } }
Example 17
Source File: BuiltInEventHandlerTestCase.java From velocity-engine with Apache License 2.0 | 4 votes |
/** * test that escape reference handler works with match restrictions * @throws Exception */ public void testEscapeReferenceMatch() throws Exception { // set up HTML match on everything, JavaScript match on _js* VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.EVENTHANDLER_REFERENCEINSERTION, "org.apache.velocity.app.event.implement.EscapeHtmlReference,org.apache.velocity.app.event.implement.EscapeJavaScriptReference"); ve.setProperty("eventhandler.escape.javascript.match", "/.*_js.*/"); ve.init(); Writer writer; // Html no JavaScript writer = new StringWriter(); ve.evaluate(newEscapeContext(),writer,"test","$test1"); assertEquals("Jimmy's <b>pizza</b>",writer.toString()); // comment out bad test -- requires latest commons-lang /** // JavaScript and HTML writer = new StringWriter(); ve.evaluate(newEscapeContext(),writer,"test","$test1_js"); assertEquals("Jimmy\\'s <b>pizza</b>",writer.toString()); // JavaScript and HTML writer = new StringWriter(); ve.evaluate(newEscapeContext(),writer,"test","$test1_js_test"); assertEquals("Jimmy\\'s <b>pizza</b>",writer.toString()); // JavaScript and HTML (method call) writer = new StringWriter(); ve.evaluate(newEscapeContext(),writer,"test","$test1_js.substring(0,7)"); assertEquals("Jimmy\\'s",writer.toString()); **/ log("Escape selected references (global configuration)"); }
Example 18
Source File: DeprecatedCheckUberspectorsTestCase.java From velocity-engine with Apache License 2.0 | 4 votes |
protected void setUpEngine(VelocityEngine engine) { engine.setProperty(Velocity.RUNTIME_LOG_INSTANCE, new TestLogger(false, true)); engine.addProperty(Velocity.UBERSPECT_CLASSNAME, "org.apache.velocity.util.introspection.UberspectImpl"); engine.addProperty(Velocity.UBERSPECT_CLASSNAME, "org.apache.velocity.util.introspection.DeprecatedCheckUberspector"); }
Example 19
Source File: GatewayBasicFuncTest.java From knox with Apache License 2.0 | 4 votes |
@Test( timeout = TestUtils.MEDIUM_TIMEOUT ) public void testOozieJobSubmission() throws Exception { LOG_ENTER(); String root = "/tmp/GatewayBasicFuncTest/testOozieJobSubmission"; String user = "hdfs"; String pass = "hdfs-password"; String group = "hdfs"; // Cleanup anything that might have been leftover because the test failed previously. deleteFile( user, pass, root, "true", HttpStatus.SC_OK ); /* Put the workflow definition into HDFS */ createFile( user, pass, group, root+"/workflow.xml", "666", "application/octet-stream", "oozie-workflow.xml", 307, 201, 200 ); /* Put the mapreduce code into HDFS. (hadoop-examples.jar) curl -X PUT --data-binary @hadoop-examples.jar 'http://192.168.1.163:8888/org.apache.org.apache.knox.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/hadoop-examples.jar?user.name=hdfs&op=CREATE' */ createFile( user, pass, group, root+"/lib/hadoop-examples.jar", "777", "application/octet-stream", findHadoopExamplesJar(), 307, 201, 200 ); /* Put the data file into HDFS (changes.txt) curl -X PUT --data-binary @changes.txt 'http://192.168.1.163:8888/org.apache.org.apache.knox.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/input/changes.txt?user.name=hdfs&op=CREATE' */ createFile( user, pass, group, root+"/input/changes.txt", "666", "text/plain", "changes.txt", 307, 201, 200 ); VelocityEngine velocity = new VelocityEngine(); velocity.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.NullLogSystem" ); velocity.setProperty( RuntimeConstants.RESOURCE_LOADER, "classpath" ); velocity.setProperty( "classpath.resource.loader.class", ClasspathResourceLoader.class.getName() ); velocity.init(); VelocityContext context = new VelocityContext(); context.put( "userName", user ); context.put( "nameNode", "hdfs://sandbox:8020" ); context.put( "jobTracker", "sandbox:50300" ); //context.put( "appPath", "hdfs://sandbox:8020" + root ); context.put( "appPath", root ); context.put( "inputDir", root + "/input" ); context.put( "outputDir", root + "/output" ); String name = TestUtils.getResourceName( this.getClass(), "oozie-jobs-submit-request.xml" ); Template template = velocity.getTemplate( name ); StringWriter sw = new StringWriter(); template.merge( context, sw ); String request = sw.toString(); /* Submit the job via Oozie. */ String id = oozieSubmitJob( user, pass, request, 201 ); String success = "SUCCEEDED"; String status = "UNKNOWN"; long delay = 1000; // 1 second. long limit = 1000 * 60; // 60 seconds. long start = System.currentTimeMillis(); while( System.currentTimeMillis() <= start+limit ) { status = oozieQueryJobStatus( user, pass, id, 200 ); if( success.equalsIgnoreCase( status ) ) { break; } else { Thread.sleep( delay ); } } assertThat( status, is( success ) ); if( CLEANUP_TEST ) { // Cleanup anything that might have been leftover because the test failed previously. deleteFile( user, pass, root, "true", HttpStatus.SC_OK ); } LOG_EXIT(); }
Example 20
Source File: VelocityEngineProvider.java From nexus-public with Eclipse Public License 1.0 | 4 votes |
private VelocityEngine create() { VelocityEngine engine = new VelocityEngine(); // log using our chute (slf4j with level fix) engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new Slf4jLogChute()); // to avoid "unable to find resource 'VM_global_library.vm' in any resource loader." engine.setProperty("velocimacro.library", ""); // to use classpath loader engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "class"); engine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); // to make us strict with template references (early problem detection) engine.setProperty("runtime.references.strict", "true"); engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "class"); engine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); // to set caching ON engine.setProperty("class.resource.loader.cache", "true"); // to never check for template modification (they are JARred) engine.setProperty("class.resource.loader.modificationCheckInterval", "0"); // to set strict mode OFF engine.setProperty("runtime.references.strict", "false"); // to force templates having inline local scope for VM definitions engine.setProperty("velocimacro.permissions.allow.inline.local.scope", "true"); log.debug("Initializing: {}", engine); try { engine.init(); } catch (Exception e) { Throwables.throwIfUnchecked(e); throw new RuntimeException(e); } return engine; }