| 1 | |
package com.aragost.javahg.internals; |
| 2 | |
|
| 3 | |
import com.google.common.io.Closeables; |
| 4 | |
import java.io.BufferedReader; |
| 5 | |
import java.io.InputStreamReader; |
| 6 | |
import java.net.URL; |
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | 0 | public final class ServiceLoader |
| 15 | |
{ |
| 16 | |
|
| 17 | |
private static final String SERVICE_PREFIX = "META-INF/services/"; |
| 18 | |
|
| 19 | |
|
| 20 | |
|
| 21 | |
|
| 22 | |
|
| 23 | |
|
| 24 | |
|
| 25 | |
|
| 26 | |
|
| 27 | |
|
| 28 | |
|
| 29 | |
public static <S> S loadService( Class<S> serviceClass ) throws ServiceException { |
| 30 | 1 | ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); |
| 31 | 1 | if ( classLoader == null ){ |
| 32 | 0 | classLoader = Utils.class.getClassLoader(); |
| 33 | |
} |
| 34 | 1 | return loadService(classLoader, serviceClass); |
| 35 | |
} |
| 36 | |
|
| 37 | |
|
| 38 | |
|
| 39 | |
|
| 40 | |
|
| 41 | |
|
| 42 | |
|
| 43 | |
|
| 44 | |
|
| 45 | |
|
| 46 | |
|
| 47 | |
public static <S> S loadService(ClassLoader classLoader, Class<S> serviceClass ) throws ServiceException{ |
| 48 | 1 | S service = null; |
| 49 | 1 | String name = serviceClass.getName(); |
| 50 | 1 | URL resource = classLoader.getResource(SERVICE_PREFIX.concat(name)); |
| 51 | 1 | if ( resource != null ){ |
| 52 | 0 | BufferedReader reader = null; |
| 53 | |
try { |
| 54 | 0 | reader = new BufferedReader(new InputStreamReader(resource.openStream(), "UTF-8")); |
| 55 | 0 | String line = reader.readLine(); |
| 56 | 0 | while (line != null){ |
| 57 | 0 | int comment = line.indexOf("#"); |
| 58 | 0 | if ( comment >= 0 ){ |
| 59 | 0 | line = line.substring(0, comment); |
| 60 | |
} |
| 61 | 0 | line = line.trim(); |
| 62 | 0 | if ( line.length() > 0 ){ |
| 63 | 0 | service = (S) Class.forName(line).newInstance(); |
| 64 | 0 | break; |
| 65 | |
} |
| 66 | 0 | line = reader.readLine(); |
| 67 | 0 | } |
| 68 | 0 | } catch ( Exception ex ){ |
| 69 | 0 | throw new ServiceException( |
| 70 | |
"could not load service for class ".concat(name), ex); |
| 71 | |
} finally { |
| 72 | 0 | Closeables.closeQuietly(reader); |
| 73 | 0 | } |
| 74 | |
} |
| 75 | 1 | return service; |
| 76 | |
} |
| 77 | |
} |