Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2003-2006 The Apache Software Foundation.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  * 
  * This code was basaed on the simular code in the Velocity Tools project.
  */
 
 package org.sakaiproject.portal.charon.velocity;
 
 import java.io.File;
 
 
Resource loader that uses the ServletContext of a webapp to load Velocity templates. (it's much easier to use with servlets than the standard FileResourceLoader, in particular the use of war files is transparent). The default search path is '/' (relative to the webapp root), but you can change this behaviour by specifying one or more paths by mean of as many webapp.resource.loader.path properties as needed in the velocity.properties file. All paths must be relative to the root of the webapp. To enable caching and cache refreshing the webapp.resource.loader.cache and webapp.resource.loader.modificationCheckInterval properties need to be set in the velocity.properties file ... auto-reloading of global macros requires the webapp.resource.loader.cache property to be set to 'false'.

Author(s):
Geir Magnusson Jr.
Nathan Bubna
Claude Brisson
Version:
$Id: WebappLoader.java 21575 2007-02-15 13:40:21Z ian@caret.cam.ac.uk $
 
 
 public class WebappLoader extends ResourceLoader
 {

The root paths for templates (relative to webapp's root).
 
 	protected String[] paths = null;
 
 	protected HashMap templatePaths = null;
 
 	protected ServletContext servletContext = null;

This is abstract in the base class, so we need it.
NOTE: this expects that the ServletContext has already been placed in the runtime's application attributes under its full class name (i.e. "javax.servlet.ServletContext").

Parameters:
configuration the org.apache.commons.collections.ExtendedProperties associated with this resource loader.
 
 	public void init(ExtendedProperties configuration)
 	{
 		.debug("WebappLoader : initialization starting.");
 
 		/* get configured paths */
 		 = configuration.getStringArray("path");
 		if ( == null || . == 0)
 		{
 			 = new String[1];
 			[0] = "/";
 		}
 		else
 		{
 			/* make sure the paths end with a '/' */
 			for (int i = 0; i < .i++)
 			{
 				if (![i].endsWith("/"))
 				{
 					[i] += '/';
 				}
 				if ( [i].startsWith("./") ) {
 					[i] = [i].substring(1);
 				}
 				.info("WebappLoader : added template path - '" + [i] + "'");
 			}
 		}
 
		/* get the ServletContext */
		if (obj instanceof ServletContext)
		{
		}
		else
		{
			.error("WebappLoader : unable to retrieve ServletContext");
		}
		/* init the template paths map */
		.debug("WebappLoader : initialization complete.");
	}

Get an InputStream so that the Runtime can build a template with it.

Parameters:
name name of template to get
Returns:
InputStream containing the template
Throws:
org.apache.velocity.exception.ResourceNotFoundException if template not found in classpath.
	public synchronized InputStream getResourceStream(String name)
	{
		InputStream result = null;
		if (name == null || name.length() == 0)
		{
					"WebappLoader : No template name provided");
		}
		/*
		 * since the paths always ends in '/', make sure the name never starts
		 * with one
		 */
		while (name.startsWith("/"))
		{
			name = name.substring(1);
		}
		Exception exception = null;
		for (int i = 0; i < .i++)
		{
			try
			{
				result = .getResourceAsStream([i] + name);
				/* save the path and exit the loop if we found the template */
				if (result != null)
				{
					break;
				}
			}
			catch (Exception e)
			{
				/* only save the first one for later throwing */
				if (exception == null)
				{
					exception = e;
				}
			}
		}
		/* if we never found the template */
		if (result == null)
		{
			String msg;
			if (exception == null)
			{
				msg = "WebappLoader : Resource '" + name + "' not found.";
			}
			else
			{
				msg = exception.getMessage();
			}
			/* convert to a general Velocity ResourceNotFoundException */
			throw new ResourceNotFoundException(msg);
		}
		return result;
	}
	private File getCachedFile(String rootPathString fileName)
	{
		// we do this when we cache a resource,
		// so do it again to ensure a match
		while (fileName.startsWith("/"))
		{
			fileName = fileName.substring(1);
		}
		String savedPath = (String.get(fileName);
		return new File(rootPath + savedPathfileName);
	}

Checks to see if a resource has been deleted, moved or modified.

Parameters:
resource Resource The resource to check for modification
Returns:
boolean True if the resource has been modified
	public boolean isSourceModified(Resource resource)
	{
		String rootPath = .getRealPath("/");
		if (rootPath == null)
		{
			// rootPath is null if the servlet container cannot translate the
			// virtual path to a real path for any reason (such as when the
			// content is being made available from a .war archive)
			return false;
		}
		// first, try getting the previously found file
		String fileName = resource.getName();
		File cachedFile = getCachedFile(rootPathfileName);
		if (!cachedFile.exists())
		{
			/* then the source has been moved and/or deleted */
			return true;
		}
		/*
		 * check to see if the file can now be found elsewhere before it is
		 * found in the previously saved path
		 */
		File currentFile = null;
		for (int i = 0; i < .i++)
		{
			currentFile = new File(rootPath + [i], fileName);
			if (currentFile.canRead())
			{
				/*
				 * stop at the first resource found (just like in
				 * getResourceStream())
				 */
				break;
			}
		}
		/* if the current is the cached and it is readable */
		if (cachedFile.equals(currentFile) && cachedFile.canRead())
		{
			/* then (and only then) do we compare the last modified values */
			return (cachedFile.lastModified() != resource.getLastModified());
		}
		else
		{
			/*
			 * we found a new file for the resource or the resource is no longer
			 * readable.
			 */
			return true;
		}
	}

Checks to see when a resource was last modified

Parameters:
resource Resource the resource to check
Returns:
long The time when the resource was last modified or 0 if the file can't be read
	public long getLastModified(Resource resource)
	{
		String rootPath = .getRealPath("/");
		if (rootPath == null)
		{
			// rootPath is null if the servlet container cannot translate the
			// virtual path to a real path for any reason (such as when the
			// content is being made available from a .war archive)
			return 0;
		}
		File cachedFile = getCachedFile(rootPathresource.getName());
		if (cachedFile.canRead())
		{
			return cachedFile.lastModified();
		}
		else
		{
			return 0;
		}
	}
New to GrepCode? Check out our FAQ X