001
014
015 package com.liferay.portal.kernel.util;
016
017 import com.liferay.portal.kernel.log.Log;
018 import com.liferay.portal.kernel.log.LogFactoryUtil;
019
020 import java.io.BufferedReader;
021 import java.io.InputStream;
022 import java.io.InputStreamReader;
023
024 import java.lang.reflect.Constructor;
025
026 import java.net.URL;
027
028 import java.util.ArrayList;
029 import java.util.Enumeration;
030 import java.util.List;
031
032
037 public class ServiceLoader {
038
039 public static <S> List<S> load(Class<S> clazz) throws Exception {
040 return load(clazz, _serviceLoaderCondition);
041 }
042
043 public static <S> List<S> load(
044 Class<S> clazz, ServiceLoaderCondition serviceLoaderCondition)
045 throws Exception {
046
047 Thread currentThread = Thread.currentThread();
048
049 ClassLoader classLoader = currentThread.getContextClassLoader();
050
051 return load(classLoader, clazz, serviceLoaderCondition);
052 }
053
054 public static <S> List<S> load(ClassLoader classLoader, Class<S> clazz)
055 throws Exception {
056
057 return load(classLoader, clazz, _serviceLoaderCondition);
058 }
059
060 public static <S> List<S> load(
061 ClassLoader classLoader, Class<S> clazz,
062 ServiceLoaderCondition serviceLoaderCondition)
063 throws Exception {
064
065 Enumeration<URL> enu = classLoader.getResources(
066 "META-INF/services/" + clazz.getName());
067
068 List<S> services = new ArrayList<>();
069
070 while (enu.hasMoreElements()) {
071 URL url = enu.nextElement();
072
073 if (!serviceLoaderCondition.isLoad(url)) {
074 continue;
075 }
076
077 try {
078 _load(services, classLoader, clazz, url);
079 }
080 catch (Exception e) {
081 _log.error(
082 "Unable to load " + clazz + " with " + classLoader, e);
083 }
084 }
085
086 return services;
087 }
088
089 private static <S> void _load(
090 List<S> services, ClassLoader classLoader, Class<S> clazz, URL url)
091 throws Exception {
092
093 try (InputStream inputStream = url.openStream()) {
094 BufferedReader bufferedReader = new BufferedReader(
095 new InputStreamReader(inputStream, StringPool.UTF8));
096
097 while (true) {
098 String line = bufferedReader.readLine();
099
100 if (line == null) {
101 break;
102 }
103
104 int comment = line.indexOf(CharPool.POUND);
105
106 if (comment >= 0) {
107 line = line.substring(0, comment);
108 }
109
110 String name = line.trim();
111
112 if (name.length() == 0) {
113 continue;
114 }
115
116 Class<?> serviceClass = Class.forName(name, true, classLoader);
117
118 Class<? extends S> serviceImplClass = serviceClass.asSubclass(
119 clazz);
120
121 Constructor<? extends S> constructor =
122 serviceImplClass.getConstructor();
123
124 S service = constructor.newInstance();
125
126 services.add(service);
127 }
128 }
129 }
130
131 private static final Log _log = LogFactoryUtil.getLog(ServiceLoader.class);
132
133 private static final ServiceLoaderCondition _serviceLoaderCondition =
134 new DefaultServiceLoaderCondition();
135
136 }