1

I have a requirement to generate some automated mails and so I wanted to use velocity for this task.I have copied all velocity jars to the lib folder and created a hello.vm template and placed in WEB-INF/templates folder.Below is exception I am getting,

org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'hello.vm'
userCount incremented to :1
    at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:474)
    at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:352)
    at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533)
    at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1514)
    at org.apache.velocity.app.VelocityEngine.getTemplate(VelocityEngine.java:373)
    at indian.test.handleRequest(test.java:34)
    at org.apache.velocity.tools.view.VelocityViewServlet.doRequest(VelocityViewServlet.java:217)
    at org.apache.velocity.tools.view.VelocityViewServlet.doGet(VelocityViewServlet.java:182)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at listener.trimresponse.doFilter(trimresponse.java:46)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)

I tried all the other ways to load resource using classloader/webapps and still the error remains the same.I am using netbeans 7.2.x with tomcat 7.27. Appreciate if someone can suggest something for this.

Below is my velocity properties file,

resource.loader = file
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path = C:\Users\kiran\Desktop\Netbeans Projects\ourstory\web\WEB-INF\templates
file.resource.loader.cache = true
file.resource.loader.modificationCheckInterval = 2
runtime.log=/WEB-INF/logs/velocity.log 
runtime.log.logsystem.class=org.apache.velocity.runtime.log.Log4JLogSystem
runtime.log.logsystem.log4j.pattern=%d - %m%n
runtime.log.logsystem.log4j.file.size=10000
runtime.log.logsystem.log4j.file.backups=1

and below is servlet I am using

import java.util.Properties;
import javax.servlet.http.*;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.VelocityViewServlet;

public class test extends VelocityViewServlet {
    private String htmlTemplate = "hello.vm";

    VelocityContext context = new VelocityContext();

    @Override
    public Template handleRequest(HttpServletRequest request,
            HttpServletResponse response,
            Context context) {
   //    Properties props = new Properties();
    //    props.setProperty("resource.loader", "class");
    //    props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    //    props.setProperty("webapp.resource.loader.path", "/WEB-INF/templates/");

        VelocityEngine engine = new VelocityEngine();


        engine.init();

        Template template = null;

        try {
            context.put("name", "Velocity Test");           
                    template = engine.getTemplate(htmlTemplate);
           } catch (Exception e) {
             e.printStackTrace();
            System.err.println("Exception caught: " + e.getMessage());
        }
        return template;
    }
}

its simple servlet but for some reason I am unable to get it working.

Olaf Kock
  • 46,930
  • 8
  • 59
  • 90
Kiran Badi
  • 501
  • 2
  • 9
  • 24
  • 1
    Try to load it from classpath rather than `WEB-INF`.It could help.Or simply put the template in the same folder where `test.java` is. It should help to find the resource.For reference see this post http://stackoverflow.com/questions/3443819/velocity-cant-find-resource – SRy Dec 03 '12 at 04:53
  • I tried Srinivas loading it from classpath and Webapps.But no joy.I dont know why its not finding it.I am on windows vista,netbeans7.2x and tc7.027.In every case,error is same.How do I know which path getTemplate call is checking for ?.I have my projects folder in desktop and my TC is in Program Files file under apache software configuration.Current working directory points to Tomcat bin directory in Program files. – Kiran Badi Dec 03 '12 at 15:37
  • I guess Environment shouldn't be a matter.In my project I am loading it from Classpath but with no properites files.Just directly mentioning the path in the java Code.But did u try loading it from same folder where your test.java is ? – SRy Dec 03 '12 at 17:23
  • Yes I had tried that approach as well.Actually I am integrating the velocity with my existing j2ee application built with servlets/jsp.I can direct access the vm files via browser but for some reason its not going via velocityview servlet.Let me clean up the things and load it via classpath again.I have spend nearly 1 day on this frustating error message and exhausted all the options that google gave me.I dont know if it works for you ,it should work for me. – Kiran Badi Dec 03 '12 at 18:16
  • 1
    At this point I don't see anything else.Go through these links , these might help you http://svn.apache.org/repos/asf/velocity/engine/trunk/velocity-engine-core/src/test/java/org/apache/velocity/test/StringResourceLoaderRepositoryTestCase.java and http://velocity.apache.org/engine/devel/apidocs/org/apache/velocity/runtime/resource/loader/StringResourceLoader.html – SRy Dec 03 '12 at 19:45
  • I just ran the same unit test and it ran without any issues.Testsuite: org.apache.velocity.test.StringResourceLoaderRepositoryTestCase Tests run: 6, Failures: 0, Errors: 0, Time elapsed: 0.357 sec.I dont know where I should look now.Let me read the documents again,maybe I am missing something finer details. – Kiran Badi Dec 03 '12 at 21:17
  • Thanks Srinivas, its solved.How to do give you points.Works under web-inf/templates as well. – Kiran Badi Dec 03 '12 at 23:44

1 Answers1

0

(Answered in comments and edits. See Question with no answers, but issue solved in the comments (or extended in chat) )

The OP wrote:

Update Solved.

Finally After wasting good 2 days and pulling out lot of hairs,and banging the head many times, its resolved.here is what I did to resolve this, added couple of logging statements to ensure that it points correct to the templates folders and then pasing the absolute path to the template file. Watch out for backslashes and forward slashes. Need to log the folder paths and see where exactly its looking for and then keep dubugging. Its pain in the ass to fix such a simple stuff.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author kiran
 */
import java.io.File;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.http.*;
import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.VelocityViewServlet;

public class Hellotest extends VelocityViewServlet {

    @Override
    public Template handleRequest(HttpServletRequest request,
            HttpServletResponse response,
            Context context) {
        Properties prop = new Properties();
  //      prop.put("resource.loader", "class");
  //      prop.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        String absolutePath = new File(Thread.currentThread().getContextClassLoader().getResource("").getFile()).getParentFile().getParentFile().getPath();
        prop.put("file.resource.loader.path", absolutePath + "\\templates\\");
        System.out.println("absolute path is : " + absolutePath);       
        System.out.println("keyset is : " + prop.keySet()); 
        Enumeration em = prop.keys();
        while (em.hasMoreElements()) {
            String str = (String) em.nextElement();
            System.out.println(str + ": " + prop.get(str));
        }
        VelocityEngine Velocity = new VelocityEngine();
        Velocity.init(prop);
        Template template = null;
        context.put("name", "Velocity Test");
        try {
            System.out.println("absolute path inside is : " + context); 
            template = Velocity.getTemplate("hello.vm","UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Exception caught: " + e.getMessage());
        }

        return template;
    }
}

and here is updated velocity properties file,

resource.loader = file
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.cache = true
file.resource.loader.modificationCheckInterval = 2

and finally I put the templates under webpages folder. Maybe I will try to push this in web-inf and see how it goes. Its not good thing to keep templates under webpages given that we are exposing it.

Community
  • 1
  • 1
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129