Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServletContext on Google App Engine where is the "context" in the classpath?

I want to deploy a few Freemarker templates with my Google App Engine java application to use as email body templates. I'm using freemarker-gae-2.3.23.jar.

My question is where within the war file should I place my template files so that the Freemarker Configuration class can find them? I thought WEB-INF/classes/templates would work but I'm getting the following error when I run it on a GAE instance. getRealPath() does not give any insight either. Empty string is returned. Any thoughts or suggestions much appreciated.

SEVERE: Template ./templates/invitation.ftl not found.
java.lang.RuntimeException: Error in loading ftl template: Template ./templates/invitation.ftl not found.

My basic config is as follows:

public class FreeMarkerConfig {

private static FreeMarkerConfig freeMarkerConfig = null;
private static Configuration cfg = null;
private static final Logger logger =   Logger.getLogger(FreeMarkerConfig.class.getName());

private FreeMarkerConfig(ServletContext context){
    cfg = new Configuration();
    cfg.setServletContextForTemplateLoading(context, "/templates");
}

public static FreeMarkerConfig getInstance(ServletContext context){
    if(freeMarkerConfig == null){

        freeMarkerConfig = new FreeMarkerConfig(context);
        return freeMarkerConfig;
    }
    return freeMarkerConfig;
}

public static Template getTemplateByName(String fileName){
    try {
        return cfg.getTemplate(fileName);
    } catch(IOException e) {
        logger.severe(e.getMessage());
        e.getStackTrace();
        throw new RuntimeException("Error in loading ftl template: "+e.getMessage());
    }
}
}l
like image 645
mba12 Avatar asked Sep 20 '15 01:09

mba12


1 Answers

The solution was two fold. The context location is the "web" directory. So setting the freemarker config with this, fixed the problem.

    private FreeMarkerConfig(ServletContext context){
    cfg = new Configuration();
    cfg.setServletContextForTemplateLoading(context, "/WEB-INF/classes/templates/");
    }

As a second helpful tip I found I had to request the template with just the name of the template and not the filename. i.e. invitation and not invitation.ftl

like image 157
mba12 Avatar answered Oct 10 '22 00:10

mba12