1 17 18 package org.apache.avalon.fortress.util; 19 20 import java.io.BufferedReader; 21 import java.io.IOException; 22 import java.io.InputStream; 23 import java.io.InputStreamReader; 24 import java.net.URL; 25 import java.util.*; 26 27 40 public final class Service 41 { 42 private static final String SERVICES = "META-INF/services/"; 43 private static final HashMap providers = new HashMap(); 44 45 48 private Service() 49 { 50 } 51 52 60 public static synchronized Iterator providers( final Class klass, ClassLoader loader ) 61 { 62 final String serviceFile = SERVICES + klass.getName(); 63 64 if ( null == loader ) 65 { 66 loader = klass.getClassLoader(); 67 } 68 69 Set providerSet = (Set) providers.get( serviceFile ); 70 71 if ( null == providerSet ) 72 { 73 providerSet = new HashSet(); 74 Enumeration enum = null; 75 boolean errorOccurred = false; 76 77 providers.put( serviceFile, providerSet ); 78 79 try 80 { 81 enum = loader.getResources( serviceFile ); 82 } 83 catch ( IOException ioe ) 84 { 85 errorOccurred = true; 86 } 87 88 if ( !errorOccurred ) 89 { 90 while ( enum.hasMoreElements() ) 91 { 92 try 93 { 94 final URL url = (URL) enum.nextElement(); 95 final InputStream is = url.openStream(); 96 final BufferedReader reader = new BufferedReader( 97 new InputStreamReader( is, 98 "UTF-8" ) ); 99 100 String line = reader.readLine(); 101 while ( null != line ) 102 { 103 try 104 { 105 final int comment = line.indexOf( '#' ); 106 107 if ( comment > -1 ) 108 { 109 line = line.substring( 0, comment ); 110 } 111 112 line.trim(); 113 114 if ( line.length() > 0 ) 115 { 116 providerSet.add( loader.loadClass( line ) ); 118 } 119 } 120 catch ( Exception e ) 121 { 122 } 124 125 line = reader.readLine(); 126 } 127 } 128 catch ( Exception e ) 129 { 130 } 132 } 133 } 134 } 135 136 return providerSet.iterator(); 137 } 138 139 146 public static synchronized Iterator providers( final Class klass ) 147 { 148 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 149 150 return providers( klass, loader ); 151 } 152 } 153 | Popular Tags |