org.mmbase.util
Class ResourceLoader

java.lang.Object
  extended byjava.lang.ClassLoader
      extended byorg.mmbase.util.ResourceLoader

public class ResourceLoader
extends ClassLoader

MMBase resource loader, for loading config-files and those kind of things. It knows about MMBase config file locations. I read http://www.javaworld.com/javaqa/2003-08/02-qa-0822-urls.html. Programmers should do something like this if they need a configuration file:

InputStream configStream = ResourceLoader.getConfigurationRoot().getResourceAsStream("modules/myconfiguration.xml");
or
InputSource config = ResourceLoader.getConfigurationRoot().getInputSource("modules/myconfiguration.xml");
of if you need a list of all resources:
ResourceLoader builderLoader = new ResourceLoader("builders");
List list = builderLoader.getResourcePaths(ResourceLoader.XML_PATTERN, true)
When you want to place a configuration file then you have several options, wich are in order of preference:
  1. Place it as on object in 'resources' builder (if such a builder is present)
  2. Place it in the directory identified by the 'mmbase.config' setting (A system property or web.xml setting).
  3. Place it in the directory WEB-INF/config. If this is a real directory (you are not in a war), then the resource will also be returned by getFiles(java.lang.String).
  4. Place it in the class-loader path of your app-server, below the 'org.mmbase.config' package. For tomcat this boils down to the following list (Taken from tomcat 5 class-loader howto)
    1. Bootstrap classes of your JVM
    2. System class loader classses
    3. /WEB-INF/classes of your web application. If this is a real directory (you are not in a war), then the resource will also be returned by getFiles(java.lang.String).
    4. /WEB-INF/lib/*.jar of your web application
    5. $CATALINA_HOME/common/classes
    6. $CATALINA_HOME/common/endorsed/*.jar
    7. $CATALINA_HOME/common/lib/*.jar
    8. $CATALINA_BASE/shared/classes
    9. $CATALINA_BASE/shared/lib/*.jar

Resources which do not reside in the MMBase configuration repository, can also be handled. Those can be resolved relatively to the web root, using getWebRoot().

Resources can programmaticly created or changed by the use of createResourceAsStream(java.lang.String), or something like getWriter(java.lang.String).

If you want to check beforehand if a resource can be changed, then something like resourceLoader.getResource().openConnection().getDoOutput() can be used.

That is also valid if you want to check for existance. resourceLoader.getResource().openConnection().getDoInput().

If you want to remove a resource, you must write null to all URL's returned by findResources(java.lang.String) (Do for every URL:url.openConnection().getOutputStream().write(null);)

Encodings

ResourceLoader is well aware of encodings. You can open XML's as Reader, and this will be done using the encoding specified in the XML itself. When saving an XML using a Writer, this will also be done using the encoding specified in the XML.

For property-files, the java-unicode-escaping is undone on loading, and applied on saving, so there is no need to think of that.

Since:
MMBase-1.8
Version:
$Id: ResourceLoader.java,v 1.37 2006/06/20 20:19:08 michiel Exp $
Author:
Michiel Meeuwissen

Nested Class Summary
protected  class ResourceLoader.ClassLoaderURLStreamHandler
           
protected  class ResourceLoader.FileURLStreamHandler
           
protected  class ResourceLoader.NodeURLStreamHandler
          URLStreamHandler for NodeConnections.
protected  class ResourceLoader.PathURLStreamHandler
          Extension URLStreamHandler, used for the 'sub' Handlers, entries of 'roots' in ResourceLoader are of this type.
protected  class ResourceLoader.ServletResourceURLStreamHandler
          URLStreamHandler based on the servletContext object of ResourceLoader
 
Field Summary
protected static String CLASSLOADER_ROOT
          Used when getting resources with normal class-loader.
static String DEFAULT_CONTEXT
           
static String FILENAME_FIELD
           
static String HANDLE_FIELD
           
protected static String INDEX
          Used when using getResourcePaths for normal class-loaders.
static String LASTMODIFIED_FIELD
           
static URL NODE_URL_CONTEXT
          Protocol prefix used by URL objects in this class.
protected static String PROTOCOL
          Protocol prefix used by URL objects in this class.
protected static String RESOURCE_ROOT
          Used for files, and servlet resources.
static String RESOURCENAME_FIELD
           
static int TYPE_CONFIG
           
static String TYPE_FIELD
           
static int TYPE_WEB
           
static Pattern XML_PATTERN
          Can be used as an argument for getResourcePaths(Pattern, boolean).
 
Constructor Summary
protected ResourceLoader()
          This constructor instantiates a new root resource-loader.
protected ResourceLoader(ResourceLoader cl, String context)
          Instantiates a ResourceLoader for a 'sub directory' of given ResourceLoader.
 
Method Summary
 OutputStream createResourceAsStream(String name)
          If you want to change a resource, or create one, then this method can be used.
 boolean equals(Object o)
           
protected  URL findResource(String name)
          If name starts with '/' or 'mm:/' the 'parent' resourceloader is used.
protected  Enumeration findResources(String name)
          
 Set getChildContexts(Pattern pattern, boolean recursive)
          Returns a set of context strings which can be used to instantiated new ResourceLoaders (resource loaders for directories) (see getChildResourceLoader(String)).
 ResourceLoader getChildResourceLoader(String context)
           
static ResourceLoader getConfigurationRoot()
          Singleton that returns the ResourceLoader for loading mmbase configuration
 URL getContext()
          Returns the 'context' for the ResourceLoader (an URL).
static String getDirectory(String path)
          Utility method to return the 'directory' part of a resource-name.
 Document getDocument(String name)
          Returns the givens resource as a Document (parsed XML).
 Document getDocument(String name, boolean validation, Class baseClass)
          Returns the givens resource as a Document (parsed XML).
static Document getDocument(URL url, boolean validation, Class baseClass)
          Static version of getDocument(String, boolean, Class), can e.g.
 List getFiles(String name)
          Used by ResourceWatcher.
 InputSource getInputSource(String name)
          Returns the givens resource as an InputSource (XML streams).
static InputSource getInputSource(URL url)
          Static version of getInputSource(String), can e.g.
static String getName(String path)
          Utility method to return the name part of a resource-name (removed directory and 'extension').
 ResourceLoader getParentResourceLoader()
          Returns the 'parent' ResourceLoader.
 Reader getReader(String name)
          Returns a reader for a given resource.
 List getResourceList(String name)
          Returns a List, containing all URL's which may represent the given resource.
 Set getResourcePaths(Pattern pattern, boolean recursive)
          Returns a set of 'sub resources' (read: 'files in the same directory'), which can succesfully be loaded by the ResourceLoader.
protected  Set getResourcePaths(Pattern pattern, boolean recursive, boolean directories)
          Used by getResourcePaths(Pattern, boolean) and getChildContexts(Pattern, boolean)
static ResourceLoader getSystemRoot()
          Singleton that returns the ResourceLoader for loading from the file-system, relative from current working directory and falling back to the file system roots.
static ResourceLoader getWebDirectory(HttpServletRequest request)
          Returns the resource loader associated with the directory of the given request
static ResourceLoader getWebRoot()
          Singleton that returns the ResourceLoader for witch the base path is the web root
 Writer getWriter(String name)
          Returns a writer for a given resource, so that you can overwrite or create it.
 int hashCode()
           
static void init(ServletContext sc)
          Initializes the Resourceloader using a servlet-context (makes resolving relatively to WEB-INF/config possible).
static void main(String[] argv)
          For testing purposes only
protected  URL newURL(String url)
          Creates a new URL object, which is used to load resources.
static void setResourceBuilder(NodeManager b)
          Sets the MMBase builder which must be used for resource.
 void storeDocument(String name, Document doc)
          Creates a resource for a given Document.
 void storeSource(String name, Source source, DocumentType docType)
          Creates a resource with given name for given Source.
 String toInternalForm(String name)
          Returns an abstract URL for a resource with given name, findResource(name).toString() would give an 'external' form.
static String toInternalForm(URL u)
           
 String toString()
           
 
Methods inherited from class java.lang.ClassLoader
clearAssertionStatus, defineClass, defineClass, defineClass, definePackage, findClass, findLibrary, findLoadedClass, findSystemClass, getPackage, getPackages, getParent, getResource, getResourceAsStream, getResources, getSystemClassLoader, getSystemResource, getSystemResourceAsStream, getSystemResources, loadClass, loadClass, resolveClass, setClassAssertionStatus, setDefaultAssertionStatus, setPackageAssertionStatus, setSigners
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

PROTOCOL

protected static final String PROTOCOL
Protocol prefix used by URL objects in this class.

See Also:
Constant Field Values

RESOURCE_ROOT

protected static final String RESOURCE_ROOT
Used for files, and servlet resources.

See Also:
Constant Field Values

CLASSLOADER_ROOT

protected static final String CLASSLOADER_ROOT
Used when getting resources with normal class-loader.

See Also:
Constant Field Values

NODE_URL_CONTEXT

public static final URL NODE_URL_CONTEXT
Protocol prefix used by URL objects in this class.


INDEX

protected static final String INDEX
Used when using getResourcePaths for normal class-loaders.

See Also:
Constant Field Values

RESOURCENAME_FIELD

public static final String RESOURCENAME_FIELD
See Also:
Constant Field Values

TYPE_FIELD

public static final String TYPE_FIELD
See Also:
Constant Field Values

FILENAME_FIELD

public static final String FILENAME_FIELD
See Also:
Constant Field Values

HANDLE_FIELD

public static final String HANDLE_FIELD
See Also:
Constant Field Values

LASTMODIFIED_FIELD

public static final String LASTMODIFIED_FIELD
See Also:
Constant Field Values

DEFAULT_CONTEXT

public static final String DEFAULT_CONTEXT
See Also:
Constant Field Values

TYPE_CONFIG

public static final int TYPE_CONFIG
See Also:
Constant Field Values

TYPE_WEB

public static final int TYPE_WEB
See Also:
Constant Field Values

XML_PATTERN

public static final Pattern XML_PATTERN
Can be used as an argument for getResourcePaths(Pattern, boolean). MMBase works mainly with xml configuration files, so this comes in handy.

Constructor Detail

ResourceLoader

protected ResourceLoader()
This constructor instantiates a new root resource-loader. This constructor is protected (so you may use it in an extension), but normally use: getConfigurationRoot() or getWebRoot().


ResourceLoader

protected ResourceLoader(ResourceLoader cl,
                         String context)
Instantiates a ResourceLoader for a 'sub directory' of given ResourceLoader. Used by getChildResourceLoader(java.lang.String).

Method Detail

newURL

protected URL newURL(String url)
              throws MalformedURLException
Creates a new URL object, which is used to load resources. First a normal java.net.URL is instantiated, if that fails, we check for the 'mmbase' protocol. If so, a URL is instantiated with a URLStreamHandler which can handle that. If that too fails, it should actually already be a MalformedURLException, but we try supposing it is some existing file and return a file: URL. If no such file, only then a MalformedURLException is thrown.

Throws:
MalformedURLException

init

public static void init(ServletContext sc)
Initializes the Resourceloader using a servlet-context (makes resolving relatively to WEB-INF/config possible).

Parameters:
sc - The ServletContext used for determining the mmbase configuration directory. Or null.

setResourceBuilder

public static void setResourceBuilder(NodeManager b)
Sets the MMBase builder which must be used for resource. The builder must have an URL and a HANDLE field. This method can be called only once.

Parameters:
b - An MMObjectBuilder (this may be null if no such builder available)
Throws:
RuntimeException - if builder was set already.

getName

public static String getName(String path)
Utility method to return the name part of a resource-name (removed directory and 'extension'). Used e.g. when loading builders in MMBase.


getDirectory

public static String getDirectory(String path)
Utility method to return the 'directory' part of a resource-name. Used e.g. when loading builders in MMBase.


getConfigurationRoot

public static ResourceLoader getConfigurationRoot()
Singleton that returns the ResourceLoader for loading mmbase configuration


getSystemRoot

public static ResourceLoader getSystemRoot()
Singleton that returns the ResourceLoader for loading from the file-system, relative from current working directory and falling back to the file system roots. This can be used in command-line tools and such. In a servlet environment you should use either getConfigurationRoot() or getWebRoot().


getWebRoot

public static ResourceLoader getWebRoot()
Singleton that returns the ResourceLoader for witch the base path is the web root


getWebDirectory

public static ResourceLoader getWebDirectory(HttpServletRequest request)
Returns the resource loader associated with the directory of the given request


findResource

protected URL findResource(String name)
If name starts with '/' or 'mm:/' the 'parent' resourceloader is used. Otherwise the name is resolved relatively. (For the root ResourceLoader that is the same as starting with /)


findResources

protected Enumeration findResources(String name)
                             throws IOException

Throws:
IOException
See Also:
getResourceList(java.lang.String)

getResourceList

public List getResourceList(String name)
Returns a List, containing all URL's which may represent the given resource. This can be used to show what resource whould be loaded and what resource whould be masked, or one can also simply somehow 'merge' all these resources.


getContext

public URL getContext()
Returns the 'context' for the ResourceLoader (an URL).


getParentResourceLoader

public ResourceLoader getParentResourceLoader()
Returns the 'parent' ResourceLoader. Or null if this ClassLoader has no parent. You can create a ResourceLoader with a parent by getChildResourceLoader(String).


getChildResourceLoader

public ResourceLoader getChildResourceLoader(String context)
Parameters:
context - a context relative to the current resource loader
Returns:
a new 'child' ResourceLoader or the parent ResourceLoader if the context is ".."
See Also:
ResourceLoader(ResourceLoader, String)

getResourcePaths

public Set getResourcePaths(Pattern pattern,
                            boolean recursive)
Returns a set of 'sub resources' (read: 'files in the same directory'), which can succesfully be loaded by the ResourceLoader.

Parameters:
pattern - A Regular expression pattern to which the file-name must match, or null if no restrictions apply
recursive - If true, then also subdirectories are searched.
Returns:
A Set of Strings which can be successfully loaded with the resourceloader.

getChildContexts

public Set getChildContexts(Pattern pattern,
                            boolean recursive)
Returns a set of context strings which can be used to instantiated new ResourceLoaders (resource loaders for directories) (see getChildResourceLoader(String)).

Parameters:
pattern - A Regular expression pattern to which the file-name must match, or null if no restrictions apply
recursive - If true, then also subdirectories are searched.

getResourcePaths

protected Set getResourcePaths(Pattern pattern,
                               boolean recursive,
                               boolean directories)
Used by getResourcePaths(Pattern, boolean) and getChildContexts(Pattern, boolean)

Parameters:
pattern - A Regular expression pattern to which the file-name must match, or null if no restrictions apply
recursive - If true, then also subdirectories are searched.
directories - getResourceContext supplies true getResourcePaths supplies false

createResourceAsStream

public OutputStream createResourceAsStream(String name)
                                    throws IOException
If you want to change a resource, or create one, then this method can be used. Specify the desired resource-name and you get an OutputStream back, to which you must write. This is a shortcut to findResource(name).openConnection().getOutputStream() If the given resource already existed, it will be overwritten, or shadowed, if it was not writeable.

Throws:
IOException - If the Resource for some reason could not be created.

getInputSource

public InputSource getInputSource(String name)
                           throws IOException
Returns the givens resource as an InputSource (XML streams). ResourceLoader is often used for XML. The System ID is set, otherwise you could as wel do new InputSource(r.getResourceAsStream());

Parameters:
name - The name of the resource to be loaded
Returns:
The InputSource if succesfull, null otherwise.
Throws:
IOException

getInputSource

public static InputSource getInputSource(URL url)
                                  throws IOException
Static version of getInputSource(String), can e.g. be used in combination with getResourceList(String)

Throws:
IOException

getDocument

public Document getDocument(String name)
                     throws SAXException,
                            IOException
Returns the givens resource as a Document (parsed XML). This can come in handly, because most configuration in in XML.

Parameters:
name - The name of the resource to be loaded
Returns:
The Document if succesful, null if there is no such resource.
Throws:
SAXException - If the resource does not present parseable XML.
IOException

getDocument

public Document getDocument(String name,
                            boolean validation,
                            Class baseClass)
                     throws SAXException,
                            IOException
Returns the givens resource as a Document (parsed XML). This can come in handly, because most configuration in in XML.

Parameters:
name - The name of the resource to be loaded
validation - If true, validate the xml. By dtd if one of the first lines starts with <!DOCTYPE, by XSD otherwise
baseClass - If validation is true, the base class to serach for the validating xsd or dtd
Returns:
The Document if succesful, null if there is no such resource.
Throws:
SAXException - If the resource does not present parseable XML.
IOException

getDocument

public static Document getDocument(URL url,
                                   boolean validation,
                                   Class baseClass)
                            throws SAXException,
                                   IOException
Static version of getDocument(String, boolean, Class), can e.g. be used in combination with getResourceList(String)

Throws:
SAXException
IOException

storeSource

public void storeSource(String name,
                        Source source,
                        DocumentType docType)
                 throws IOException
Creates a resource with given name for given Source.

Parameters:
docType - Document which must be used, or null if none.
Throws:
IOException
See Also:
createResourceAsStream(String)

storeDocument

public void storeDocument(String name,
                          Document doc)
                   throws IOException
Creates a resource for a given Document.

Parameters:
name - Name of the resource.
doc - The xml document which must be stored.
Throws:
IOException
See Also:
createResourceAsStream(String)

getReader

public Reader getReader(String name)
                 throws IOException
Returns a reader for a given resource. This performs the tricky task of finding the encoding. Resources are actually InputStreams (byte arrays), but often they are quite text-oriented (like e.g. XML's or property-files), so this method may be useful. A resource is supposed to be a property-file if it's name ends in ".properties", it is supposed to be XML if it's content starts with <?xml.

Throws:
IOException
See Also:
ClassLoader.getResourceAsStream(String)

getWriter

public Writer getWriter(String name)
                 throws IOException
Returns a writer for a given resource, so that you can overwrite or create it. This performs the tricky task of serializing to the right encoding. It supports the same tricks as getReader(java.lang.String), but then inversed.

Throws:
IOException
See Also:
getReader(String), createResourceAsStream(String)

toInternalForm

public String toInternalForm(String name)
Returns an abstract URL for a resource with given name, findResource(name).toString() would give an 'external' form.


toInternalForm

public static String toInternalForm(URL u)

getFiles

public List getFiles(String name)
Used by ResourceWatcher. And by some deprecated code that wants to produce File objects.

Returns:
A List of all files associated with the resource.

toString

public String toString()
See Also:
Object.toString()

equals

public boolean equals(Object o)
See Also:
Object.equals(java.lang.Object)

hashCode

public int hashCode()
See Also:
Object.hashCode()

main

public static void main(String[] argv)
For testing purposes only



MMBase build 1.8.1.20060716