Example usage for org.dom4j.io SAXReader setEncoding

List of usage examples for org.dom4j.io SAXReader setEncoding

Introduction

In this page you can find the example usage for org.dom4j.io SAXReader setEncoding.

Prototype

public void setEncoding(String encoding) 

Source Link

Document

Sets encoding used for InputSource (null means system default encoding)

Usage

From source file:org.jivesoftware.openfire.container.PluginManager.java

License:Open Source License

/**
 * Loads a plug-in module into the container. Loading consists of the
 * following steps:<ul>//from w ww.  jav  a 2  s.  c o  m
 * <p/>
 * <li>Add all jars in the <tt>lib</tt> dir (if it exists) to the class loader</li>
 * <li>Add all files in <tt>classes</tt> dir (if it exists) to the class loader</li>
 * <li>Locate and load <tt>module.xml</tt> into the context</li>
 * <li>For each jive.module entry, load the given class as a module and start it</li>
 * <p/>
 * </ul>
 *
 * @param pluginDir the plugin directory.
 */
private void loadPlugin(File pluginDir) {
    // Only load the admin plugin during setup mode.
    if (XMPPServer.getInstance().isSetupMode() && !(pluginDir.getName().equals("admin"))) {
        return;
    }
    Log.debug("PluginManager: Loading plugin " + pluginDir.getName());
    Plugin plugin;
    try {
        File pluginConfig = new File(pluginDir, "plugin.xml");
        if (pluginConfig.exists()) {
            SAXReader saxReader = new SAXReader();
            saxReader.setEncoding("UTF-8");
            Document pluginXML = saxReader.read(pluginConfig);

            // See if the plugin specifies a version of Openfire
            // required to run.
            Element minServerVersion = (Element) pluginXML.selectSingleNode("/plugin/minServerVersion");
            if (minServerVersion != null) {
                Version requiredVersion = new Version(minServerVersion.getTextTrim());
                Version currentVersion = XMPPServer.getInstance().getServerInfo().getVersion();
                if (requiredVersion.isNewerThan(currentVersion)) {
                    String msg = "Ignoring plugin " + pluginDir.getName() + ": requires " + "server version "
                            + requiredVersion;
                    Log.warn(msg);
                    System.out.println(msg);
                    return;
                }
            }

            PluginClassLoader pluginLoader;

            // Check to see if this is a child plugin of another plugin. If it is, we
            // re-use the parent plugin's class loader so that the plugins can interact.
            Element parentPluginNode = (Element) pluginXML.selectSingleNode("/plugin/parentPlugin");

            String pluginName = pluginDir.getName();
            String webRootKey = pluginName + ".webRoot";
            String classesDirKey = pluginName + ".classes";
            String webRoot = System.getProperty(webRootKey);
            String classesDir = System.getProperty(classesDirKey);

            if (webRoot != null) {
                final File compilationClassesDir = new File(pluginDir, "classes");
                if (!compilationClassesDir.exists()) {
                    compilationClassesDir.mkdir();
                }
                compilationClassesDir.deleteOnExit();
            }

            if (parentPluginNode != null) {
                String parentPlugin = parentPluginNode.getTextTrim();
                // See if the parent is already loaded.
                if (plugins.containsKey(parentPlugin)) {
                    pluginLoader = classloaders.get(getPlugin(parentPlugin));
                    pluginLoader.addDirectory(pluginDir, classesDir != null);

                } else {
                    // See if the parent plugin exists but just hasn't been loaded yet.
                    // This can only be the case if this plugin name is alphabetically before
                    // the parent.
                    if (pluginName.compareTo(parentPlugin) < 0) {
                        // See if the parent exists.
                        File file = new File(pluginDir.getParentFile(), parentPlugin + ".jar");
                        if (file.exists()) {
                            // Silently return. The child plugin will get loaded up on the next
                            // plugin load run after the parent.
                            return;
                        } else {
                            file = new File(pluginDir.getParentFile(), parentPlugin + ".war");
                            if (file.exists()) {
                                // Silently return. The child plugin will get loaded up on the next
                                // plugin load run after the parent.
                                return;
                            } else {
                                String msg = "Ignoring plugin " + pluginName + ": parent plugin " + parentPlugin
                                        + " not present.";
                                Log.warn(msg);
                                System.out.println(msg);
                                return;
                            }
                        }
                    } else {
                        String msg = "Ignoring plugin " + pluginName + ": parent plugin " + parentPlugin
                                + " not present.";
                        Log.warn(msg);
                        System.out.println(msg);
                        return;
                    }
                }
            }
            // This is not a child plugin, so create a new class loader.
            else {
                pluginLoader = new PluginClassLoader();
                pluginLoader.addDirectory(pluginDir, classesDir != null);
            }

            // Check to see if development mode is turned on for the plugin. If it is,
            // configure dev mode.

            PluginDevEnvironment dev = null;
            if (webRoot != null || classesDir != null) {
                dev = new PluginDevEnvironment();

                System.out.println("Plugin " + pluginName + " is running in development mode.");
                Log.info("Plugin " + pluginName + " is running in development mode.");
                if (webRoot != null) {
                    File webRootDir = new File(webRoot);
                    if (!webRootDir.exists()) {
                        // Ok, let's try it relative from this plugin dir?
                        webRootDir = new File(pluginDir, webRoot);
                    }

                    if (webRootDir.exists()) {
                        dev.setWebRoot(webRootDir);
                    }
                }

                if (classesDir != null) {
                    File classes = new File(classesDir);
                    if (!classes.exists()) {
                        // ok, let's try it relative from this plugin dir?
                        classes = new File(pluginDir, classesDir);
                    }

                    if (classes.exists()) {
                        dev.setClassesDir(classes);
                        pluginLoader.addURLFile(classes.getAbsoluteFile().toURI().toURL());
                    }
                }
            }

            String className = pluginXML.selectSingleNode("/plugin/class").getText().trim();
            plugin = (Plugin) pluginLoader.loadClass(className).newInstance();
            if (parentPluginNode != null) {
                String parentPlugin = parentPluginNode.getTextTrim();
                // See if the parent is already loaded.
                if (plugins.containsKey(parentPlugin)) {
                    pluginLoader = classloaders.get(getPlugin(parentPlugin));
                    classloaders.put(plugin, pluginLoader);
                }
            }

            plugins.put(pluginName, plugin);
            pluginDirs.put(plugin, pluginDir);

            // If this is a child plugin, register it as such.
            if (parentPluginNode != null) {
                String parentPlugin = parentPluginNode.getTextTrim();
                List<String> childrenPlugins = parentPluginMap.get(plugins.get(parentPlugin));
                if (childrenPlugins == null) {
                    childrenPlugins = new ArrayList<String>();
                    parentPluginMap.put(plugins.get(parentPlugin), childrenPlugins);
                }
                childrenPlugins.add(pluginName);
                // Also register child to parent relationship.
                childPluginMap.put(plugin, parentPlugin);
            } else {
                // Only register the class loader in the case of this not being
                // a child plugin.
                classloaders.put(plugin, pluginLoader);
            }

            // Check the plugin's database schema (if it requires one).
            if (!DbConnectionManager.getSchemaManager().checkPluginSchema(plugin)) {
                // The schema was not there and auto-upgrade failed.
                Log.error(pluginName + " - " + LocaleUtils.getLocalizedString("upgrade.database.failure"));
                System.out.println(
                        pluginName + " - " + LocaleUtils.getLocalizedString("upgrade.database.failure"));
            }

            // Load any JSP's defined by the plugin.
            File webXML = new File(pluginDir, "web" + File.separator + "WEB-INF" + File.separator + "web.xml");
            if (webXML.exists()) {
                PluginServlet.registerServlets(this, plugin, webXML);
            }
            // Load any custom-defined servlets.
            File customWebXML = new File(pluginDir,
                    "web" + File.separator + "WEB-INF" + File.separator + "web-custom.xml");
            if (customWebXML.exists()) {
                PluginServlet.registerServlets(this, plugin, customWebXML);
            }

            if (dev != null) {
                pluginDevelopment.put(plugin, dev);
            }

            // Configure caches of the plugin
            configureCaches(pluginDir, pluginName);

            // Init the plugin.
            ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(pluginLoader);
            plugin.initializePlugin(this, pluginDir);
            Thread.currentThread().setContextClassLoader(oldLoader);

            // If there a <adminconsole> section defined, register it.
            Element adminElement = (Element) pluginXML.selectSingleNode("/plugin/adminconsole");
            if (adminElement != null) {
                Element appName = (Element) adminElement
                        .selectSingleNode("/plugin/adminconsole/global/appname");
                if (appName != null) {
                    // Set the plugin name so that the proper i18n String can be loaded.
                    appName.addAttribute("plugin", pluginName);
                }
                // If global images are specified, override their URL.
                Element imageEl = (Element) adminElement
                        .selectSingleNode("/plugin/adminconsole/global/logo-image");
                if (imageEl != null) {
                    imageEl.setText("plugins/" + pluginName + "/" + imageEl.getText());
                    // Set the plugin name so that the proper i18n String can be loaded.
                    imageEl.addAttribute("plugin", pluginName);
                }
                imageEl = (Element) adminElement.selectSingleNode("/plugin/adminconsole/global/login-image");
                if (imageEl != null) {
                    imageEl.setText("plugins/" + pluginName + "/" + imageEl.getText());
                    // Set the plugin name so that the proper i18n String can be loaded.
                    imageEl.addAttribute("plugin", pluginName);
                }
                // Modify all the URL's in the XML so that they are passed through
                // the plugin servlet correctly.
                List urls = adminElement.selectNodes("//@url");
                for (Object url : urls) {
                    Attribute attr = (Attribute) url;
                    attr.setValue("plugins/" + pluginName + "/" + attr.getValue());
                }
                // In order to internationalize the names and descriptions in the model,
                // we add a "plugin" attribute to each tab, sidebar, and item so that
                // the the renderer knows where to load the i18n Strings from.
                String[] elementNames = new String[] { "tab", "sidebar", "item" };
                for (String elementName : elementNames) {
                    List values = adminElement.selectNodes("//" + elementName);
                    for (Object value : values) {
                        Element element = (Element) value;
                        // Make sure there's a name or description. Otherwise, no need to
                        // override i18n settings.
                        if (element.attribute("name") != null || element.attribute("value") != null) {
                            element.addAttribute("plugin", pluginName);
                        }
                    }
                }

                AdminConsole.addModel(pluginName, adminElement);
            }
            firePluginCreatedEvent(pluginName, plugin);
        } else {
            Log.warn("Plugin " + pluginDir + " could not be loaded: no plugin.xml file found");
        }
    } catch (Throwable e) {
        Log.error("Error loading plugin: " + pluginDir, e);
    }
}

