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

PluginInfo.java 32KB

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