1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.discovery.resource;
18
19 import java.io.IOException;
20 import java.net.URL;
21 import java.util.Enumeration;
22
23 import org.apache.commons.discovery.Resource;
24 import org.apache.commons.discovery.ResourceDiscover;
25 import org.apache.commons.discovery.ResourceIterator;
26 import org.apache.commons.discovery.jdk.JDKHooks;
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29
30
31
32 public class DiscoverResources extends ResourceDiscoverImpl implements ResourceDiscover {
33
34 private static Log log = LogFactory.getLog(DiscoverResources.class);
35
36
37
38
39
40
41
42 @Deprecated
43 public static void setLog(Log _log) {
44 log = _log;
45 }
46
47
48
49
50 public DiscoverResources() {
51 super();
52 }
53
54
55
56
57
58
59 public DiscoverResources(ClassLoaders classLoaders) {
60 super(classLoaders);
61 }
62
63
64
65
66 @Override
67 public ResourceIterator findResources(final String resourceName) {
68 if (log.isDebugEnabled()) {
69 log.debug("find: resourceName='" + resourceName + "'");
70 }
71
72 return new ResourceIterator() {
73
74 private int idx = 0;
75
76 private ClassLoader loader = null;
77
78 private Enumeration<URL> resources = null;
79
80 private Resource resource = null;
81
82 public boolean hasNext() {
83 if (resource == null) {
84 resource = getNextResource();
85 }
86 return resource != null;
87 }
88
89 @Override
90 public Resource nextResource() {
91 Resource element = resource;
92 resource = null;
93 return element;
94 }
95
96 private Resource getNextResource() {
97 if (resources == null || !resources.hasMoreElements()) {
98 resources = getNextResources();
99 }
100
101 Resource resourceInfo;
102 if (resources != null) {
103 URL url = resources.nextElement();
104
105 if (log.isDebugEnabled()) {
106 log.debug("getNextResource: next URL='" + url + "'");
107 }
108
109 resourceInfo = new Resource(resourceName, url, loader);
110 } else {
111 resourceInfo = null;
112 }
113
114 return resourceInfo;
115 }
116
117 private Enumeration<URL> getNextResources() {
118 while (idx < getClassLoaders().size()) {
119 loader = getClassLoaders().get(idx++);
120 if (log.isDebugEnabled()) {
121 log.debug("getNextResources: search using ClassLoader '" + loader + "'");
122 }
123 try {
124 Enumeration<URL> e = JDKHooks.getJDKHooks().getResources(loader, resourceName);
125 if (e != null && e.hasMoreElements()) {
126 return e;
127 }
128 } catch( IOException ex ) {
129 log.warn("getNextResources: Ignoring Exception", ex);
130 }
131 }
132 return null;
133 }
134 };
135 }
136
137 }