DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

WebAppResourceLoader

04.17.2005
| 5893 views |
  • submit to reddit
        The following code is for loading Velocity resources (i.e. Velocity files) from a web application's ServletContext.

import java.io.InputStream;

import javax.servlet.ServletContext;

import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;

public class WebAppResourceLoader extends ResourceLoader {

    private static ServletContext context = null;

    public void init(ExtendedProperties extendedProperties) {

    }

    private static ServletContext getServletContext() {
        return context;
    }

    public static void setServletContext(ServletContext context) {
        WebAppResourceLoader.context = context;
    }

    /**
     * @see org.apache.velocity.runtime.resource.loader.ResourceLoader#getResourceStream(java.lang.String)
     */
    public InputStream getResourceStream(String name)
            throws ResourceNotFoundException {
        InputStream result = null;

        if (name == null || name.length() == 0) {
            throw new ResourceNotFoundException("No template name provided");
        }

        try {
            if (!name.startsWith("/"))
                name = "/" + name;

            result = getServletContext().getResourceAsStream(name);
        } catch (NullPointerException npe) {
            throw new ResourceNotFoundException("ServletContext not found");
        } catch (Exception fnfe) {
            throw new ResourceNotFoundException(fnfe.getMessage());
        }

        return result;
    }

    public boolean isSourceModified(Resource arg0) {
        return false;
    }

    public long getLastModified(Resource arg0) {
        return 0;
    }

}

Then to initialize Velocity:

    WebAppResourceLoader.setServletContext(servletContext);
    Properties props = new Properties();
    props.setProperty("resource.loader", "webapp");
    props.setProperty("webapp.resource.loader.description", 
        "Load from the ServletContext");
    props.setProperty("webapp.resource.loader.class",
        "package.WebAppResourceLoader");
    Velocity.init(props);

From then on out you can use #parse directives such as:

#parse("/WEB-INF/something.vm")