From source file:org.jivesoftware.openfire.container.PluginManager.java

License:Open Source License

/**
 * Returns the value of an element selected via an xpath expression from
 * a Plugin's plugin.xml file./*from   ww w .java 2  s.  c om*/
 *
 * @param plugin the plugin.
 * @param xpath  the xpath expression.
 * @return the value of the element selected by the xpath expression.
 */
private String getElementValue(Plugin plugin, String xpath) {
    File pluginDir = pluginDirs.get(plugin);
    if (pluginDir == null) {
        return null;
    }
    try {
        File pluginConfig = new File(pluginDir, "plugin.xml");
        if (pluginConfig.exists()) {
            SAXReader saxReader = new SAXReader();
            saxReader.setEncoding("UTF-8");
            Document pluginXML = saxReader.read(pluginConfig);
            Element element = (Element) pluginXML.selectSingleNode(xpath);
            if (element != null) {
                return element.getTextTrim();
            }
        }
    } catch (Exception e) {
        Log.error(e.getMessage(), e);
    }
    return null;
}

From source file:org.jivesoftware.openfire.container.PluginMetadataHelper.java

License:Apache License

/**
 * Returns the value of an element selected via an xpath expression from
 * a Plugin's plugin.xml file.//from ww  w . ja va2  s.  c  o m
 *
 * @param pluginDir the path of the plugin directory.
 * @param xpath     the xpath expression.
 * @return the value of the element selected by the xpath expression.
 */
