KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hudson > util > Service


1 package hudson.util;
2
3 import java.io.BufferedReader JavaDoc;
4 import java.io.IOException JavaDoc;
5 import java.io.InputStreamReader JavaDoc;
6 import java.net.URL JavaDoc;
7 import java.util.Collection JavaDoc;
8 import java.util.Enumeration JavaDoc;
9 import java.util.logging.Level JavaDoc;
10 import java.util.logging.Logger JavaDoc;
11
12 /**
13  * Load classes by looking up <tt>META-INF/services</tt>.
14  *
15  * @author Kohsuke Kawaguchi
16  */

17 public class Service {
18     /**
19      * Look up <tt>META-INF/service/<i>SPICLASSNAME</i></tt> from the classloader
20      * and all the discovered classes into the given collection.
21      */

22     public static <T> void load(Class JavaDoc<T> spi, ClassLoader JavaDoc cl, Collection JavaDoc<Class JavaDoc<? extends T>> result) {
23         try {
24             Enumeration JavaDoc<URL JavaDoc> e = cl.getResources("META-INF/services/" + spi.getName());
25             while(e.hasMoreElements()) {
26                 BufferedReader JavaDoc r = null;
27                 URL JavaDoc url = e.nextElement();
28                 try {
29                     r = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(url.openStream(),"UTF-8"));
30                     String JavaDoc line;
31                     while((line=r.readLine())!=null) {
32                         if(line.startsWith("#"))
33                             continue; // comment line
34
line = line.trim();
35                         if(line.length()==0)
36                             continue; // empty line. ignore.
37

38                         try {
39                             result.add(cl.loadClass(line).asSubclass(spi));
40                         } catch (ClassNotFoundException JavaDoc x) {
41                             LOGGER.log(Level.WARNING, "Failed to load "+line, x);
42                         }
43                     }
44                 } catch (IOException JavaDoc x) {
45                     LOGGER.log(Level.WARNING, "Failed to load "+url, x);
46                 } finally {
47                     r.close();
48                 }
49             }
50         } catch (IOException JavaDoc x) {
51             LOGGER.log(Level.WARNING, "Failed to look up service providers for "+spi, x);
52         }
53     }
54
55     private static final Logger JavaDoc LOGGER = Logger.getLogger(Service.class.getName());
56 }
57
Popular Tags