Prod Tester
Prod Tester

Reputation: 253

apache velocity resource not found exception even though template file is in the same directory

i've learned of velocity as template engine and am trying it out in my code snippet.

package myproj.templating.velocity;

import java.io.StringWriter;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

public class velocityTest {

    public static void main (String args[]) {

        VelocityEngine ve = new VelocityEngine();
        ve.init();

        VelocityContext context = new VelocityContext();

        context.put( "name", new String("Velocity") );

        Template template = null;

        try
        {
           template = ve.getTemplate("mytemplate.vm");
        }
        catch (ResourceNotFoundException rne) {
            rne.printStackTrace();
        }
        catch ( ParseErrorException pee )

        {
          // syntax error: problem parsing the template
            pee.printStackTrace();
        }
        catch( MethodInvocationException mie )
        {
          // something invoked in the template
          // threw an exception
            mie.printStackTrace();
        }
        catch( Exception e )
        { e.printStackTrace();}

        StringWriter sw = new StringWriter();

        template.merge( context, sw );

        System.out.println("result= " + sw.toString());
    }
}

mytemplate.vm file is physically located in the same directory as this code and i've checked the spelling multiple times. but i still get ResourceNotFound exception. what could be wrong? i've tried suggestions on stackflow to add filepath and what not but still gets the same exception.

Upvotes: 0

Views: 1481

Answers (1)

Prod Tester
Prod Tester

Reputation: 253

following set up did the trick.

Properties p = new Properties();
 p.setProperty("resource.loader","file");
 p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
 p.setProperty("file.resource.loader.path","/actual/full/path/here");           
 p.setProperty("file.resource.loader.cache", "false");
 p.setProperty("file.resource.loader.modificationCheckInterval", "0");

ve.init(p);

Upvotes: 1

Related Questions