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 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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.util.ArrayList;
  22. import java.util.Collections;
  23. import java.util.HashMap;
  24. import java.util.LinkedHashMap;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Set;
  28. /**
  29. * @author Decebal Suiu
  30. */
  31. public abstract class AbstractExtensionFinder implements ExtensionFinder, PluginStateListener {
  32. private static final Logger log = LoggerFactory.getLogger(AbstractExtensionFinder.class);
  33. protected PluginManager pluginManager;
  34. protected volatile Map<String, Set<String>> entries; // cache by pluginId
  35. protected volatile Map<String, ExtensionInfo> extensionInfos; // cache extension infos by class name
  36. protected Boolean checkForExtensionDependencies = null;
  37. public AbstractExtensionFinder(PluginManager pluginManager) {
  38. this.pluginManager = pluginManager;
  39. }
  40. public abstract Map<String, Set<String>> readPluginsStorages();
  41. public abstract Map<String, Set<String>> readClasspathStorages();
  42. @Override
  43. @SuppressWarnings("unchecked")
  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 (entries.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 == null || 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 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. return getEntries().get(pluginId);
  185. }
  186. @Override
  187. public void pluginStateChanged(PluginStateEvent event) {
  188. // TODO optimize (do only for some transitions)
  189. // clear cache
  190. entries = null;
  191. // By default we're assuming, that no checks for extension dependencies are necessary.
  192. //
  193. // A plugin, that has an optional dependency to other plugins, might lead to unloadable
  194. // Java classes (NoClassDefFoundError) at application runtime due to possibly missing
  195. // dependencies. Therefore we're enabling the check for optional extensions, if the
  196. // started plugin contains at least one optional plugin dependency.
  197. if (checkForExtensionDependencies == null && PluginState.STARTED.equals(event.getPluginState())) {
  198. for (PluginDependency dependency : event.getPlugin().getDescriptor().getDependencies()) {
  199. if (dependency.isOptional()) {
  200. log.debug("Enable check for extension dependencies via ASM.");
  201. checkForExtensionDependencies = true;
  202. break;
  203. }
  204. }
  205. }
  206. }
  207. /**
  208. * Returns true, if the extension finder checks extensions for its required plugins.
  209. * This feature has to be enabled, in order check the availability of
  210. * {@link Extension#plugins()} configured by an extension.
  211. * <p>
  212. * This feature is enabled by default, if at least one available plugin makes use of
  213. * optional plugin dependencies. Those optional plugins might not be available at runtime.
  214. * Therefore any extension is checked by default against available plugins before its
  215. * instantiation.
  216. * <p>
  217. * Notice: This feature requires the optional <a href="https://asm.ow2.io/">ASM library</a>
  218. * to be available on the applications classpath.
  219. *
  220. * @return true, if the extension finder checks extensions for its required plugins
  221. */
  222. public final boolean isCheckForExtensionDependencies() {
  223. return Boolean.TRUE.equals(checkForExtensionDependencies);
  224. }
  225. /**
  226. * Plugin developers may enable / disable checks for required plugins of an extension.
  227. * This feature has to be enabled, in order check the availability of
  228. * {@link Extension#plugins()} configured by an extension.
  229. * <p>
  230. * This feature is enabled by default, if at least one available plugin makes use of
  231. * optional plugin dependencies. Those optional plugins might not be available at runtime.
  232. * Therefore any extension is checked by default against available plugins before its
  233. * instantiation.
  234. * <p>
  235. * Notice: This feature requires the optional <a href="https://asm.ow2.io/">ASM library</a>
  236. * to be available on the applications classpath.
  237. *
  238. * @param checkForExtensionDependencies true to enable checks for optional extensions, otherwise false
  239. */
  240. public void setCheckForExtensionDependencies(boolean checkForExtensionDependencies) {
  241. this.checkForExtensionDependencies = checkForExtensionDependencies;
  242. }
  243. protected void debugExtensions(Set<String> extensions) {
  244. if (log.isDebugEnabled()) {
  245. if (extensions.isEmpty()) {
  246. log.debug("No extensions found");
  247. } else {
  248. log.debug("Found possible {} extensions:", extensions.size());
  249. for (String extension : extensions) {
  250. log.debug(" " + extension);
  251. }
  252. }
  253. }
  254. }
  255. private Map<String, Set<String>> readStorages() {
  256. Map<String, Set<String>> result = new LinkedHashMap<>();
  257. result.putAll(readClasspathStorages());
  258. result.putAll(readPluginsStorages());
  259. return result;
  260. }
  261. private Map<String, Set<String>> getEntries() {
  262. if (entries == null) {
  263. entries = readStorages();
  264. }
  265. return entries;
  266. }
  267. /**
  268. * Returns the parameters of an {@link Extension} annotation without loading
  269. * the corresponding class into the class loader.
  270. *
  271. * @param className name of the class, that holds the requested {@link Extension} annotation
  272. * @param classLoader class loader to access the class
  273. * @return the contents of the {@link Extension} annotation or null, if the class does not
  274. * have an {@link Extension} annotation
  275. */
  276. private ExtensionInfo getExtensionInfo(String className, ClassLoader classLoader) {
  277. if (extensionInfos == null) {
  278. extensionInfos = new HashMap<>();
  279. }
  280. if (!extensionInfos.containsKey(className)) {
  281. log.trace("Load annotation for '{}' using asm", className);
  282. ExtensionInfo info = ExtensionInfo.load(className, classLoader);
  283. if (info == null) {
  284. log.warn("No extension annotation was found for '{}'", className);
  285. extensionInfos.put(className, null);
  286. } else {
  287. extensionInfos.put(className, info);
  288. }
  289. }
  290. return extensionInfos.get(className);
  291. }
  292. private ExtensionWrapper createExtensionWrapper(Class<?> extensionClass) {
  293. int ordinal = 0;
  294. if (extensionClass.isAnnotationPresent(Extension.class)) {
  295. ordinal = extensionClass.getAnnotation(Extension.class).ordinal();
  296. }
  297. ExtensionDescriptor descriptor = new ExtensionDescriptor(ordinal, extensionClass);
  298. return new ExtensionWrapper<>(descriptor, pluginManager.getExtensionFactory());
  299. }
  300. private void checkDifferentClassLoaders(Class<?> type, Class<?> extensionClass) {
  301. ClassLoader typeClassLoader = type.getClassLoader(); // class loader of extension point
  302. ClassLoader extensionClassLoader = extensionClass.getClassLoader();
  303. boolean match = ClassUtils.getAllInterfacesNames(extensionClass).contains(type.getSimpleName());
  304. if (match && !extensionClassLoader.equals(typeClassLoader)) {
  305. // in this scenario the method 'isAssignableFrom' returns only FALSE
  306. // see http://www.coderanch.com/t/557846/java/java/FWIW-FYI-isAssignableFrom-isInstance-differing
  307. log.error("Different class loaders: '{}' (E) and '{}' (EP)", extensionClassLoader, typeClassLoader);
  308. }
  309. }
  310. }