static String getElementValue(Path pluginDir, String xpath) {
    if (pluginDir == null) {
        return null;
    }
    try {
        final Path pluginConfig = pluginDir.resolve("plugin.xml");
        if (Files.exists(pluginConfig)) {
            final SAXReader saxReader = new SAXReader();
            saxReader.setEncoding("UTF-8");
            final Document pluginXML = saxReader.read(pluginConfig.toFile());
            final Element element = (Element) pluginXML.selectSingleNode(xpath);
            if (element != null) {
                return element.getTextTrim();
            }
        }
    } catch (Exception e) {
        Log.error("Unable to get element value '{}' from plugin.xml of plugin in '{}':", xpath, pluginDir, e);
    }
    return null;
}

From source file:org.jivesoftware.openfire.crowd.CrowdVCardProvider.java

License:Open Source License

/**
 * @see org.jivesoftware.openfire.vcard.DefaultVCardProvider#loadVCard(java.lang.String)
 *///w  w  w .j ava 2s.  com
@Override
public Element loadVCard(String username) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("loadvcard:" + username);
    }

    if (MUTEX.containsKey(username)) {
        // preventing looping
        return null;
    }

    try {
        MUTEX.put(username, username);

        Element vcard = super.loadVCard(username);

        if (vcard == null) {
            CrowdUserProvider userProvider = (CrowdUserProvider) UserManager.getUserProvider();
            try {
                User user = userProvider.getCrowdUser(username);
                String str = VCARD_TEMPLATE.replace("@displayname@", user.displayName)
                        .replace("@lastname@", user.lastName).replace("@firstname@", user.firstName)
                        .replace("@email@", user.email).replace("@nickname@", username);

                SAXReader xmlReader = new SAXReader();
                xmlReader.setEncoding("UTF-8");

                vcard = xmlReader.read(new StringReader(str)).getRootElement();

            } catch (UserNotFoundException unfe) {
                LOG.error("Unable to find user:" + String.valueOf(username) + " for loading its vcard", unfe);
                return null;
            } catch (DocumentException de) {
                LOG.error("vcard parsing error", de);
                return null;
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug(vcard != null ? vcard.asXML() : "vcard is null");
            }

            // store this new vcard
            if (vcard != null) {
                try {
                    createVCard(username, vcard);
                } catch (AlreadyExistsException aee) {
                    LOG.error("Unable to create and store a new vcard for user:" + username
                            + "; one already exists", aee);
                }
            }
        }

        return vcard;

    } catch (RuntimeException re) {
        LOG.error("Failure occured when loading a vcard for user:" + username, re);
        throw re;
    } finally {
        MUTEX.remove(username);
    }
}

