Java Code Examples for org.apache.velocity.app.VelocityEngine#addProperty()

The following examples show how to use org.apache.velocity.app.VelocityEngine#addProperty() . 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: VelocityConfigurer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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");
	}
}
 
Example 2
Source File: VelocityConfigurer.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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");
	}
}
 
Example 3
Source File: MacroAutoReloadTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
protected void setUp() throws Exception
{
    // always copy macros library before modifying it, to ensure successive tests will pass
    Files.copy(FileSystems.getDefault().getPath(RELOAD_TEMPLATE_PATH + "/macros.vtl"), FileSystems.getDefault().getPath(RELOAD_TEMPLATE_PATH + "/macros2.vtl"), StandardCopyOption.REPLACE_EXISTING);

    engine = new VelocityEngine();

    //by default, make the engine's log output go to the test-report
    log = new TestLogger(false, false);
    engine.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, log);

    // use file resource loader
    engine.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file,string");
    engine.addProperty("file.resource.loader.path", RELOAD_TEMPLATE_PATH);
    engine.addProperty("velocimacro.library", "macros2.vtl");
    engine.addProperty("velocimacro.library.autoreload", "true");
    engine.addProperty("file.resource.loader.cache", "false");
    engine.addProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    engine.addProperty("string.resource.loader.repository.name", "stringRepo");
    engine.addProperty("string.resource.loader.repository.static", "false");
    context = new VelocityContext();
}
 
Example 4
Source File: VelocityTemplateParser.java    From eagle with Apache License 2.0 6 votes vote down vote up
public VelocityTemplateParser(String templateString) throws ParseErrorException {
    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 resourceRepository = (StringResourceRepository) engine.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT);
    resourceRepository.putStringResource(TEMPLATE_NAME, templateString);
    template = engine.getTemplate(TEMPLATE_NAME);
    ASTprocess data = (ASTprocess) template.getData();
    visitor = new ParserNodeVisitor();
    data.jjtAccept(visitor, null);
}
 
Example 5
Source File: StringResourceLoaderRepositoryTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
protected VelocityEngine newStringEngine(String repoName, boolean isStatic)
{
    VelocityEngine engine = new VelocityEngine();
    TestLogger logger = new TestLogger();
    engine.setProperty(Velocity.RESOURCE_LOADERS, "string");
    engine.addProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    if (repoName != null)
    {
        engine.addProperty("string.resource.loader.repository.name", repoName);
    }
    if (!isStatic)
    {
        engine.addProperty("string.resource.loader.repository.static", "false");
    }
    engine.addProperty("string.resource.loader.modificationCheckInterval", "1");
    engine.setProperty(Velocity.RUNTIME_LOG_INSTANCE, logger);
    return engine;
}
 
Example 6
Source File: BaseTestCase.java    From velocity-tools with Apache License 2.0 6 votes vote down vote up
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 7
Source File: BaseTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
protected VelocityEngine createEngine()
{
    VelocityEngine ret = new VelocityEngine();
    ret.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, log);

    // use string resource loader by default, instead of file
    ret.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file,string");
    ret.addProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    ret.addProperty("string.resource.loader.repository.name", stringRepoName);
    ret.addProperty("string.resource.loader.repository.static", "false");

    setUpEngine(ret);
    return ret;
}
 
Example 8
Source File: Velocity702TestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
public void setUpEngine(VelocityEngine engine)
{
    engine.setProperty(RuntimeConstants.RESOURCE_LOADERS, "high,low");
    engine.addProperty("high.resource.loader.class", StringResourceLoader.class.getName());
    engine.addProperty("high.resource.loader.cache", "false");
    engine.addProperty("high.resource.loader.repository.name", "high");
    engine.addProperty("high.resource.loader.repository.static", "false");
    engine.addProperty("high.resource.loader.modificationCheckInterval", "1");
    engine.addProperty("low.resource.loader.class", StringResourceLoader.class.getName());
    engine.addProperty("low.resource.loader.cache", "true");
    engine.addProperty("low.resource.loader.repository.name", "low");
    engine.addProperty("low.resource.loader.repository.static", "false");
    engine.addProperty("low.resource.loader.modificationCheckInterval", "1");
    engine.init();
}
 
Example 9
Source File: Velocity747TestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
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 10
Source File: VelocityTemplateTest.java    From eagle with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: VelocityAlertTemplateEngine.java    From eagle with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Config config) {
    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.init();

    stringResourceRepository = (StringResourceRepository) engine.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT);
    policyDefinitionRepository = new HashMap<>();
}
 
