You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AbstractExtensionFinder.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. /*
  2. * Copyright (C) 2012-present the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.pf4j;
  17. import org.pf4j.asm.ExtensionInfo;
  18. import org.pf4j.util.ClassUtils;
  19. import org.slf4j.Logger;
  20. import org.slf4j.LoggerFactory;
  21. import java.lang.annotation.Annotation;
  22. import java.util.ArrayList;
  23. import java.util.Collections;
  24. import java.util.HashMap;
  25. import java.util.LinkedHashMap;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.Set;
  29. /**
  30. * @author Decebal Suiu
  31. */
  32. public abstract class AbstractExtensionFinder implements ExtensionFinder, PluginStateListener {
  33. private static final Logger log = LoggerFactory.getLogger(AbstractExtensionFinder.class);
  34. protected PluginManager pluginManager;
  35. protected volatile Map<String, Set<String>> entries; // cache by pluginId
  36. protected volatile Map<String, ExtensionInfo> extensionInfos; // cache extension infos by class name
  37. protected Boolean checkForExtensionDependencies = null;
  38. protected AbstractExtensionFinder(PluginManager pluginManager) {
  39. this.pluginManager = pluginManager;
  40. }
  41. public abstract Map<String, Set<String>> readPluginsStorages();
  42. public abstract Map<String, Set<String>> readClasspathStorages();
  43. @Override
  44. public <T> List<ExtensionWrapper<T>> find(Class<T> type) {
  45. log.debug("Finding extensions of extension point '{}'", type.getName());
  46. Map<String, Set<String>> entries = getEntries();
  47. List<ExtensionWrapper<T>> result = new ArrayList<>();
  48. // add extensions found in classpath and plugins
  49. for (String pluginId : entries.keySet()) {
  50. // classpath's extensions <=> pluginId = null
  51. List<ExtensionWrapper<T>> pluginExtensions = find(type, pluginId);
  52. result.addAll(pluginExtensions);
  53. }
  54. if (result.isEmpty()) {
  55. log.debug("No extensions found for extension point '{}'", type.getName());
  56. } else {
  57. log.debug("Found {} extensions for extension point '{}'", result.size(), type.getName());
  58. }
  59. // sort by "ordinal" property
  60. Collections.sort(result);
  61. return result;
  62. }
  63. @Override
  64. @SuppressWarnings("unchecked")
  65. public <T> List<ExtensionWrapper<T>> find(Class<T> type, String pluginId) {
  66. log.debug("Finding extensions of extension point '{}' for plugin '{}'", type.getName(), pluginId);
  67. List<ExtensionWrapper<T>> result = new ArrayList<>();
  68. // classpath's extensions <=> pluginId = null
  69. Set<String> classNames = findClassNames(pluginId);
  70. if (classNames.isEmpty()) {
  71. return result;
  72. }
  73. if (pluginId != null) {
  74. PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginId);
  75. if (PluginState.STARTED != pluginWrapper.getPluginState()) {
  76. return result;
  77. }
  78. log.trace("Checking extensions from plugin '{}'", pluginId);
  79. } else {
  80. log.trace("Checking extensions from classpath");
  81. }
  82. ClassLoader classLoader = (pluginId != null) ? pluginManager.getPluginClassLoader(pluginId) : getClass().getClassLoader();
  83. for (String className : classNames) {
  84. try {
  85. if (isCheckForExtensionDependencies()) {
  86. // Load extension annotation without initializing the class itself.
  87. //
  88. // If optional dependencies are used, the class loader might not be able
  89. // to load the extension class because of missing optional dependencies.
  90. //
  91. // Therefore we're extracting the extension annotation via asm, in order
  92. // to extract the required plugins for an extension. Only if all required
  93. // plugins are currently available and started, the corresponding
  94. // extension is loaded through the class loader.
  95. ExtensionInfo extensionInfo = getExtensionInfo(className, classLoader);
  96. if (extensionInfo == null) {
  97. log.error("No extension annotation was found for '{}'", className);
  98. continue;
  99. }
  100. // Make sure, that all plugins required by this extension are available.
  101. List<String> missingPluginIds = new ArrayList<>();
  102. for (String requiredPluginId : extensionInfo.getPlugins()) {
  103. PluginWrapper requiredPlugin = pluginManager.getPlugin(requiredPluginId);
  104. if (requiredPlugin == null || !PluginState.STARTED.equals(requiredPlugin.getPluginState())) {
  105. missingPluginIds.add(requiredPluginId);
  106. }
  107. }
  108. if (!missingPluginIds.isEmpty()) {
  109. StringBuilder missing = new StringBuilder();
  110. for (String missingPluginId : missingPluginIds) {
  111. if (missing.length() > 0) missing.append(", ");
  112. missing.append(missingPluginId);
  113. }
  114. log.trace("Extension '{}' is ignored due to missing plugins: {}", className, missing);
  115. continue;
  116. }
  117. }
  118. log.debug("Loading class '{}' using class loader '{}'", className, classLoader);
  119. Class<?> extensionClass = classLoader.loadClass(className);
  120. log.debug("Checking extension type '{}'", className);
  121. if (type.isAssignableFrom(extensionClass)) {
  122. ExtensionWrapper extensionWrapper = createExtensionWrapper(extensionClass);
  123. result.add(extensionWrapper);
  124. log.debug("Added extension '{}' with ordinal {}", className, extensionWrapper.getOrdinal());
  125. } else {
  126. log.trace("'{}' is not an extension for extension point '{}'", className, type.getName());
  127. if (RuntimeMode.DEVELOPMENT.equals(pluginManager.getRuntimeMode())) {
  128. checkDifferentClassLoaders(type, extensionClass);
  129. }
  130. }
  131. } catch (ClassNotFoundException | NoClassDefFoundError e) {
  132. log.error(e.getMessage(), e);
  133. }
  134. }
  135. if (result.isEmpty()) {
  136. log.debug("No extensions found for extension point '{}'", type.getName());
  137. } else {
  138. log.debug("Found {} extensions for extension point '{}'", result.size(), type.getName());
  139. }
  140. // sort by "ordinal" property
  141. Collections.sort(result);
  142. return result;
  143. }
  144. @Override
  145. public List<ExtensionWrapper> find(String pluginId) {
  146. log.debug("Finding extensions from plugin '{}'", pluginId);
  147. List<ExtensionWrapper> result = new ArrayList<>();
  148. Set<String> classNames = findClassNames(pluginId);
  149. if (classNames.isEmpty()) {
  150. return result;
  151. }
  152. if (pluginId != null) {
  153. PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginId);
  154. if (PluginState.STARTED != pluginWrapper.getPluginState()) {
  155. return result;
  156. }
  157. log.trace("Checking extensions from plugin '{}'", pluginId);
  158. } else {
  159. log.trace("Checking extensions from classpath");
  160. }
  161. ClassLoader classLoader = (pluginId != null) ? pluginManager.getPluginClassLoader(pluginId) : getClass().getClassLoader();
  162. for (String className : classNames) {
  163. try {
  164. log.debug("Loading class '{}' using class loader '{}'", className, classLoader);
  165. Class<?> extensionClass = classLoader.loadClass(className);
  166. ExtensionWrapper extensionWrapper = createExtensionWrapper(extensionClass);
  167. result.add(extensionWrapper);
  168. log.debug("Added extension '{}' with ordinal {}", className, extensionWrapper.getOrdinal());
  169. } catch (ClassNotFoundException | NoClassDefFoundError e) {
  170. log.error(e.getMessage(), e);
  171. }
  172. }
  173. if (result.isEmpty()) {
  174. log.debug("No extensions found for plugin '{}'", pluginId);
  175. } else {
  176. log.debug("Found {} extensions for plugin '{}'", result.size(), pluginId);
  177. }
  178. // sort by "ordinal" property
  179. Collections.sort(result);
  180. return result;
  181. }
  182. @Override
  183. public Set<String> findClassNames(String pluginId) {
  184. Set<String> classNames = getEntries().get(pluginId);
  185. if (classNames == null) {
  186. return Collections.emptySet();
  187. }
  188. return classNames;
  189. }
  190. @Override
  191. public void pluginStateChanged(PluginStateEvent event) {
  192. // TODO optimize (do only for some transitions)
  193. // clear cache
  194. entries = null;
  195. // By default we're assuming, that no checks for extension dependencies are necessary.
  196. //
  197. // A plugin, that has an optional dependency to other plugins, might lead to unloadable
  198. // Java classes (NoClassDefFoundError) at application runtime due to possibly missing
  199. // dependencies. Therefore we're enabling the check for optional extensions, if the
  200. // started plugin contains at least one optional plugin dependency.
  201. if (checkForExtensionDependencies == null && PluginState.STARTED.equals(event.getPluginState())) {
  202. for (PluginDependency dependency : event.getPlugin().getDescriptor().getDependencies()) {
  203. if (dependency.isOptional()) {
  204. log.debug("Enable check for extension dependencies via ASM.");
  205. checkForExtensionDependencies = true;
  206. break;
  207. }
  208. }
  209. }
  210. }
  211. /**
  212. * Returns true, if the extension finder checks extensions for its required plugins.
  213. * This feature has to be enabled, in order check the availability of
  214. * {@link Extension#plugins()} configured by an extension.
  215. * <p>
  216. * This feature is enabled by default, if at least one available plugin makes use of
  217. * optional plugin dependencies. Those optional plugins might not be available at runtime.
  218. * Therefore any extension is checked by default against available plugins before its
  219. * instantiation.
  220. * <p>
  221. * Notice: This feature requires the optional <a href="https://asm.ow2.io/">ASM library</a>
  222. * to be available on the applications classpath.
  223. *
  224. * @return true, if the extension finder checks extensions for its required plugins
  225. */
  226. public final boolean isCheckForExtensionDependencies() {
  227. return Boolean.TRUE.equals(checkForExtensionDependencies);
  228. }
  229. /**
  230. * Plugin developers may enable / disable checks for required plugins of an extension.
  231. * This feature has to be enabled, in order check the availability of
  232. * {@link Extension#plugins()} configured by an extension.
  233. * <p>
  234. * This feature is enabled by default, if at least one available plugin makes use of
  235. * optional plugin dependencies. Those optional plugins might not be available at runtime.
  236. * Therefore any extension is checked by default against available plugins before its
  237. * instantiation.
  238. * <p>
  239. * Notice: This feature requires the optional <a href="https://asm.ow2.io/">ASM library</a>
  240. * to be available on the applications classpath.
  241. *
  242. * @param checkForExtensionDependencies true to enable checks for optional extensions, otherwise false
  243. */
  244. public void setCheckForExtensionDependencies(boolean checkForExtensionDependencies) {
  245. this.checkForExtensionDependencies = checkForExtensionDependencies;
  246. }
  247. protected void debugExtensions(Set<String> extensions) {
  248. if (log.isDebugEnabled()) {
  249. if (extensions.isEmpty()) {
  250. log.debug("No extensions found");
  251. } else {
  252. log.debug("Found possible {} extensions:", extensions.size());
  253. for (String extension : extensions) {
  254. log.debug(" " + extension);
  255. }
  256. }
  257. }
  258. }
  259. private Map<String, Set<String>> readStorages() {
  260. Map<String, Set<String>> result = new LinkedHashMap<>();
  261. result.putAll(readClasspathStorages());
  262. result.putAll(readPluginsStorages());
  263. return result;
  264. }
  265. private Map<String, Set<String>> getEntries() {
  266. if (entries == null) {
  267. entries = readStorages();
  268. }
  269. return entries;
  270. }
  271. /**
  272. * Returns the parameters of an {@link Extension} annotation without loading
  273. * the corresponding class into the class loader.
  274. *
  275. * @param className name of the class, that holds the requested {@link Extension} annotation
  276. * @param classLoader class loader to access the class
  277. * @return the contents of the {@link Extension} annotation or null, if the class does not
  278. * have an {@link Extension} annotation
  279. */
  280. private ExtensionInfo getExtensionInfo(String className, ClassLoader classLoader) {
  281. if (extensionInfos == null) {
  282. extensionInfos = new HashMap<>();
  283. }
  284. if (!extensionInfos.containsKey(className)) {
  285. log.trace("Load annotation for '{}' using asm", className);
  286. ExtensionInfo info = ExtensionInfo.load(className, classLoader);
  287. if (info == null) {
  288. log.warn("No extension annotation was found for '{}'", className);
  289. extensionInfos.put(className, null);
  290. } else {
  291. extensionInfos.put(className, info);
  292. }
  293. }
  294. return extensionInfos.get(className);
  295. }
  296. private ExtensionWrapper createExtensionWrapper(Class<?> extensionClass) {
  297. Extension extensionAnnotation = findExtensionAnnotation(extensionClass);
  298. int ordinal = extensionAnnotation != null ? extensionAnnotation.ordinal() : 0;
  299. ExtensionDescriptor descriptor = new ExtensionDescriptor(ordinal, extensionClass);
  300. return new ExtensionWrapper<>(descriptor, pluginManager.getExtensionFactory());
  301. }
  302. public static Extension findExtensionAnnotation(Class<?> clazz) {
  303. if (clazz.isAnnotationPresent(Extension.class)) {
  304. return clazz.getAnnotation(Extension.class);
  305. }
  306. // search recursively through all annotations
  307. for (Annotation annotation : clazz.getAnnotations()) {
  308. Class<? extends Annotation> annotationClass = annotation.annotationType();
  309. if (!annotationClass.getName().startsWith("java.lang.annotation")) {
  310. Extension extensionAnnotation = findExtensionAnnotation(annotationClass);
  311. if (extensionAnnotation != null) {
  312. return extensionAnnotation;
  313. }
  314. }
  315. }
  316. return null;
  317. }
  318. private void checkDifferentClassLoaders(Class<?> type, Class<?> extensionClass) {
  319. ClassLoader typeClassLoader = type.getClassLoader(); // class loader of extension point
  320. ClassLoader extensionClassLoader = extensionClass.getClassLoader();
  321. boolean match = ClassUtils.getAllInterfacesNames(extensionClass).contains(type.getSimpleName());
  322. if (match && !extensionClassLoader.equals(typeClassLoader)) {
  323. // in this scenario the method 'isAssignableFrom' returns only FALSE
  324. // see http://www.coderanch.com/t/557846/java/java/FWIW-FYI-isAssignableFrom-isInstance-differing
  325. log.error("Different class loaders: '{}' (E) and '{}' (EP)", extensionClassLoader, typeClassLoader);
  326. }
  327. }
  328. }