From source file:org.jivesoftware.openfire.OfflineMessageStore.java

License:Open Source License

@Override
public void start() throws IllegalStateException {
    super.start();
    // Initialize the pool of sax readers
    for (int i = 0; i < POOL_SIZE; i++) {
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        xmlReaders.add(xmlReader);/*from w ww. ja  v a  2  s  .  co  m*/
    }
    // Add this module as a user event listener so we can delete
    // all offline messages when a user is deleted
    UserEventDispatcher.addListener(this);
}

From source file:org.jivesoftware.openfire.PrivateStorage.java

License:Open Source License

@Override
public void start() throws IllegalStateException {
    super.start();
    // Initialize the pool of sax readers
    for (int i = 0; i < POOL_SIZE; i++) {
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        xmlReaders.add(xmlReader);/*from   www .  ja v a2  s. com*/
    }
    // Add this module as a user event listener so we can delete
    // all user properties when a user is deleted
    UserEventDispatcher.addListener(this);
}

From source file:org.jivesoftware.openfire.update.UpdateManager.java

License:Open Source License

private void processServerUpdateResponse(String response, boolean notificationsEnabled)
        throws DocumentException {
    // Reset last known update information
    serverUpdate = null;/*from  w ww.  j  av  a  2s .  c  o  m*/
    SAXReader xmlReader = new SAXReader();
    xmlReader.setEncoding("UTF-8");
    Element xmlResponse = xmlReader.read(new StringReader(response)).getRootElement();
    // Parse response and keep info as Update objects
    Element openfire = xmlResponse.element("openfire");
    if (openfire != null) {
        // A new version of openfire was found
        Version latestVersion = new Version(openfire.attributeValue("latest"));
        if (latestVersion.isNewerThan(XMPPServer.getInstance().getServerInfo().getVersion())) {
            String changelog = openfire.attributeValue("changelog");
            String url = openfire.attributeValue("url");
            // Keep information about the available server update
            serverUpdate = new Update("Openfire", latestVersion.getVersionString(), changelog, url);
        }
    }
    // Check if we need to send notifications to admins
    if (notificationsEnabled && isNotificationEnabled() && serverUpdate != null) {
        Collection<JID> admins = XMPPServer.getInstance().getAdmins();
        Message notification = new Message();
        notification.setFrom(serverName);
        notification.setBody(getNotificationMessage() + " " + serverUpdate.getComponentName() + " "
                + serverUpdate.getLatestVersion());
        for (JID jid : admins) {
            notification.setTo(jid);
            router.route(notification);
        }
    }
    // Save response in a file for later retrieval
    saveLatestServerInfo();
}

