01: package org.objectweb.celtix.resource;
02:
03: import java.io.InputStream;
04: import java.util.LinkedList;
05: import java.util.List;
06: import java.util.logging.Level;
07: import java.util.logging.Logger;
08:
09: import org.objectweb.celtix.common.logging.LogUtils;
10:
11: public class DefaultResourceManager implements ResourceManager {
12:
13: private static final Logger LOG = LogUtils
14: .getL7dLogger(DefaultResourceManager.class);
15: private static ResourceManager instance;
16:
17: protected final List<ResourceResolver> resolvers = new LinkedList<ResourceResolver>();
18:
19: public DefaultResourceManager() {
20: initializeDefaultResolvers();
21: }
22:
23: public final <T> T resolveResource(String name, Class<T> type) {
24: return findResource(name, type, false);
25: }
26:
27: public final InputStream getResourceAsStream(String name) {
28: return findResource(name, InputStream.class, true);
29: }
30:
31: public final void addResourceResolver(ResourceResolver resolver) {
32: if (!resolvers.contains(resolver)) {
33: resolvers.add(0, resolver);
34: }
35: }
36:
37: public final void removeResourceResolver(ResourceResolver resolver) {
38: if (resolvers.contains(resolver)) {
39: resolvers.remove(resolver);
40: }
41: }
42:
43: public final List getResourceResolvers() {
44: return resolvers;
45: }
46:
47: private <T> T findResource(String name, Class<T> type,
48: boolean asStream) {
49: if (LOG.isLoggable(Level.FINE)) {
50: LOG.fine("resolving resource <"
51: + name
52: + ">"
53: + (asStream ? " as stream " : " type <" + type
54: + ">"));
55: }
56:
57: T ret = null;
58: for (ResourceResolver rr : resolvers) {
59: if (asStream) {
60: ret = type.cast(rr.getAsStream(name));
61: } else {
62: ret = rr.resolve(name, type);
63: }
64: if (ret != null) {
65: break;
66: }
67: }
68: return ret;
69: }
70:
71: public static synchronized ResourceManager instance() {
72: if (instance == null) {
73: instance = new DefaultResourceManager();
74: }
75: return instance;
76: }
77:
78: public static synchronized void clearInstance() {
79: instance = null;
80: }
81:
82: private void initializeDefaultResolvers() {
83: addResourceResolver(new ClasspathResolver());
84: addResourceResolver(new ClassLoaderResolver(getClass()
85: .getClassLoader()));
86: }
87:
88: }
|