Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Velocity engine initialization issue

I have a written a library that has a mailbuilding part. This mailbuilding part employs the use of Velocity. The mailbuilder class is as follows --

public class mailBuilder {
 public void initialize() throws Exception
    {
            Properties props = new Properties();

            log.info("About to set the ClassPath for Velocity specific tasks");
            props.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath");
            props.setProperty("classpath." + VelocityEngine.RESOURCE_LOADER + ".class", ClasspathResourceLoader.class.getName());

            try
            {
                log.info("Just before");
                Velocity.init(props);
                log.info("Just after");
            }
            catch ( Exception e )
            {
                log.error( "Caught Execption on velocityEngine init", e );
                throw new Exception( "Caught Execption on velocityEngine init", e );
            }
            log.info("Completed initializing Velocity Engine");

    }

public String returnMailstring() throws Exception {
initialize();
....
....
}

}

Now when i run and test this library as is from eclipse, it the results are as expected and things seems fine. I have a web application that takes in a request from the UI, and uses ExecutorService (newSingleThreadExecutor) to service these user requests one by one silently in the background.

I am noticing that my calls to the aforementioned library are getting hung at the mailbuilding part specifically at Velocity.init(props) There is no exception thrown but the thread seems to hang at the VelocityEngine initialization. I have looked up online and had no luck with what the issue may be. Any help on how the issue would be immense.

Thanks p1ng

like image 638
ping Avatar asked Dec 27 '22 08:12

ping


1 Answers

There are two models for velocity usage:

  1. Singleton model i.e. Velocity.init(..), here you have only a single velocity configuration in your app. You should call init only once in this case in the application startup via a listener or any sort of initializing bean.
  2. The multimodel starting version 1.2 you can have multiple velocity engines using multiple configurations the model is used as such:
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;

...


//  create a new instance of the engine
 VelocityEngine ve = new VelocityEngine();


//  configure the engine.  In this case, we are using
//  ourselves as a logger (see logging examples..)


ve.setProperty(
    VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);

//  initialize the engine
ve.init();

...

Template t = ve.getTemplate("foo.vm");

so just choose the model you wish to use and follow it. but invoking Velocity.init() in a threaded way certainly should have an undesirable behavior.

like image 57
MahdeTo Avatar answered Jan 06 '23 23:01

MahdeTo