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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. /*
  2. * Copyright (c) 2006-2014 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.DMDircMBassador;
  24. import com.dmdirc.config.ConfigFileBackedConfigProvider;
  25. import com.dmdirc.config.InvalidIdentityFileException;
  26. import com.dmdirc.events.AppErrorEvent;
  27. import com.dmdirc.events.PluginLoadedEvent;
  28. import com.dmdirc.events.PluginUnloadedEvent;
  29. import com.dmdirc.events.UserErrorEvent;
  30. import com.dmdirc.interfaces.config.ConfigProvider;
  31. import com.dmdirc.interfaces.config.IdentityController;
  32. import com.dmdirc.logger.ErrorLevel;
  33. import com.dmdirc.util.SimpleInjector;
  34. import com.dmdirc.util.resourcemanager.ResourceManager;
  35. import com.dmdirc.util.validators.ValidationResponse;
  36. import java.io.File;
  37. import java.io.IOException;
  38. import java.io.InputStream;
  39. import java.util.ArrayList;
  40. import java.util.Collection;
  41. import java.util.Collections;
  42. import java.util.HashMap;
  43. import java.util.List;
  44. import java.util.Map;
  45. import java.util.Timer;
  46. import java.util.TimerTask;
  47. import java.util.TreeMap;
  48. import javax.annotation.Nonnull;
  49. import javax.inject.Provider;
  50. import org.slf4j.LoggerFactory;
  51. import dagger.ObjectGraph;
  52. /**
  53. * Stores plugin metadata and handles loading of plugin resources.
  54. */
  55. public class PluginInfo implements Comparable<PluginInfo>, ServiceProvider {
  56. private static final org.slf4j.Logger log = LoggerFactory.getLogger(PluginInfo.class);
  57. /** The metadata for this plugin. */
  58. private final PluginMetaData metaData;
  59. /** The initialiser to use for the injector. */
  60. private final Provider<PluginInjectorInitialiser> injectorInitialiser;
  61. /** The object graph to pass to plugins for DI purposes. */
  62. private final ObjectGraph objectGraph;
  63. /** The controller to add and remove settings from. */
  64. private final IdentityController identityController;
  65. /** Filename for this plugin (taken from URL). */
  66. private final String filename;
  67. /** The actual Plugin from this jar. */
  68. private Plugin plugin;
  69. /** The classloader used for this Plugin. */
  70. private PluginClassLoader pluginClassLoader;
  71. /** The resource manager used by this pluginInfo. */
  72. private ResourceManager resourceManager;
  73. /** Is this plugin only loaded temporarily? */
  74. private boolean tempLoaded;
  75. /** List of classes this plugin has. */
  76. private final List<String> myClasses = new ArrayList<>();
  77. /** Last Error Message. */
  78. private String lastError = "No Error";
  79. /** Are we trying to load? */
  80. private boolean isLoading;
  81. /** List of services we provide. */
  82. private final List<Service> provides = new ArrayList<>();
  83. /** List of children of this plugin. */
  84. private final List<PluginInfo> children = new ArrayList<>();
  85. /** Map of exports. */
  86. private final Map<String, ExportInfo> exports = new HashMap<>();
  87. /** List of configuration providers. */
  88. private final List<ConfigProvider> configProviders = new ArrayList<>();
  89. /** Event bus to post plugin loaded events to. */
  90. private final DMDircMBassador eventBus;
  91. /**
  92. * Create a new PluginInfo.
  93. *
  94. * @param metadata The plugin's metadata information
  95. * @param injectorInitialiser The initialiser to use for the plugin's injector.
  96. * @param eventBus Event bus to post event loaded events on.
  97. * @param identityController The identity controller to add and remove settings from.
  98. * @param objectGraph The object graph to give to plugins for DI purposes.
  99. *
  100. * @throws PluginException if there is an error loading the Plugin
  101. */
  102. public PluginInfo(
  103. final PluginMetaData metadata,
  104. final Provider<PluginInjectorInitialiser> injectorInitialiser,
  105. final DMDircMBassador eventBus,
  106. final IdentityController identityController,
  107. final ObjectGraph objectGraph) throws PluginException {
  108. this.injectorInitialiser = injectorInitialiser;
  109. this.objectGraph = objectGraph;
  110. this.eventBus = eventBus;
  111. this.identityController = identityController;
  112. this.filename = new File(metadata.getPluginUrl().getPath()).getName();
  113. this.metaData = metadata;
  114. ResourceManager res;
  115. try {
  116. res = getResourceManager();
  117. } catch (IOException ioe) {
  118. lastError = "Error with resourcemanager: " + ioe.getMessage();
  119. throw new PluginException("Plugin " + filename + " failed to load. " + lastError, ioe);
  120. }
  121. updateClassList(res);
  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. * @param res Resource manager to use to read the plugin contents.
  148. */
  149. private void updateClassList(final ResourceManager res) {
  150. myClasses.clear();
  151. for (final String classfilename : res.getResourcesStartingWith("")) {
  152. final String classname = classfilename.replace('/', '.');
  153. if (classname.endsWith(".class")) {
  154. myClasses.add(classname.substring(0, classname.length() - 6));
  155. }
  156. }
  157. }
  158. /**
  159. * Retrieves the injector used to inject parameters into this plugin's methods.
  160. *
  161. * @return The injector used for this plugin
  162. */
  163. public SimpleInjector getInjector() {
  164. final SimpleInjector injector;
  165. final SimpleInjector[] parents = new SimpleInjector[metaData.getParent() == null ? 0 : 1];
  166. final Plugin[] plugins = new Plugin[parents.length];
  167. if (metaData.getParent() != null) {
  168. final PluginInfo parent = metaData.getManager()
  169. .getPluginInfoByName(metaData.getParent());
  170. parents[0] = parent.getInjector();
  171. plugins[0] = parent.getPlugin();
  172. }
  173. injector = new SimpleInjector(parents);
  174. for (Plugin parentPlugin : plugins) {
  175. injector.addParameter(parentPlugin);
  176. }
  177. // TODO: This should be switched to using a full DI framework.
  178. injector.addParameter(PluginInfo.class, this);
  179. injector.addParameter(PluginMetaData.class, metaData);
  180. injectorInitialiser.get().initialise(injector);
  181. return injector;
  182. }
  183. /**
  184. * Gets the {@link ObjectGraph} that should be used when loading this plugin.
  185. *
  186. * <p>
  187. * Where this plugin has a parent which returns a non-null graph from
  188. * {@link Plugin#getObjectGraph()} that object graph will be used unmodified. Otherwise, the
  189. * global object graph will be used.
  190. *
  191. * @return An {@link ObjectGraph} to be used.
  192. */
  193. protected ObjectGraph getObjectGraph() {
  194. if (metaData.getParent() != null) {
  195. final PluginInfo parentInfo = metaData.getManager()
  196. .getPluginInfoByName(metaData.getParent());
  197. Plugin parent = parentInfo.getPlugin();
  198. ObjectGraph parentGraph = parent.getObjectGraph();
  199. if (parentGraph != null) {
  200. return parentGraph;
  201. }
  202. }
  203. return objectGraph;
  204. }
  205. /**
  206. * Get the licence for this plugin if it exists.
  207. *
  208. * @return An InputStream for the licence of this plugin, or null if no licence found.
  209. *
  210. * @throws IOException if there is an error with the ResourceManager.
  211. */
  212. public Map<String, InputStream> getLicenceStreams() throws IOException {
  213. final TreeMap<String, InputStream> licences = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
  214. licences.putAll(getResourceManager().getResourcesStartingWithAsInputStreams(
  215. "META-INF/licences/"));
  216. return licences;
  217. }
  218. /**
  219. * Get the defaults, formatters and icons for this plugin.
  220. */
  221. private void getDefaults() {
  222. final ConfigProvider defaults = identityController.getAddonSettings();
  223. log.trace("{}: Using domain '{}'",
  224. new Object[]{metaData.getName(), getDomain()});
  225. for (Map.Entry<String, String> entry : metaData.getDefaultSettings().entrySet()) {
  226. final String key = entry.getKey();
  227. final String value = entry.getValue();
  228. defaults.setOption(getDomain(), key, value);
  229. }
  230. for (Map.Entry<String, String> entry : metaData.getFormatters().entrySet()) {
  231. final String key = entry.getKey();
  232. final String value = entry.getValue();
  233. defaults.setOption("formatter", key, value);
  234. }
  235. for (Map.Entry<String, String> entry : metaData.getIcons().entrySet()) {
  236. final String key = entry.getKey();
  237. final String value = entry.getValue();
  238. defaults.setOption("icon", key, value);
  239. }
  240. }
  241. /**
  242. * Try get the identities for this plugin. This will unload any identities previously loaded by
  243. * this plugin.
  244. */
  245. private void loadIdentities() {
  246. try {
  247. final Map<String, InputStream> identityStreams = getResourceManager()
  248. .getResourcesStartingWithAsInputStreams("META-INF/identities/");
  249. unloadIdentities();
  250. for (Map.Entry<String, InputStream> entry : identityStreams.entrySet()) {
  251. final String name = entry.getKey();
  252. final InputStream stream = entry.getValue();
  253. if (name.endsWith("/") || stream == null) {
  254. // Don't try to load folders or null streams
  255. continue;
  256. }
  257. synchronized (configProviders) {
  258. try {
  259. final ConfigProvider configProvider = new ConfigFileBackedConfigProvider(
  260. stream, false);
  261. identityController.addConfigProvider(configProvider);
  262. configProviders.add(configProvider);
  263. } catch (final InvalidIdentityFileException ex) {
  264. eventBus.publish(new UserErrorEvent(ErrorLevel.MEDIUM, ex,
  265. "Error with identity file '" + name + "' in plugin '"
  266. + metaData.getName() + "'", ""));
  267. }
  268. }
  269. }
  270. } catch (final IOException ioe) {
  271. eventBus.publish(new UserErrorEvent(ErrorLevel.MEDIUM, ioe,
  272. "Error finding identities in plugin '" + metaData.getName() + "'", ""));
  273. }
  274. }
  275. /**
  276. * Unload any identities loaded by this plugin.
  277. */
  278. private void unloadIdentities() {
  279. synchronized (configProviders) {
  280. for (ConfigProvider identity : configProviders) {
  281. identityController.removeConfigProvider(identity);
  282. }
  283. configProviders.clear();
  284. }
  285. }
  286. /**
  287. * Update provides list.
  288. */
  289. private void updateProvides() {
  290. // Remove us from any existing provides lists.
  291. synchronized (provides) {
  292. for (Service service : provides) {
  293. service.delProvider(this);
  294. }
  295. provides.clear();
  296. }
  297. // Get services provided by this plugin
  298. final Collection<String> providesList = metaData.getServices();
  299. if (providesList != null) {
  300. for (String item : providesList) {
  301. final String[] bits = item.split(" ");
  302. final String name = bits[0];
  303. final String type = bits.length > 1 ? bits[1] : "misc";
  304. if (!name.equalsIgnoreCase("any") && !type.equalsIgnoreCase("export")) {
  305. final Service service = metaData.getManager().getService(type, name, true);
  306. synchronized (provides) {
  307. service.addProvider(this);
  308. provides.add(service);
  309. }
  310. }
  311. }
  312. }
  313. updateExports();
  314. }
  315. /**
  316. * Called when the plugin is updated using the updater. Reloads metaData and updates the list of
  317. * files.
  318. */
  319. public void pluginUpdated() {
  320. try {
  321. // Force a new resourcemanager just in case.
  322. updateClassList(getResourceManager(true));
  323. updateMetaData();
  324. updateProvides();
  325. getDefaults();
  326. } catch (IOException ioe) {
  327. eventBus.publish(new UserErrorEvent(ErrorLevel.MEDIUM, ioe,
  328. "There was an error updating " + metaData.getName(), ""));
  329. }
  330. }
  331. /**
  332. * Try to reload the metaData from the plugin.config file. If this fails, the old data will be
  333. * used still.
  334. *
  335. * @return true if metaData was reloaded ok, else false.
  336. */
  337. private boolean updateMetaData() {
  338. metaData.load();
  339. return !metaData.hasErrors();
  340. }
  341. /**
  342. * Gets a resource manager for this plugin
  343. *
  344. * @return The resource manager for this plugin
  345. *
  346. * @throws IOException if there is any problem getting a ResourceManager for this plugin
  347. */
  348. public ResourceManager getResourceManager() throws IOException {
  349. return getResourceManager(false);
  350. }
  351. /**
  352. * Get the resource manager for this plugin
  353. *
  354. * @return The resource manager for this plugin
  355. *
  356. * @param forceNew Force a new resource manager rather than using the old one.
  357. *
  358. * @throws IOException if there is any problem getting a ResourceManager for this plugin
  359. * @since 0.6
  360. */
  361. public synchronized ResourceManager getResourceManager(final boolean forceNew) throws
  362. IOException {
  363. if (resourceManager == null || forceNew) {
  364. resourceManager = ResourceManager.getResourceManager("jar://" + metaData.getPluginUrl().
  365. getPath());
  366. // Clear the resourcemanager in 10 seconds to stop us holding the file open
  367. new Timer(filename + "-resourcemanagerTimer").schedule(new TimerTask() {
  368. /** {@inheritDoc} */
  369. @Override
  370. public void run() {
  371. resourceManager = null;
  372. }
  373. }, 10000);
  374. }
  375. return resourceManager;
  376. }
  377. /** {@inheritDoc} */
  378. @Override
  379. public final boolean isActive() {
  380. return isLoaded();
  381. }
  382. /** {@inheritDoc} */
  383. @Override
  384. public void activateServices() {
  385. loadPlugin();
  386. }
  387. /** {@inheritDoc} */
  388. @Override
  389. public String getProviderName() {
  390. return "Plugin: " + metaData.getFriendlyName() + " ("
  391. + metaData.getName() + " / " + getFilename() + ")";
  392. }
  393. /** {@inheritDoc} */
  394. @Override
  395. public List<Service> getServices() {
  396. synchronized (provides) {
  397. return new ArrayList<>(provides);
  398. }
  399. }
  400. /**
  401. * Is this plugin loaded?
  402. *
  403. * @return True if the plugin is currently (non-temporarily) loaded, false otherwise
  404. */
  405. public boolean isLoaded() {
  406. return plugin != null && !tempLoaded;
  407. }
  408. /**
  409. * Is this plugin temporarily loaded?
  410. *
  411. * @return True if this plugin is currently temporarily loaded, false otherwise
  412. */
  413. public boolean isTempLoaded() {
  414. return plugin != null && tempLoaded;
  415. }
  416. /**
  417. * Try to Load the plugin files temporarily.
  418. */
  419. public void loadPluginTemp() {
  420. if (isLoaded() || isTempLoaded()) {
  421. // Already loaded, don't do anything
  422. return;
  423. }
  424. tempLoaded = true;
  425. loadPlugin();
  426. }
  427. /**
  428. * Load any required plugins or services.
  429. *
  430. * @return True if all requirements have been satisfied, false otherwise
  431. */
  432. protected boolean loadRequirements() {
  433. return loadRequiredPlugins() && loadRequiredServices();
  434. }
  435. /**
  436. * Attempts to load all services that are required by this plugin.
  437. *
  438. * @return True iff all required services were found and satisfied
  439. */
  440. protected boolean loadRequiredServices() {
  441. final ServiceManager manager = metaData.getManager();
  442. for (String serviceInfo : metaData.getRequiredServices()) {
  443. final String[] parts = serviceInfo.split(" ", 2);
  444. if ("any".equals(parts[0])) {
  445. Service best = null;
  446. boolean found = false;
  447. for (Service service : manager.getServicesByType(parts[1])) {
  448. if (service.isActive()) {
  449. found = true;
  450. break;
  451. }
  452. best = service;
  453. }
  454. if (!found && best != null) {
  455. found = best.activate();
  456. }
  457. if (!found) {
  458. return false;
  459. }
  460. } else {
  461. final Service service = manager.getService(parts[1], parts[0]);
  462. if (service == null || !service.activate()) {
  463. return false;
  464. }
  465. }
  466. }
  467. return true;
  468. }
  469. /**
  470. * Attempts to load all plugins that are required by this plugin.
  471. *
  472. * @return True if all required plugins were found and loaded
  473. */
  474. protected boolean loadRequiredPlugins() {
  475. final String required = metaData.getRequirements().get("plugins");
  476. if (required != null) {
  477. for (String pluginName : required.split(",")) {
  478. final String[] data = pluginName.split(":");
  479. if (!data[0].trim().isEmpty() && !loadRequiredPlugin(data[0])) {
  480. return false;
  481. }
  482. }
  483. }
  484. if (metaData.getParent() != null) {
  485. return loadRequiredPlugin(metaData.getParent());
  486. }
  487. return true;
  488. }
  489. /**
  490. * Attempts to load the specified required plugin.
  491. *
  492. * @param name The name of the plugin to be loaded
  493. *
  494. * @return True if the plugin was found and loaded, false otherwise
  495. */
  496. protected boolean loadRequiredPlugin(final String name) {
  497. log.info("Loading required plugin '{}' for plugin {}",
  498. new Object[]{name, metaData.getName()});
  499. final PluginInfo pi = metaData.getManager().getPluginInfoByName(name);
  500. if (pi == null) {
  501. return false;
  502. }
  503. if (tempLoaded) {
  504. pi.loadPluginTemp();
  505. } else {
  506. pi.loadPlugin();
  507. }
  508. return true;
  509. }
  510. /**
  511. * Load the plugin files.
  512. */
  513. public void loadPlugin() {
  514. if (isLoaded() || isLoading) {
  515. lastError = "Not Loading: (" + isLoaded() + "||" + isLoading + ")";
  516. return;
  517. }
  518. updateProvides();
  519. if (isTempLoaded()) {
  520. tempLoaded = false;
  521. if (!loadRequirements()) {
  522. tempLoaded = true;
  523. lastError = "Unable to satisfy dependencies for " + metaData.getName();
  524. return;
  525. }
  526. try {
  527. plugin.load(this, getObjectGraph());
  528. plugin.onLoad();
  529. } catch (LinkageError | Exception e) {
  530. lastError = "Error in onLoad for " + metaData.getName() + ":"
  531. + e.getMessage();
  532. eventBus.publishAsync(new AppErrorEvent(ErrorLevel.MEDIUM, e, lastError, ""));
  533. unloadPlugin();
  534. }
  535. } else {
  536. isLoading = true;
  537. if (!loadRequirements()) {
  538. isLoading = false;
  539. lastError = "Unable to satisfy dependencies for " + metaData.getName();
  540. return;
  541. }
  542. loadIdentities();
  543. loadClass(metaData.getMainClass());
  544. if (isLoaded()) {
  545. //TODO plugin loading shouldn't be done from here, event bus shouldn't be here.
  546. eventBus.publishAsync(new PluginLoadedEvent(this));
  547. }
  548. isLoading = false;
  549. }
  550. }
  551. /**
  552. * Add the given Plugin as a child of this plugin.
  553. *
  554. * @param child Child to add
  555. */
  556. public void addChild(final PluginInfo child) {
  557. children.add(child);
  558. }
  559. /**
  560. * Remove the given Plugin as a child of this plugin.
  561. *
  562. * @param child Child to remove
  563. */
  564. public void delChild(final PluginInfo child) {
  565. children.remove(child);
  566. }
  567. /**
  568. * Returns a list of this plugin's children.
  569. *
  570. * @return List of child plugins
  571. */
  572. public List<PluginInfo> getChildren() {
  573. return Collections.unmodifiableList(children);
  574. }
  575. /**
  576. * Checks if this plugin has any children.
  577. *
  578. * @return true iff this plugin has children
  579. */
  580. public boolean hasChildren() {
  581. return !children.isEmpty();
  582. }
  583. /**
  584. * Initialises this plugin's classloader.
  585. */
  586. private void initialiseClassLoader() {
  587. if (pluginClassLoader == null) {
  588. final PluginClassLoader[] loaders = new PluginClassLoader[metaData.getParent() == null
  589. ? 0 : 1];
  590. if (metaData.getParent() != null) {
  591. final String parentName = metaData.getParent();
  592. final PluginInfo parent = metaData.getManager()
  593. .getPluginInfoByName(parentName);
  594. parent.addChild(this);
  595. loaders[0] = parent.getPluginClassLoader();
  596. if (loaders[0] == null) {
  597. // Not loaded? Try again...
  598. parent.loadPlugin();
  599. loaders[0] = parent.getPluginClassLoader();
  600. if (loaders[0] == null) {
  601. lastError = "Unable to get classloader from required parent '" + parentName
  602. + "' for " + metaData.getName();
  603. return;
  604. }
  605. }
  606. }
  607. pluginClassLoader = new PluginClassLoader(this, metaData.getManager().
  608. getGlobalClassLoader(), loaders);
  609. }
  610. }
  611. /**
  612. * Load the given classname.
  613. *
  614. * @param classname Class to load
  615. */
  616. private void loadClass(final String classname) {
  617. try {
  618. initialiseClassLoader();
  619. // Don't reload a class if its already loaded.
  620. if (pluginClassLoader.isClassLoaded(classname, true)) {
  621. lastError = "Classloader says we are already loaded.";
  622. return;
  623. }
  624. final Class<?> clazz = pluginClassLoader.loadClass(classname);
  625. if (clazz == null) {
  626. lastError = "Class '" + classname + "' was not able to load.";
  627. return;
  628. }
  629. // Only try and construct the main class, anything else should be constructed
  630. // by the plugin itself.
  631. if (classname.equals(metaData.getMainClass())) {
  632. final Object temp = getInjector().createInstance(clazz);
  633. if (temp instanceof Plugin) {
  634. final ValidationResponse prerequisites = ((Plugin) temp).checkPrerequisites();
  635. if (prerequisites.isFailure()) {
  636. if (!tempLoaded) {
  637. lastError = "Prerequisites for plugin not met. ('"
  638. + filename + ":" + metaData.getMainClass()
  639. + "' -> '" + prerequisites.getFailureReason() + "') ";
  640. eventBus.publish(new UserErrorEvent(ErrorLevel.LOW, null, lastError, ""));
  641. }
  642. } else {
  643. plugin = (Plugin) temp;
  644. log.debug("{}: Setting domain '{}'",
  645. new Object[]{metaData.getName(), getDomain()});
  646. plugin.setDomain(getDomain());
  647. if (!tempLoaded) {
  648. try {
  649. plugin.load(this, getObjectGraph());
  650. plugin.onLoad();
  651. } catch (LinkageError | Exception e) {
  652. lastError = "Error in onLoad for "
  653. + metaData.getName() + ":" + e.getMessage();
  654. eventBus.publishAsync(new AppErrorEvent(ErrorLevel.MEDIUM,
  655. e, lastError, ""));
  656. unloadPlugin();
  657. }
  658. }
  659. }
  660. }
  661. }
  662. } catch (ClassNotFoundException cnfe) {
  663. lastError = "Class not found ('" + filename + ":" + classname + ":"
  664. + classname.equals(metaData.getMainClass()) + "') - "
  665. + cnfe.getMessage();
  666. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, cnfe, lastError, ""));
  667. } catch (NoClassDefFoundError ncdf) {
  668. lastError = "Unable to instantiate plugin ('" + filename + ":"
  669. + classname + ":"
  670. + classname.equals(metaData.getMainClass())
  671. + "') - Unable to find class: " + ncdf.getMessage();
  672. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, ncdf, lastError, ""));
  673. } catch (VerifyError ve) {
  674. lastError = "Unable to instantiate plugin ('" + filename + ":"
  675. + classname + ":"
  676. + classname.equals(metaData.getMainClass())
  677. + "') - Incompatible: " + ve.getMessage();
  678. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, ve, lastError, ""));
  679. } catch (IllegalArgumentException ex) {
  680. lastError = "Unable to instantiate class for plugin " + metaData.getName()
  681. + ": " + classname;
  682. eventBus.publishAsync(new AppErrorEvent(ErrorLevel.LOW, ex, lastError, ""));
  683. }
  684. }
  685. /**
  686. * Gets the configuration domain that should be used by this plugin.
  687. *
  688. * @return The configuration domain to use.
  689. */
  690. public String getDomain() {
  691. return "plugin-" + metaData.getName();
  692. }
  693. /**
  694. * Unload the plugin if possible.
  695. */
  696. public void unloadPlugin() {
  697. unloadPlugin(false);
  698. }
  699. /**
  700. * Can this plugin be unloaded? Will return false if: - The plugin is persistent (all its
  701. * classes are loaded into the global class loader) - The plugin isn't currently loaded - The
  702. * metadata key "unloadable" is set to false, no or 0
  703. *
  704. * @return true if plugin can be unloaded
  705. */
  706. public boolean isUnloadable() {
  707. return !isPersistent() && (isTempLoaded() || isLoaded())
  708. && metaData.isUnloadable();
  709. }
  710. /**
  711. * Unload the plugin if possible.
  712. *
  713. * @param parentUnloading is our parent already unloading? (if so, don't call delChild)
  714. */
  715. private void unloadPlugin(final boolean parentUnloading) {
  716. if (isUnloadable()) {
  717. if (!isTempLoaded()) {
  718. // Unload all children
  719. for (PluginInfo child : children) {
  720. child.unloadPlugin(true);
  721. }
  722. // Delete ourself as a child of our parent.
  723. if (!parentUnloading) {
  724. if (metaData.getParent() != null) {
  725. final PluginInfo pi = metaData.getManager()
  726. .getPluginInfoByName(metaData.getParent());
  727. if (pi != null) {
  728. pi.delChild(this);
  729. }
  730. }
  731. }
  732. // Now unload ourself
  733. try {
  734. plugin.onUnload();
  735. } catch (Exception | LinkageError e) {
  736. lastError = "Error in onUnload for " + metaData.getName()
  737. + ":" + e + " - " + e.getMessage();
  738. eventBus.publishAsync(new AppErrorEvent(ErrorLevel.MEDIUM, e, lastError, ""));
  739. }
  740. //TODO plugin unloading shouldn't be done from here, event bus shouldn't be here.
  741. eventBus.publishAsync(new PluginUnloadedEvent(this));
  742. synchronized (provides) {
  743. for (Service service : provides) {
  744. service.delProvider(this);
  745. }
  746. provides.clear();
  747. }
  748. }
  749. unloadIdentities();
  750. tempLoaded = false;
  751. plugin = null;
  752. pluginClassLoader = null;
  753. }
  754. }
  755. /**
  756. * Get the list of Classes
  757. *
  758. * @return Classes this plugin has
  759. */
  760. public List<String> getClassList() {
  761. return Collections.unmodifiableList(myClasses);
  762. }
  763. /**
  764. * Is this a persistent plugin?
  765. *
  766. * @return true if persistent, else false
  767. */
  768. public boolean isPersistent() {
  769. return metaData.getPersistentClasses().contains("*");
  770. }
  771. /**
  772. * Does this plugin contain any persistent classes?
  773. *
  774. * @return true if this plugin contains any persistent classes, else false
  775. */
  776. public boolean hasPersistent() {
  777. return !metaData.getPersistentClasses().isEmpty();
  778. }
  779. /**
  780. * Get a list of all persistent classes in this plugin
  781. *
  782. * @return List of all persistent classes in this plugin
  783. */
  784. public Collection<String> getPersistentClasses() {
  785. if (isPersistent()) {
  786. return getClassList();
  787. } else {
  788. return metaData.getPersistentClasses();
  789. }
  790. }
  791. /**
  792. * Is this a persistent class?
  793. *
  794. * @param classname class to check persistence of
  795. *
  796. * @return true if file (or whole plugin) is persistent, else false
  797. */
  798. public boolean isPersistent(final String classname) {
  799. return isPersistent() || metaData.getPersistentClasses().contains(classname);
  800. }
  801. /**
  802. * String Representation of this plugin
  803. *
  804. * @return String Representation of this plugin
  805. */
  806. @Override
  807. public String toString() {
  808. return metaData.getFriendlyName() + " - " + filename;
  809. }
  810. /** {@inheritDoc} */
  811. @Override
  812. public int compareTo(@Nonnull final PluginInfo o) {
  813. return toString().compareTo(o.toString());
  814. }
  815. /**
  816. * Update exports list.
  817. */
  818. private void updateExports() {
  819. exports.clear();
  820. // Get exports provided by this plugin
  821. final Collection<String> exportsList = metaData.getExports();
  822. for (String item : exportsList) {
  823. final String[] bits = item.split(" ");
  824. if (bits.length > 2) {
  825. final String methodName = bits[0];
  826. final String methodClass = bits[2];
  827. final String serviceName = bits.length > 4 ? bits[4] : bits[0];
  828. // Add a provides for this
  829. final Service service = metaData.getManager().
  830. getService("export", serviceName, true);
  831. synchronized (provides) {
  832. service.addProvider(this);
  833. provides.add(service);
  834. }
  835. // Add is as an export
  836. exports.put(serviceName, new ExportInfo(methodName, methodClass, this));
  837. }
  838. }
  839. }
  840. /** {@inheritDoc} */
  841. @Override
  842. public ExportedService getExportedService(final String name) {
  843. if (exports.containsKey(name)) {
  844. return exports.get(name).getExportedService();
  845. } else {
  846. return null;
  847. }
  848. }
  849. /**
  850. * Does this plugin export the specified service?
  851. *
  852. * @param name Name of the service to check
  853. *
  854. * @return true iff the plugin exports the service
  855. */
  856. public boolean hasExportedService(final String name) {
  857. return exports.containsKey(name);
  858. }
  859. }