pluginmanager.java

来自「开源项目openfire的完整源程序」· Java 代码 · 共 708 行 · 第 1/2 页

JAVA
708
字号
    /**
     * Removes a plugin from the plugin list.
     *
     * @param plugin the plugin to remove.
     */
    public void removePlugin(Plugin plugin) {
        plugins.remove(plugin);
    }

    /**
     * Returns a Collection of Plugins.
     *
     * @return a Collection of Plugins.
     */
    public Collection getPlugins() {
        return plugins;
    }

    /**
     * Returns the instance of the plugin class initialized during startup.
     *
     * @param communicatorPlugin the plugin to find.
     * @return the instance of the plugin.
     */
    public Plugin getPlugin(Class communicatorPlugin) {
        Iterator iter = getPlugins().iterator();
        while (iter.hasNext()) {
            Plugin plugin = (Plugin)iter.next();
            if (plugin.getClass() == communicatorPlugin) {
                return plugin;
            }
        }
        return null;
    }

    /**
     * Loads and initalizes all Plugins.
     *
     * @see Plugin
     */
    public void initializePlugins() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                final Iterator iter = plugins.iterator();
                while (iter.hasNext()) {
                    long start = System.currentTimeMillis();
                    Plugin plugin = (Plugin)iter.next();
                    Log.debug("Trying to initialize " + plugin);
                    try {
                        plugin.initialize();
                    }
                    catch (Throwable e) {
                        Log.error(e);
                    }

                    long end = System.currentTimeMillis();
                    Log.debug("Took " + (end - start) + " ms. to load " + plugin);
                }
            }
        });

    }

    public void shutdown() {
        final Iterator pluginIter = plugins.iterator();
        while (pluginIter.hasNext()) {
            Plugin plugin = (Plugin)pluginIter.next();
            try {
                plugin.shutdown();
            }
            catch (Exception e) {
                Log.warning("Exception on shutdown of plugin.", e);
            }
        }
    }

    public void mainWindowActivated() {
    }

    public void mainWindowDeactivated() {
    }

    /**
     * Locates the best class loader based on context (see class description).
     *
     * @return The best parent classloader to use
     */
    private ClassLoader getParentClassLoader() {
        ClassLoader parent = Thread.currentThread().getContextClassLoader();
        if (parent == null) {
            parent = this.getClass().getClassLoader();
            if (parent == null) {
                parent = ClassLoader.getSystemClassLoader();
            }
        }
        return parent;
    }

    /**
     * Expands all plugin packs (.jar files located in the plugin dir with plugin.xml).
     */
    private void expandNewPlugins() {
        File[] jars = PLUGINS_DIRECTORY.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                boolean accept = false;
                String smallName = name.toLowerCase();
                if (smallName.endsWith(".jar")) {
                    accept = true;
                }
                return accept;
            }
        });

        // Do nothing if no jar or zip files were found
        if (jars == null) {
            return;
        }


        for (int i = 0; i < jars.length; i++) {
            if (jars[i].isFile()) {
                File file = jars[i];

                URL url = null;
                try {
                    url = file.toURL();
                }
                catch (MalformedURLException e) {
                    Log.error(e);
                }
                String name = URLFileSystem.getName(url);
                File directory = new File(PLUGINS_DIRECTORY, name);
                if (directory.exists() && directory.isDirectory()) {
                    // Check to see if directory contains the plugin.xml file.
                    // If not, delete directory.
                    File pluginXML = new File(directory, "plugin.xml");
                    if (pluginXML.exists()) {
                        if (pluginXML.lastModified() < file.lastModified()) {
                            uninstall(directory);
                            unzipPlugin(file, directory);
                        }
                        continue;
                    }

                    uninstall(directory);
                }
                else {
                    // Unzip contents into directory
                    unzipPlugin(file, directory);
                }
            }
        }
    }

    private void loadPublicPlugins() {
        // First, expand all plugins that have yet to be expanded.
        expandNewPlugins();


        File[] files = PLUGINS_DIRECTORY.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return dir.isDirectory();
            }
        });

        // Do nothing if no jar or zip files were found
        if (files == null) {
            return;
        }

        for (int i = 0; i < files.length; i++) {
            File file = files[i];

            File pluginXML = new File(file, "plugin.xml");
            if (pluginXML.exists()) {
                try {
                    classLoader.addPlugin(file);
                    loadPublicPlugin(file);
                }
                catch (Throwable e) {
                    Log.error("Unable to load dirs", e);
                }
            }
        }
    }

    /**
     * Adds and installs a new plugin into Spark.
     *
     * @param plugin the plugin to install.
     * @throws Exception thrown if there was a problem loading the plugin.
     */
    public void addPlugin(PublicPlugin plugin) throws Exception {
        expandNewPlugins();

        URL url = new URL(plugin.getDownloadURL());
        String name = URLFileSystem.getName(url);
        File pluginDownload = new File(PluginManager.PLUGINS_DIRECTORY, name);

        ((PluginClassLoader)getParentClassLoader()).addPlugin(pluginDownload);

        Plugin pluginClass = loadPublicPlugin(pluginDownload);

        Log.debug("Trying to initialize " + pluginClass);
        pluginClass.initialize();
    }

    /**
     * Unzips a plugin from a JAR file into a directory. If the JAR file
     * isn't a plugin, this method will do nothing.
     *
     * @param file the JAR file
     * @param dir  the directory to extract the plugin to.
     */
    private void unzipPlugin(File file, File dir) {
        try {
            ZipFile zipFile = new JarFile(file);
            // Ensure that this JAR is a plugin.
            if (zipFile.getEntry("plugin.xml") == null) {
                return;
            }
            dir.mkdir();
            for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
                JarEntry entry = (JarEntry)e.nextElement();
                File entryFile = new File(dir, entry.getName());
                // Ignore any manifest.mf entries.
                if (entry.getName().toLowerCase().endsWith("manifest.mf")) {
                    continue;
                }
                if (!entry.isDirectory()) {
                    entryFile.getParentFile().mkdirs();
                    FileOutputStream out = new FileOutputStream(entryFile);
                    InputStream zin = zipFile.getInputStream(entry);
                    byte[] b = new byte[512];
                    int len = 0;
                    while ((len = zin.read(b)) != -1) {
                        out.write(b, 0, len);
                    }
                    out.flush();
                    out.close();
                    zin.close();
                }
            }
            zipFile.close();
            zipFile = null;
        }
        catch (Throwable e) {
            Log.error("Error unzipping plugin", e);
        }
    }

    /**
     * Returns a collection of all public plugins.
     *
     * @return the collection of public plugins.
     */
    public List<PublicPlugin> getPublicPlugins() {
        return publicPlugins;
    }

    private void uninstall(File pluginDir) {
        File[] files = pluginDir.listFiles();
        for (int i = 0; i < files.length; i++) {
            File f = files[i];
            if (f.isFile()) {
                f.delete();
            }
        }

        File libDir = new File(pluginDir, "lib");

        File[] libs = libDir.listFiles();
        final int no = libs != null ? libs.length : 0;
        for (int i = 0; i < no; i++) {
            File f = libs[i];
            f.delete();
        }

        libDir.delete();

        pluginDir.delete();
    }

    /**
     * Removes and uninstall a plugin from Spark.
     *
     * @param plugin the plugin to uninstall.
     */
    public void removePublicPlugin(PublicPlugin plugin) {
        for (PublicPlugin publicPlugin : getPublicPlugins()) {
            if (plugin.getName().equals(publicPlugin.getName())) {
                publicPlugins.remove(plugin);
            }
        }
    }

    /**
     * Returns true if the specified plugin is installed.
     *
     * @param plugin the <code>PublicPlugin</code> plugin to check.
     * @return true if installed.
     */
    public boolean isInstalled(PublicPlugin plugin) {
        for (PublicPlugin publicPlugin : getPublicPlugins()) {
            if (plugin.getName().equals(publicPlugin.getName())) {
                return true;
            }
        }

        return false;
    }

    /**
     * Checks the plugin for required operating system.
     *
     * @param plugin the Plugin element to check.
     * @return true if the operating system is ok for the plugin to run on.
     */
    private boolean isOperatingSystemOK(Element plugin) {
        // Check for operating systems
        try {

            final Element osElement = (Element)plugin.selectSingleNode("os");
            if (osElement != null) {
                String operatingSystem = osElement.getText();

                boolean ok = false;

                final String currentOS = JiveInfo.getOS().toLowerCase();

                // Iterate through comma delimited string
                StringTokenizer tkn = new StringTokenizer(operatingSystem, ",");
                while (tkn.hasMoreTokens()) {
                    String os = tkn.nextToken().toLowerCase();
                    if (currentOS.contains(os) || currentOS.equalsIgnoreCase(os)) {
                        ok = true;
                    }
                }

                if (!ok) {
                    Log.debug("Unable to load plugin " + plugin.selectSingleNode("name").getText() + " due to invalid operating system. Required OS = " + operatingSystem);
                    return false;
                }
            }
        }
        catch (Exception e) {
            Log.error(e);
        }

        return true;
    }


}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?