Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

PluginInfo.java 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. /*
  2. * Copyright (c) 2006-2015 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.plugins;
  23. import com.dmdirc.config.ConfigFileBackedConfigProvider;
  24. import com.dmdirc.config.InvalidIdentityFileException;
  25. import com.dmdirc.events.PluginLoadedEvent;
  26. import com.dmdirc.events.PluginUnloadedEvent;
  27. import com.dmdirc.interfaces.EventBus;
  28. import com.dmdirc.interfaces.config.ConfigProvider;
  29. import com.dmdirc.interfaces.config.IdentityController;
  30. import com.dmdirc.util.validators.ValidationResponse;
  31. import java.io.IOException;
  32. import java.io.InputStream;
  33. import java.nio.file.DirectoryStream;
  34. import java.nio.file.FileSystem;
  35. import java.nio.file.FileSystems;
  36. import java.nio.file.FileVisitResult;
  37. import java.nio.file.Files;
  38. import java.nio.file.Path;
  39. import java.nio.file.SimpleFileVisitor;
  40. import java.nio.file.attribute.BasicFileAttributes;
  41. import java.util.ArrayList;
  42. import java.util.Collection;
  43. import java.util.Collections;
  44. import java.util.HashMap;
  45. import java.util.List;
  46. import java.util.Map;
  47. import org.slf4j.Logger;
  48. import org.slf4j.LoggerFactory;
  49. import dagger.ObjectGraph;
  50. import static com.dmdirc.util.LogUtils.APP_ERROR;
  51. import static com.dmdirc.util.LogUtils.USER_ERROR;
  52. /**
  53. * Stores plugin metadata and handles loading of plugin resources.
  54. */
  55. public class PluginInfo implements ServiceProvider {
  56. private static final Logger LOG = LoggerFactory.getLogger(PluginInfo.class);
  57. /** The metadata for this plugin. */
  58. private final PluginMetaData metaData;
  59. /** The manager to use to look up other plugins. */
  60. private final PluginManager pluginManager;
  61. /** The manager to register services with. */
  62. private final ServiceManager serviceManager;
  63. /** The object graph to pass to plugins for DI purposes. */
  64. private final ObjectGraph objectGraph;
  65. /** The controller to add and remove settings from. */
  66. private final IdentityController identityController;
  67. /** Filename for this plugin (taken from URL). */
  68. private final String filename;
  69. /** The actual Plugin from this jar. */
  70. private Plugin plugin;
  71. /** The classloader used for this Plugin. */
  72. private PluginClassLoader pluginClassLoader;
  73. /** List of classes this plugin has. */
  74. private final List<String> myClasses = new ArrayList<>();
  75. /** Last Error Message. */
  76. private String lastError = "No Error";
  77. /** Are we trying to load? */
  78. private boolean isLoading;
  79. /** List of services we provide. */
  80. private final List<Service> provides = new ArrayList<>();
  81. /** List of children of this plugin. */
  82. private final List<PluginInfo> children = new ArrayList<>();
  83. /** Map of exports. */
  84. private final Map<String, ExportInfo> exports = new HashMap<>();
  85. /** List of configuration providers. */
  86. private final Collection<ConfigFileBackedConfigProvider> configProviders = new ArrayList<>();
  87. /** Event bus to post plugin loaded events to. */
  88. private final EventBus eventBus;
  89. /** File system for the plugin's jar. */
  90. private final FileSystem pluginFilesystem;
  91. /**
  92. * Create a new PluginInfo.
  93. *
  94. * @param metadata The plugin's metadata information
  95. * @param eventBus Event bus to post event loaded events on.
  96. * @param identityController The identity controller to add and remove settings from.
  97. * @param objectGraph The object graph to give to plugins for DI purposes.
  98. *
  99. * @throws PluginException if there is an error loading the Plugin
  100. */
  101. public PluginInfo(
  102. final PluginManager pluginManager,
  103. final ServiceManager serviceManager,
  104. final PluginMetaData metadata,
  105. final EventBus eventBus,
  106. final IdentityController identityController,
  107. final ObjectGraph objectGraph) throws PluginException {
  108. this.pluginManager = pluginManager;
  109. this.serviceManager = serviceManager;
  110. this.objectGraph = objectGraph;
  111. this.eventBus = eventBus;
  112. this.identityController = identityController;
  113. this.filename = metadata.getPluginPath().getFileName().toString();
  114. this.metaData = metadata;
  115. try {
  116. pluginFilesystem = FileSystems.newFileSystem(metadata.getPluginPath(), null);
  117. } catch (IOException ex) {
  118. lastError = "Error loading filesystem: " + ex.getMessage();
  119. throw new PluginException("Plugin " + filename + " failed to load. " + lastError, ex);
  120. }
  121. updateClassList();
  122. if (!myClasses.contains(metadata.getMainClass())) {
  123. lastError = "main class file (" + metadata.getMainClass() + ") not found in jar.";
  124. throw new PluginException("Plugin " + filename + " failed to load. " + lastError);
  125. }
  126. updateProvides();
  127. getDefaults();
  128. }
  129. public PluginMetaData getMetaData() {
  130. return metaData;
  131. }
  132. public String getFilename() {
  133. return filename;
  134. }
  135. public Plugin getPlugin() {
  136. return plugin;
  137. }
  138. public PluginClassLoader getPluginClassLoader() {
  139. return pluginClassLoader;
  140. }
  141. public String getLastError() {
  142. return lastError;
  143. }
  144. /**
  145. * Updates the list of known classes within this plugin from the specified resource manager.
  146. */
  147. private void updateClassList() throws PluginException {
  148. myClasses.clear();
  149. try {
  150. Files.walkFileTree(pluginFilesystem.getPath("/"), new SimpleFileVisitor<Path>() {
  151. @Override
  152. public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) {
  153. if (file.getFileName().toString().endsWith(".class")) {
  154. final String classname = file.toAbsolutePath().toString().replace('/',
  155. '.');
  156. myClasses.add(classname.substring(1, classname.length() - 6));
  157. }
  158. return FileVisitResult.CONTINUE;
  159. }
  160. });
  161. } catch (IOException ex) {
  162. lastError = "Error loading classes: " + ex.getMessage();
  163. throw new PluginException("Plugin " + filename + " failed to load. " + lastError, ex);
  164. }
  165. }
  166. /**
  167. * Gets the {@link ObjectGraph} that should be used when loading this plugin.
  168. *
  169. * <p>
  170. * Where this plugin has a parent which returns a non-null graph from
  171. * {@link Plugin#getObjectGraph()} that object graph will be used unmodified. Otherwise, the
  172. * global object graph will be used.
  173. *
  174. * @return An {@link ObjectGraph} to be used.
  175. */
  176. protected ObjectGraph getObjectGraph() {
  177. if (metaData.getParent() != null) {
  178. final PluginInfo parentInfo = pluginManager.getPluginInfoByName(metaData.getParent());
  179. final Plugin parent = parentInfo.getPlugin();
  180. final ObjectGraph parentGraph = parent.getObjectGraph();
  181. if (parentGraph != null) {
  182. return parentGraph;
  183. }
  184. }
  185. return objectGraph;
  186. }
  187. /**
  188. * Get the defaults, formatters and icons for this plugin.
  189. */
  190. private void getDefaults() {
  191. final ConfigProvider defaults = identityController.getAddonSettings();
  192. LOG.trace("{}: Using domain '{}'", new Object[]{metaData.getName(), getDomain()});
  193. for (Map.Entry<String, String> entry : metaData.getDefaultSettings().entrySet()) {
  194. final String key = entry.getKey();
  195. final String value = entry.getValue();
  196. defaults.setOption(getDomain(), key, value);
  197. }
  198. for (Map.Entry<String, String> entry : metaData.getFormatters().entrySet()) {
  199. final String key = entry.getKey();
  200. final String value = entry.getValue();
  201. defaults.setOption("formatter", key, value);
  202. }
  203. for (Map.Entry<String, String> entry : metaData.getIcons().entrySet()) {
  204. final String key = entry.getKey();
  205. final String value = entry.getValue();
  206. defaults.setOption("icon", key, value);
  207. }
  208. }
  209. /**
  210. * Try get the identities for this plugin. This will unload any identities previously loaded by
  211. * this plugin.
  212. */
  213. private void loadIdentities() {
  214. if (!Files.exists(pluginFilesystem.getPath("/META-INF/identities/"))) {
  215. return;
  216. }
  217. try {
  218. unloadIdentities();
  219. try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(
  220. pluginFilesystem.getPath("/META-INF/identities/"))) {
  221. directoryStream.forEach(this::loadIdentity);
  222. }
  223. } catch (final IOException ioe) {
  224. LOG.warn(USER_ERROR, "Error finding identities in plugin '{}'", metaData.getName(),
  225. ioe);
  226. }
  227. }
  228. private void loadIdentity(final Path path) {
  229. if (!Files.isRegularFile(path)) {
  230. // Don't try to load folders etc
  231. return;
  232. }
  233. try (final InputStream stream = Files.newInputStream(path)) {
  234. synchronized (configProviders) {
  235. final ConfigFileBackedConfigProvider configProvider =
  236. new ConfigFileBackedConfigProvider(stream, false);
  237. identityController.addConfigProvider(configProvider);
  238. configProviders.add(configProvider);
  239. }
  240. } catch (InvalidIdentityFileException ex) {
  241. LOG.warn(USER_ERROR, "Error with identity file '{}' in plugin '{}'",
  242. path.getFileName(), metaData.getName(), ex);
  243. } catch (IOException ex) {
  244. LOG.warn(USER_ERROR, "Unable to load identity file '{}' in plugin '{}'",
  245. path.getFileName(), metaData.getName(), ex);
  246. }
  247. }
  248. /**
  249. * Unload any identities loaded by this plugin.
  250. */
  251. private void unloadIdentities() {
  252. synchronized (configProviders) {
  253. configProviders.forEach(identityController::removeConfigProvider);
  254. configProviders.clear();
  255. }
  256. }
  257. /**
  258. * Update provides list.
  259. */
  260. private void updateProvides() {
  261. // Remove us from any existing provides lists.
  262. synchronized (provides) {
  263. for (Service service : provides) {
  264. service.delProvider(this);
  265. }
  266. provides.clear();
  267. }
  268. // Get services provided by this plugin
  269. final Collection<String> providesList = metaData.getServices();
  270. if (providesList != null) {
  271. for (String item : providesList) {
  272. final String[] bits = item.split(" ");
  273. final String name = bits[0];
  274. final String type = bits.length > 1 ? bits[1] : "misc";
  275. if (!"any".equalsIgnoreCase(name) && !"export".equalsIgnoreCase(type)) {
  276. final Service service = serviceManager.getService(type, name, true);
  277. synchronized (provides) {
  278. service.addProvider(this);
  279. provides.add(service);
  280. }
  281. }
  282. }
  283. }
  284. updateExports();
  285. }
  286. /**
  287. * Called when the plugin is updated using the updater. Reloads metaData and updates the list of
  288. * files.
  289. */
  290. public void pluginUpdated() throws PluginException {
  291. updateClassList();
  292. updateMetaData();
  293. updateProvides();
  294. getDefaults();
  295. }
  296. /**
  297. * Try to reload the metaData from the plugin.config file. If this fails, the old data will be
  298. * used still.
  299. *
  300. * @return true if metaData was reloaded ok, else false.
  301. */
  302. private boolean updateMetaData() {
  303. metaData.load();
  304. return !metaData.hasErrors();
  305. }
  306. /**
  307. * Returns a path inside the plugin's jar for the given name.
  308. *
  309. * @param first The path string or initial part of the path string
  310. * @param more Additional strings to be joined to form the full path
  311. *
  312. * @return The resulting path inside the plugin's jar
  313. */
  314. public Path getPath(final String first, final String... more) {
  315. return pluginFilesystem.getPath(first, more);
  316. }
  317. @Override
  318. public final boolean isActive() {
  319. return isLoaded();
  320. }
  321. @Override
  322. public void activateServices() {
  323. loadPlugin();
  324. }
  325. @Override
  326. public String getProviderName() {
  327. return "Plugin: " + metaData.getFriendlyName() + " ("
  328. + metaData.getName() + " / " + getFilename() + ')';
  329. }
  330. @Override
  331. public List<Service> getServices() {
  332. synchronized (provides) {
  333. return new ArrayList<>(provides);
  334. }
  335. }
  336. /**
  337. * Is this plugin loaded?
  338. *
  339. * @return True if the plugin is currently loaded, false otherwise
  340. */
  341. public boolean isLoaded() {
  342. return plugin != null;
  343. }
  344. /**
  345. * Load any required plugins or services.
  346. *
  347. * @return True if all requirements have been satisfied, false otherwise
  348. */
  349. protected boolean loadRequirements() {
  350. return loadRequiredPlugins() && loadRequiredServices();
  351. }
  352. /**
  353. * Attempts to load all services that are required by this plugin.
  354. *
  355. * @return True iff all required services were found and satisfied
  356. */
  357. protected boolean loadRequiredServices() {
  358. for (String serviceInfo : metaData.getRequiredServices()) {
  359. final String[] parts = serviceInfo.split(" ", 2);
  360. if ("any".equals(parts[0])) {
  361. Service best = null;
  362. boolean found = false;
  363. for (Service service : serviceManager.getServicesByType(parts[1])) {
  364. if (service.isActive()) {
  365. found = true;
  366. break;
  367. }
  368. best = service;
  369. }
  370. if (!found && best != null) {
  371. found = best.activate();
  372. }
  373. if (!found) {
  374. return false;
  375. }
  376. } else {
  377. final Service service = serviceManager.getService(parts[1], parts[0]);
  378. if (service == null || !service.activate()) {
  379. return false;
  380. }
  381. }
  382. }
  383. return true;
  384. }
  385. /**
  386. * Attempts to load all plugins that are required by this plugin.
  387. *
  388. * @return True if all required plugins were found and loaded
  389. */
  390. protected boolean loadRequiredPlugins() {
  391. final String required = metaData.getRequirements().get("plugins");
  392. if (required != null) {
  393. for (String pluginName : required.split(",")) {
  394. final String[] data = pluginName.split(":");
  395. if (!data[0].trim().isEmpty() && !loadRequiredPlugin(data[0])) {
  396. return false;
  397. }
  398. }
  399. }
  400. return metaData.getParent() == null || loadRequiredPlugin(metaData.getParent());
  401. }
  402. /**
  403. * Attempts to load the specified required plugin.
  404. *
  405. * @param name The name of the plugin to be loaded
  406. *
  407. * @return True if the plugin was found and loaded, false otherwise
  408. */
  409. protected boolean loadRequiredPlugin(final String name) {
  410. LOG.info("Loading required plugin '{}' for plugin {}",
  411. new Object[]{name, metaData.getName()});
  412. final PluginInfo pi = pluginManager.getPluginInfoByName(name);
  413. if (pi == null) {
  414. return false;
  415. }
  416. pi.loadPlugin();
  417. return true;
  418. }
  419. /**
  420. * Load the plugin files.
  421. */
  422. public void loadPlugin() {
  423. if (isLoaded() || isLoading) {
  424. lastError = "Not Loading: (" + isLoaded() + "||" + isLoading + ')';
  425. return;
  426. }
  427. updateProvides();
  428. isLoading = true;
  429. if (!loadRequirements()) {
  430. isLoading = false;
  431. lastError = "Unable to satisfy dependencies for " + metaData.getName();
  432. return;
  433. }
  434. loadIdentities();
  435. loadMainClass();
  436. if (isLoaded()) {
  437. //TODO plugin loading shouldn't be done from here, event bus shouldn't be here.
  438. eventBus.publishAsync(new PluginLoadedEvent(this));
  439. }
  440. isLoading = false;
  441. }
  442. /**
  443. * Add the given Plugin as a child of this plugin.
  444. *
  445. * @param child Child to add
  446. */
  447. public void addChild(final PluginInfo child) {
  448. children.add(child);
  449. }
  450. /**
  451. * Remove the given Plugin as a child of this plugin.
  452. *
  453. * @param child Child to remove
  454. */
  455. public void delChild(final PluginInfo child) {
  456. children.remove(child);
  457. }
  458. /**
  459. * Returns a list of this plugin's children.
  460. *
  461. * @return List of child plugins
  462. */
  463. public List<PluginInfo> getChildren() {
  464. return Collections.unmodifiableList(children);
  465. }
  466. /**
  467. * Initialises this plugin's classloader.
  468. */
  469. private void initialiseClassLoader() {
  470. if (pluginClassLoader == null) {
  471. final PluginClassLoader[] loaders = new PluginClassLoader[metaData.getParent() == null
  472. ? 0 : 1];
  473. if (metaData.getParent() != null) {
  474. final String parentName = metaData.getParent();
  475. final PluginInfo parent = pluginManager.getPluginInfoByName(parentName);
  476. parent.addChild(this);
  477. loaders[0] = parent.getPluginClassLoader();
  478. if (loaders[0] == null) {
  479. // Not loaded? Try again...
  480. parent.loadPlugin();
  481. loaders[0] = parent.getPluginClassLoader();
  482. if (loaders[0] == null) {
  483. lastError = "Unable to get classloader from required parent '" + parentName
  484. + "' for " + metaData.getName();
  485. return;
  486. }
  487. }
  488. }
  489. pluginClassLoader = new PluginClassLoader(this, pluginManager.getGlobalClassLoader(),
  490. loaders);
  491. }
  492. }
  493. /**
  494. * Load the main class
  495. */
  496. private void loadMainClass() {
  497. final String classname = metaData.getMainClass();
  498. try {
  499. initialiseClassLoader();
  500. // Don't reload a class if its already loaded.
  501. if (pluginClassLoader.isClassLoaded(classname, true)) {
  502. lastError = "Classloader says we are already loaded.";
  503. return;
  504. }
  505. final Class<?> clazz = pluginClassLoader.loadClass(classname);
  506. if (clazz == null) {
  507. lastError = "Class '" + classname + "' was not able to load.";
  508. return;
  509. }
  510. createMainClass(clazz);
  511. } catch (ClassNotFoundException cnfe) {
  512. lastError = "Class not found ('" + filename + ':' + classname + ':'
  513. + classname.equals(metaData.getMainClass()) + "') - "
  514. + cnfe.getMessage();
  515. LOG.info(USER_ERROR, lastError, cnfe);
  516. } catch (NoClassDefFoundError ncdf) {
  517. lastError = "Unable to instantiate plugin ('" + filename + ':'
  518. + classname + ':'
  519. + classname.equals(metaData.getMainClass())
  520. + "') - Unable to find class: " + ncdf.getMessage();
  521. LOG.info(USER_ERROR, lastError, ncdf);
  522. } catch (VerifyError ve) {
  523. lastError = "Unable to instantiate plugin ('" + filename + ':'
  524. + classname + ':'
  525. + classname.equals(metaData.getMainClass())
  526. + "') - Incompatible: " + ve.getMessage();
  527. LOG.info(USER_ERROR, lastError, ve);
  528. } catch (IllegalArgumentException | ReflectiveOperationException ex) {
  529. lastError = "Unable to instantiate class for plugin " + metaData.getName()
  530. + ": " + classname;
  531. LOG.info(APP_ERROR, lastError, ex);
  532. }
  533. }
  534. private void createMainClass(final Class<?> clazz) throws InstantiationException,
  535. IllegalAccessException {
  536. final Object temp = clazz.newInstance();
  537. if (temp instanceof Plugin) {
  538. final ValidationResponse prerequisites = ((Plugin) temp).checkPrerequisites();
  539. if (prerequisites.isFailure()) {
  540. lastError = "Prerequisites for plugin not met. ('"
  541. + filename + ':' + metaData.getMainClass()
  542. + "' -> '" + prerequisites.getFailureReason() + "') ";
  543. LOG.info(USER_ERROR, lastError);
  544. } else {
  545. initialisePlugin((Plugin) temp);
  546. }
  547. }
  548. }
  549. private void initialisePlugin(final Plugin temp) {
  550. plugin = temp;
  551. try {
  552. plugin.load(this, getObjectGraph());
  553. plugin.onLoad();
  554. } catch (LinkageError | Exception e) {
  555. lastError = "Error in onLoad for " + metaData.getName() + ':' + e.getMessage();
  556. LOG.warn(APP_ERROR, lastError, e);
  557. unloadPlugin();
  558. }
  559. }
  560. /**
  561. * Gets the configuration domain that should be used by this plugin.
  562. *
  563. * @return The configuration domain to use.
  564. */
  565. public String getDomain() {
  566. return "plugin-" + metaData.getName();
  567. }
  568. /**
  569. * Unload the plugin if possible.
  570. */
  571. public void unloadPlugin() {
  572. unloadPlugin(false);
  573. }
  574. /**
  575. * Can this plugin be unloaded? Will return false if: - The plugin is persistent (all its
  576. * classes are loaded into the global class loader) - The plugin isn't currently loaded - The
  577. * metadata key "unloadable" is set to false, no or 0
  578. *
  579. * @return true if plugin can be unloaded
  580. */
  581. public boolean isUnloadable() {
  582. return !isPersistent() && isLoaded() && metaData.isUnloadable();
  583. }
  584. /**
  585. * Unload the plugin if possible.
  586. *
  587. * @param parentUnloading is our parent already unloading? (if so, don't call delChild)
  588. */
  589. private void unloadPlugin(final boolean parentUnloading) {
  590. if (isUnloadable()) {
  591. // Unload all children
  592. for (PluginInfo child : children) {
  593. child.unloadPlugin(true);
  594. }
  595. // Delete ourself as a child of our parent.
  596. if (!parentUnloading && metaData.getParent() != null) {
  597. final PluginInfo pi = pluginManager.getPluginInfoByName(metaData.getParent());
  598. if (pi != null) {
  599. pi.delChild(this);
  600. }
  601. }
  602. // Now unload ourself
  603. try {
  604. plugin.onUnload();
  605. } catch (Exception | LinkageError e) {
  606. lastError = "Error in onUnload for " + metaData.getName()
  607. + ':' + e + " - " + e.getMessage();
  608. LOG.warn(APP_ERROR, lastError, e);
  609. }
  610. //TODO plugin unloading shouldn't be done from here, event bus shouldn't be here.
  611. eventBus.publishAsync(new PluginUnloadedEvent(this));
  612. synchronized (provides) {
  613. for (Service service : provides) {
  614. service.delProvider(this);
  615. }
  616. provides.clear();
  617. }
  618. }
  619. unloadIdentities();
  620. plugin = null;
  621. pluginClassLoader = null;
  622. }
  623. /**
  624. * Get the list of Classes
  625. *
  626. * @return Classes this plugin has
  627. */
  628. public List<String> getClassList() {
  629. return Collections.unmodifiableList(myClasses);
  630. }
  631. /**
  632. * Is this a persistent plugin?
  633. *
  634. * @return true if persistent, else false
  635. */
  636. public boolean isPersistent() {
  637. return metaData.getPersistentClasses().contains("*");
  638. }
  639. /**
  640. * Get a list of all persistent classes in this plugin
  641. *
  642. * @return List of all persistent classes in this plugin
  643. */
  644. public Collection<String> getPersistentClasses() {
  645. if (isPersistent()) {
  646. return getClassList();
  647. } else {
  648. return metaData.getPersistentClasses();
  649. }
  650. }
  651. /**
  652. * Is this a persistent class?
  653. *
  654. * @param classname class to check persistence of
  655. *
  656. * @return true if file (or whole plugin) is persistent, else false
  657. */
  658. public boolean isPersistent(final String classname) {
  659. return isPersistent() || metaData.getPersistentClasses().contains(classname);
  660. }
  661. /**
  662. * String Representation of this plugin
  663. *
  664. * @return String Representation of this plugin
  665. */
  666. @Override
  667. public String toString() {
  668. return metaData.getFriendlyName() + " - " + filename;
  669. }
  670. /**
  671. * Update exports list.
  672. */
  673. private void updateExports() {
  674. exports.clear();
  675. // Get exports provided by this plugin
  676. final Collection<String> exportsList = metaData.getExports();
  677. for (String item : exportsList) {
  678. final String[] bits = item.split(" ");
  679. if (bits.length > 2) {
  680. final String methodName = bits[0];
  681. final String methodClass = bits[2];
  682. final String serviceName = bits.length > 4 ? bits[4] : bits[0];
  683. // Add a provides for this
  684. final Service service = serviceManager.getService("export", serviceName, true);
  685. synchronized (provides) {
  686. service.addProvider(this);
  687. provides.add(service);
  688. }
  689. // Add is as an export
  690. exports.put(serviceName, new ExportInfo(methodName, methodClass, this));
  691. }
  692. }
  693. }
  694. @Override
  695. public ExportedService getExportedService(final String name) {
  696. if (exports.containsKey(name)) {
  697. return exports.get(name).getExportedService();
  698. } else {
  699. return null;
  700. }
  701. }
  702. /**
  703. * Does this plugin export the specified service?
  704. *
  705. * @param name Name of the service to check
  706. *
  707. * @return true iff the plugin exports the service
  708. */
  709. public boolean hasExportedService(final String name) {
  710. return exports.containsKey(name);
  711. }
  712. }