Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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