Search code examples
javavelocityspark-framework

How to reload templates without reloading server?


I'm working on an application in Java/Spark framework and I'm using the Apache Velocity template engine. My problem is, that every time I change anything in the templates, I have to reload the whole server. Is there a way to enable some kind of hot-swapping to be able to work on the templates without reloading the whole server?

private final VelocityEngine velocityEngine;

public VelocityTemplateEngine() {
    Properties properties = new Properties();
    properties.setProperty("resource.loader", "class");
    properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    properties.setProperty("class.resource.loader.cache", "true");
    properties.setProperty("class.resource.loader.modificationCheckInterval", "2");
    properties.setProperty("velocimacro.library.autoreload", "true");
    properties.setProperty("velocimacro.permissions.allow.inline.to.replace.global", "true");
    velocityEngine = new org.apache.velocity.app.VelocityEngine(properties);
    //velocityEngine.init(); <-- This bit of code does not change anything when uncommented...
}

Solution:
Solved by changing the resource.loader to file and class.resource.loader.class to org.apache.velocity.runtime.resource.loader.FileResourceLoader

properties.setProperty("resource.loader", "file");
properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");

properties.setProperty("file.resource.loader.path", root + "/src/main/resources/"); // "root" points to the app folder

properties.setProperty("class.resource.loader.cache", "true"); // Enable cache
properties.setProperty("class.resource.loader.modificationCheckInterval", "2"); // Check for new files every 2 seconds

Solution

  • Try this :

    1. Initialize a velocity engine instance . VelocityEngine x = new VelocityEngine();
    2. Set properties :

       file.resource.loader.class= FileResourceLoader classname
       file.resource.loader.path=  template location
       file.resource.loader.cache= true
       file.resource.loader.modificationCheckInterval= duration in which you want to reload the templates
      
    3. x.int();

    Important point here is that you don't initialize velocity engine again on every request. Do something like this while creating velocity engine object :

      VelocityEngine x;   // instance variable
    
      if(x==null)
      {
       x = new VelocityEngine();
       x.init();
       }
      else
      {
       x;
       }