From source file:org.jivesoftware.openfire.update.UpdateManager.java

License:Open Source License

private void processAvailablePluginsResponse(String response, boolean notificationsEnabled)
        throws DocumentException {
    // Reset last known list of available plugins
    availablePlugins = new HashMap<String, AvailablePlugin>();

    // Parse response and keep info as AvailablePlugin objects
    SAXReader xmlReader = new SAXReader();
    xmlReader.setEncoding("UTF-8");
    Element xmlResponse = xmlReader.read(new StringReader(response)).getRootElement();
    Iterator plugins = xmlResponse.elementIterator("plugin");
    while (plugins.hasNext()) {
        Element plugin = (Element) plugins.next();
        String pluginName = plugin.attributeValue("name");
        String latestVersion = plugin.attributeValue("latest");
        String icon = plugin.attributeValue("icon");
        String readme = plugin.attributeValue("readme");
        String changelog = plugin.attributeValue("changelog");
        String url = plugin.attributeValue("url");
        String licenseType = plugin.attributeValue("licenseType");
        String description = plugin.attributeValue("description");
        String author = plugin.attributeValue("author");
        String minServerVersion = plugin.attributeValue("minServerVersion");
        String fileSize = plugin.attributeValue("fileSize");
        AvailablePlugin available = new AvailablePlugin(pluginName, description, latestVersion, author, icon,
                changelog, readme, licenseType, minServerVersion, url, fileSize);
        // Add plugin to the list of available plugins at js.org
        availablePlugins.put(pluginName, available);
    }//from  w  w w  .j a  v  a2s. c  o  m

    // Figure out local plugins that need to be updated
    buildPluginsUpdateList();

    // Check if we need to send notifications to admins
    if (notificationsEnabled && isNotificationEnabled() && !pluginUpdates.isEmpty()) {
        Collection<JID> admins = XMPPServer.getInstance().getAdmins();
        for (Update update : pluginUpdates) {
            Message notification = new Message();
            notification.setFrom(serverName);
            notification.setBody(getNotificationMessage() + " " + update.getComponentName() + " "
                    + update.getLatestVersion());
            for (JID jid : admins) {
                notification.setTo(jid);
                router.route(notification);
            }
        }
    }

    // Save information of available plugins
    saveAvailablePluginsInfo();
}

