[Adapdev-commits] Adapdev/src/Adapdev.NVelocity/Runtime/Resource/Loader FileResourceLoader.cs,1.4,1.
Status: Beta
Brought to you by:
intesar66
From: Sean M. <int...@us...> - 2005-11-16 07:02:00
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Resource/Loader In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Runtime/Resource/Loader Added Files: FileResourceLoader.cs ResourceLoader.cs ResourceLoaderFactory.cs ResourceLocator.cs Log Message: --- NEW FILE: ResourceLocator.cs --- namespace NVelocity.Runtime.Resource.Loader { using System; using System.Collections; using System.IO; using System.Reflection; /// <summary> /// Locates a resource (file) in the file system or as a resource in an assembly. /// </summary> public class ResourceLocator { private String filename = String.Empty; private FileInfo file = null; private Boolean isFile = false; private Boolean isResource = false; private IList assemblies = new ArrayList(); private Assembly assembly = null; public ResourceLocator(String filename) { this.filename = filename; file = new FileInfo(this.filename); if (file.Exists) { this.filename = file.FullName; isFile = true; } else { // the calling Executing and Entry assemblies may not have links to each other - // so attempt to get assemblies from all possible paths. GetReferencedAssemblies(Assembly.GetExecutingAssembly(), assemblies); if (Assembly.GetEntryAssembly() != null) { GetReferencedAssemblies(Assembly.GetEntryAssembly(), assemblies); } if (Assembly.GetCallingAssembly() != null) { GetReferencedAssemblies(Assembly.GetCallingAssembly(), assemblies); } String fn = filename.ToLower().Replace(".\\", ""); fn = fn.Replace("\\", "."); fn = fn.Replace("/", "."); foreach (Assembly a in assemblies) { String prefix = a.FullName.Substring(0, a.FullName.IndexOf(",")).ToLower(); String[] names = a.GetManifestResourceNames(); foreach (String s in names) { if (s.ToLower().Equals(fn) || s.ToLower().Equals(prefix + "." + fn)) { this.filename = s; assembly = a; isResource = true; } } } } } public static void GetReferencedAssemblies(Assembly a, IList list) { String s = a.GetName().FullName; foreach (AssemblyName an in a.GetReferencedAssemblies()) { Assembly c = Assembly.Load(an); if (!list.Contains(c)) { list.Add(c); GetReferencedAssemblies(c, list); } } if (!list.Contains(a)) { list.Add(a); } } public Stream OpenRead() { if (isFile) { return file.OpenRead(); } else if (isResource) { return assembly.GetManifestResourceStream(filename); } else { throw new FileNotFoundException("Resource could not be found", filename); } } public String FullName { get { return this.filename; } } public Boolean Exists { get { return (isFile || isResource); } } private Stream FindResource(String path, String template) { try { FileInfo file = new FileInfo(path + "\\" + template); if (file.Exists) { return new BufferedStream(new FileStream(file.FullName, FileMode.Open, FileAccess.Read)); } else { IList list = new ArrayList(); GetReferencedAssemblies(Assembly.GetEntryAssembly(), list); foreach (Assembly a in list) { Stream s = a.GetManifestResourceStream(template); if (s != null) { return s; } } return null; } } catch (FileNotFoundException fnfe) { /* * log and convert to a general Velocity ResourceNotFoundException */ return null; } } } } --- NEW FILE: ResourceLoader.cs --- namespace NVelocity.Runtime.Resource.Loader { using System; using System.IO; using Commons.Collections; /// <summary> /// This is abstract class the all text resource loaders should extend. /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a></author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <version> $Id: ResourceLoader.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $</version> public abstract class ResourceLoader { public virtual String ClassName { get { return className; } } public virtual bool CachingOn { set { isCachingOn_Renamed_Field = value; } } public virtual long ModificationCheckInterval { get { return modificationCheckInterval; } set { this.modificationCheckInterval = value; } } /// /// <summary> Does this loader want templates produced with it /// cached in the Runtime. /// </summary> protected internal bool isCachingOn_Renamed_Field = false; /// <summary> This property will be passed on to the templates /// that are created with this loader. /// </summary> protected internal long modificationCheckInterval = 2; /// <summary> Class name for this loader, for logging/debuggin /// purposes. /// </summary> protected internal String className = null; protected internal RuntimeServices rsvc = null; /// <summary> This initialization is used by all resource /// loaders and must be called to set up common /// properties shared by all resource loaders /// </summary> public virtual void commonInit(RuntimeServices rs, ExtendedProperties configuration) { this.rsvc = rs; /* * these two properties are not required for all loaders. * For example, for ClasspathLoader, what would cache mean? * so adding default values which I think are the safest * * don't cache, and modCheckInterval irrelevant... */ isCachingOn_Renamed_Field = configuration.GetBoolean("cache", false); modificationCheckInterval = configuration.GetLong("modificationCheckInterval", 0); /* * this is a must! */ className = configuration.GetString("class"); } /// /// <summary> Initialize the template loader with a /// a resources class. /// </summary> public abstract void init(ExtendedProperties configuration); /// /// <summary> Get the InputStream that the Runtime will parse /// to create a template. /// </summary> public abstract Stream getResourceStream(String source); /// <summary> Given a template, check to see if the source of InputStream /// has been modified. /// </summary> public abstract bool isSourceModified(Resource resource); /// <summary> Get the last modified time of the InputStream source /// that was used to create the template. We need the template /// here because we have to extract the name of the template /// in order to locate the InputStream source. /// </summary> public abstract long getLastModified(Resource resource); /// <summary> Return the class name of this resource Loader /// </summary> /// <summary> Set the caching state. If true, then this loader /// would like the Runtime to cache templates that /// have been created with InputStreams provided /// by this loader. /// </summary> /// <summary> The Runtime uses this to find out whether this /// template loader wants the Runtime to cache /// templates created with InputStreams provided /// by this loader. /// </summary> public virtual bool isCachingOn() { return isCachingOn_Renamed_Field; } /// <summary> Set the interval at which the InputStream source /// should be checked for modifications. /// </summary> /// <summary> Get the interval at which the InputStream source /// should be checked for modifications. /// </summary> } } --- NEW FILE: FileResourceLoader.cs --- /* 122704 SMM Removed code that calls StringUtils.normalizepath, since it caused the parse directive not to work correctly */ namespace NVelocity.Runtime.Resource.Loader { using System; using System.Collections; using System.IO; using Commons.Collections; using NVelocity.Exception; using NVelocity.Util; /// <summary> /// A loader for templates stored on the file system. /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> </author> public class FileResourceLoader : ResourceLoader { /// <summary> /// The paths to search for templates. /// </summary> protected ArrayList paths = null; /// <summary> /// Used to map the path that a template was found on /// so that we can properly check the modification /// times of the files. /// </summary> protected Hashtable templatePaths = new Hashtable(); public FileResourceLoader() { } public override void init(ExtendedProperties configuration) { rsvc.info("FileResourceLoader : initialization starting."); paths = configuration.GetVector("path"); // lets tell people what paths we will be using foreach (String path in paths) { rsvc.info("FileResourceLoader : adding path '" + path + "'"); } rsvc.info("FileResourceLoader : initialization complete."); } /// <summary> /// Get an InputStream so that the Runtime can build a /// template with it. /// </summary> /// <param name="name">name of template to get</param> /// <returns>InputStream containing the template /// @throws ResourceNotFoundException if template not found /// in the file template path. /// </returns> public override Stream getResourceStream(String templateName) { lock (this) { String template = null; int size = paths.Count; for (int i = 0; i < size; i++) { String path = (String) paths[i]; // Make sure we have a valid templateName. if (templateName == null || templateName.Length == 0) { // If we don't get a properly formed templateName // then there's not much we can do. So // we'll forget about trying to search // any more paths for the template. throw new ResourceNotFoundException("Need to specify a file name or file path!"); } // template = StringUtils.normalizePath(templateName); // if (template == null || template.Length == 0) // { // String msg = "File resource error : argument " + template + " contains .. and may be trying to access " + "content outside of template root. Rejected."; // // rsvc.error("FileResourceLoader : " + msg); // // throw new ResourceNotFoundException(msg); // } // if a / leads off, then just nip that :) // if (template.StartsWith("/")) // { // template = template.Substring(1); // } Stream inputStream = findTemplate(templateName); if (inputStream != null) { // Store the path that this template came // from so that we can check its modification // time. SupportClass.PutElement(templatePaths, templateName, path); return inputStream; } } // We have now searched all the paths for // templates and we didn't find anything so // throw an exception. String msg2 = "FileResourceLoader Error: cannot find resource " + template; throw new ResourceNotFoundException(msg2); } } /// <summary> /// Try to find a template given a normalized path. /// </summary> /// <param name="String">a normalized path</param> /// <returns>InputStream input stream that will be parsed</returns> private Stream findTemplate(String template) { try { ResourceLocator rl = new ResourceLocator(template); if (rl.Exists) { return new BufferedStream(rl.OpenRead()); } else { return null; } } catch (FileNotFoundException fnfe) { // log and convert to a general Velocity ResourceNotFoundException return null; } } /// <summary> /// How to keep track of all the modified times /// across the paths. /// </summary> public override bool isSourceModified(Resource resource) { String path = (String) templatePaths[resource.Name]; FileInfo file = new FileInfo(path + "\\" + resource.Name); if (file.Exists) { if (file.LastWriteTime.Ticks != resource.LastModified) { return true; } else { return false; } } // If the file is now unreadable, or it has // just plain disappeared then we'll just say // that it's modified :-) When the loader attempts // to load the stream it will fail and the error // will be reported then. return true; } public override long getLastModified(Resource resource) { String path = (String) templatePaths[resource.Name]; FileInfo file = new FileInfo(resource.Name); if (file.Exists) { return file.LastWriteTime.Ticks; } else { return 0; } } } } --- NEW FILE: ResourceLoaderFactory.cs --- namespace NVelocity.Runtime.Resource.Loader { using System; using NVelocity.Util; /// <summary> /// Factory to grab a template loader. /// </summary> /// <author><a href="mailto:jv...@ap...">Jason van Zyl</a></author> public class ResourceLoaderFactory { /// <summary> /// Gets the loader specified in the configuration file. /// </summary> /// <returns>TemplateLoader</returns> public static ResourceLoader getLoader(RuntimeServices rs, String loaderClassName) { ResourceLoader loader = null; try { // since properties are parsed into arrays with commas, something else needed to be used loaderClassName = loaderClassName.Replace(';', ','); Type loaderType = Type.GetType(loaderClassName); Object o = Activator.CreateInstance(loaderType); loader = (ResourceLoader) o; rs.info("Resource Loader Instantiated: " + loader.GetType().FullName); return loader; } catch (Exception e) { rs.error("Problem instantiating the template loader.\n" + "Look at your properties file and make sure the\n" + "name of the template loader is correct. Here is the\n" + "error: " + StringUtils.stackTrace(e)); throw new Exception("Problem initializing template loader: " + loaderClassName + "\nError is: " + StringUtils.stackTrace(e)); } } } } |