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

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