Example 12
Source File: MicroServiceTemplateUtil.java    From nh-micro with Apache License 2.0 5 votes vote down vote up
public static String sqlTemplateService(String template,Map paramMap,List placeList){
	VelocityEngine ve = new VelocityEngine();
	ve.addProperty("userdirective", "com.nh.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();
}
 
Example 13
Source File: MicroServiceTemplateUtil.java    From nh-micro with Apache License 2.0 5 votes vote down vote up
public static String sqlTemplateService(String template,Map paramMap,List placeList){
	VelocityEngine ve = new VelocityEngine();
	ve.addProperty("userdirective", "com.nh.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();
}
 
Example 14
Source File: VelocityResponseWriter.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private VelocityEngine createEngine(SolrQueryRequest request) {

    boolean trustedMode = request.getCore().getCoreDescriptor().isConfigSetTrusted();


    VelocityEngine engine = new VelocityEngine();

    // load the built-in _macros.vm first, then load VM_global_library.vm for legacy (pre-5.0) support,
    // and finally allow macros.vm to have the final say and override anything defined in the preceding files.
    engine.setProperty(RuntimeConstants.VM_LIBRARY, "_macros.vm,VM_global_library.vm,macros.vm");

    // Standard templates autoload, but not the macro one(s), by default, so let's just make life
    // easier, and consistent, for macro development too.
    engine.setProperty(RuntimeConstants.VM_LIBRARY_AUTORELOAD, "true");

    /*
      Set up Velocity resource loader(s)
       terminology note: "resource loader" is overloaded here, there is Solr's resource loader facility for plugins,
       and there are Velocity template resource loaders.  It's confusing, they overlap: there is a Velocity resource
       loader that loads templates from Solr's resource loader (SolrVelocityResourceLoader).

      The Velocity resource loader order is `[file,][solr],builtin` intentionally ordered in this manner.
      The "file" resource loader, enabled when the configset is trusted and `template.base.dir` is specified as a
      response writer init property.

      The "solr" resource loader, enabled when the configset is trusted, and provides templates from a velocity/
      sub-tree in either the classpath or under conf/.

      By default, only "builtin" resource loader is enabled, providing tenplates from builtin Solr .jar files.

      The basic browse templates are built into
      this plugin, but can be individually overridden by placing a same-named template in the template.base.dir specified
      directory, or within a trusted configset's velocity/ directory.
     */
    ArrayList<String> loaders = new ArrayList<String>();
    if ((fileResourceLoaderBaseDir != null) && trustedMode) {
      loaders.add("file");
      engine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, fileResourceLoaderBaseDir.getAbsolutePath());
    }
    if (trustedMode) {
      // The solr resource loader serves templates under a velocity/ subtree from <lib>, conf/,
      // or SolrCloud's configuration tree.  Or rather the other way around, other resource loaders are rooted
      // from the top, whereas this is velocity/ sub-tree rooted.
      loaders.add("solr");
      engine.setProperty("solr.resource.loader.instance", new SolrVelocityResourceLoader(request.getCore().getSolrConfig().getResourceLoader()));
    }

    // Always have the built-in classpath loader.  This is needed when using VM_LIBRARY macros, as they are required
    // to be present if specified, and we want to have a nice macros facility built-in for users to use easily, and to
    // extend in custom ways.
    loaders.add("builtin");
    engine.setProperty("builtin.resource.loader.instance", new ClasspathResourceLoader());

    engine.setProperty(RuntimeConstants.RESOURCE_LOADER, String.join(",", loaders));


    engine.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8");
    engine.setProperty(RuntimeConstants.SPACE_GOBBLING, RuntimeConstants.SpaceGobbling.LINES.toString());

    // install a class/package restricting uberspector
    engine.setProperty(RuntimeConstants.UBERSPECT_CLASSNAME,"org.apache.velocity.util.introspection.SecureUberspector");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_PACKAGES,"java.lang.reflect");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"java.lang.Class");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"java.lang.ClassLoader");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"java.lang.Compiler");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"java.lang.InheritableThreadLocal");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"java.lang.Package");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"java.lang.Process");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"java.lang.Runtime");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"java.lang.RuntimePermission");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"java.lang.SecurityManager");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"java.lang.System");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"java.lang.Thread");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"java.lang.ThreadGroup");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"java.lang.ThreadLocal");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"org.apache.solr.core.SolrResourceLoader");
    engine.addProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,"org.apache.solr.core.CoreContainer");

    if (trustedMode) {
      // Work around VELOCITY-908 with Velocity not handling locales properly
      Object spaceGobblingInitProperty = velocityInitProps.get(RuntimeConstants.SPACE_GOBBLING);
      if (spaceGobblingInitProperty != null) {
        // If there is an init property, uppercase it before Velocity.
        velocityInitProps.put(RuntimeConstants.SPACE_GOBBLING,
            String.valueOf(spaceGobblingInitProperty).toUpperCase(Locale.ROOT));
      }
      // bring in any custom properties too
      engine.setProperties(velocityInitProps);
    }

    engine.init();

    return engine;
  }
 
Example 15
Source File: HyphenInIdentifiersTestCase.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
protected void setUpEngine(VelocityEngine engine)
{
    engine.addProperty("parser.allow_hyphen_in_identifiers", true);
}
 
Example 16
Source File: DeprecatedCheckUberspectorsTestCase.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
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 17
Source File: UberspectImplTestCase.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
@Override
protected void setUpEngine(VelocityEngine engine)
{
    engine.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, new TestLogger());
    engine.addProperty(RuntimeConstants.UBERSPECT_CLASSNAME, "org.apache.velocity.util.introspection.UberspectImpl");
}
 
Example 18
Source File: Velocity537TestCase.java    From velocity-engine with Apache License 2.0 3 votes vote down vote up
public void setUp() throws Exception
{

    assureResultsDirectoryExists(RESULTS_DIR);

    velocityEngine = new VelocityEngine();
    velocityEngine.addProperty(Velocity.FILE_RESOURCE_LOADER_PATH, TEMPLATE_DIR);

    velocityEngine.setProperty(Velocity.RUNTIME_LOG_INSTANCE, new TestLogger());

    velocityEngine.init();
}