From source file:org.jivesoftware.openfire.update.UpdateManager.java

License:Open Source License

private void loadLatestServerInfo() {
    Document xmlResponse;/*w  w w .  ja va 2s.co m*/
    File file = new File(JiveGlobals.getHomeDirectory() + File.separator + "conf", "server-update.xml");
    if (!file.exists()) {
        return;
    }
    // Check read privs.
    if (!file.canRead()) {
        Log.warn("Cannot retrieve server updates. File must be readable: " + file.getName());
        return;
    }
    FileReader reader = null;
    try {
        reader = new FileReader(file);
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        xmlResponse = xmlReader.read(reader);
    } catch (Exception e) {
        Log.error("Error reading server-update.xml", e);
        return;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {
                // Do nothing
            }
        }
    }
    // Parse info and recreate update information (if still required)
    Element openfire = xmlResponse.getRootElement().element("openfire");
    if (openfire != null) {
        Version latestVersion = new Version(openfire.attributeValue("latest"));
        String changelog = openfire.attributeValue("changelog");
        String url = openfire.attributeValue("url");
        // Check if current server version is correct
        Version currentServerVersion = XMPPServer.getInstance().getServerInfo().getVersion();
        if (latestVersion.isNewerThan(currentServerVersion)) {
            serverUpdate = new Update("Openfire", latestVersion.getVersionString(), changelog, url);
        }
    }
}

From source file:org.jivesoftware.openfire.update.UpdateManager.java

License:Open Source License

private void loadAvailablePluginsInfo() {
    Document xmlResponse;/*from   w ww. j  a v  a 2  s. c  om*/
    File file = new File(JiveGlobals.getHomeDirectory() + File.separator + "conf", "available-plugins.xml");
    if (!file.exists()) {
        return;
    }
    // Check read privs.
    if (!file.canRead()) {
        Log.warn("Cannot retrieve available plugins. File must be readable: " + file.getName());
        return;
    }
    FileReader reader = null;
    try {
        reader = new FileReader(file);
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        xmlResponse = xmlReader.read(reader);
    } catch (Exception e) {
        Log.error("Error reading available-plugins.xml", e);
        return;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {
                // Do nothing
            }
        }
    }
    // Parse info and recreate available plugins
    Iterator it = xmlResponse.getRootElement().elementIterator("plugin");
    while (it.hasNext()) {
        Element plugin = (Element) it.next();
        String pluginName = plugin.attributeValue("name");
        String latestVersion = plugin.attributeValue("latest");
        String icon = plugin.attributeValue("icon");
        String readme = plugin.attributeValue("readme");
        String changelog = plugin.attributeValue("changelog");
        String url = plugin.attributeValue("url");
        String licenseType = plugin.attributeValue("licenseType");
        String description = plugin.attributeValue("description");
        String author = plugin.attributeValue("author");
        String minServerVersion = plugin.attributeValue("minServerVersion");
        String fileSize = plugin.attributeValue("fileSize");
        AvailablePlugin available = new AvailablePlugin(pluginName, description, latestVersion, author, icon,
                changelog, readme, licenseType, minServerVersion, url, fileSize);
        // Add plugin to the list of available plugins at js.org
        availablePlugins.put(pluginName, available);
    }
}