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:de.codecentric.multitool.xml.XmlLibrary.java

License:Apache License

/**
 * Liest ein XML-Document aus einer Datei ein.
 * /*w  ww.j  a v a2 s  .  c  om*/
 * | ${xmlDoc} = | Get Xml From File | ${RESOURCES}/data/trades/template1/diamosmo-channel.xml |
 */
public Document getXmlFromFile(String fileName) throws DocumentException {
    SAXReader reader = new SAXReader();
    reader.setEncoding(XML_ENCODING);
    return reader.read("file:" + fileName);
}

From source file:de.fct.companian.analyze.mvn.helper.PomHelper.java

License:Apache License

public PomHelper(File pomFile) throws DocumentException {
    this.pomFile = pomFile;
    this.document = null;

    SAXReader reader = new SAXReader();
    reader.setEncoding("ISO-8859-1");
    reader.setIgnoreComments(true);//  w  w w  .  j a  v a2  s  .  co  m
    reader.setValidation(false);

    try {
        this.document = reader.read(this.pomFile);
    } catch (Throwable t) {
        t.printStackTrace();
    }

    if (this.document != null) {
        Element projectElement = this.document.getRootElement();
        Namespace defaultNS = projectElement.getNamespace();
        if (logger.isDebugEnabled()) {
            logger.debug("extractPomInfo() using default namespace " + defaultNS.getURI());
        }

        Map<String, String> nsMap = new HashMap<String, String>();
        nsMap.put("mvn", defaultNS.getURI());

        this.nsContext = new SimpleNamespaceContext(nsMap);
    } else {
        throw new DocumentException("Could not create document.");
    }
}

From source file:de.thischwa.pmcms.model.tool.ImportBackup.java

License:LGPL

@Override
public void run() {
    logger.info("Try to import site from file: " + zipFile.getName());
    siteHolder.clear();//from w  w  w  . ja  v a 2 s.c  o m
    ZipInfo zipInfo;
    try {
        zipInfo = Zip.getEntryInfo(zipFile);
    } catch (IOException e1) {
        throw new FatalException("While getting infos for zip entries: " + e1.getMessage(), e1);
    }
    SAXReader reader = new SAXReader();
    reader.setEncoding(Constants.STANDARD_ENCODING);
    try {
        String xml = IOUtils.toString(zipInfo.getInputStream("db.xml"));
        // clean up invalid xml chars
        xml = Utils.stripNonValidXMLCharacters(xml);

        Document document = reader.read(IOUtils.toInputStream(xml));
        Element root = document.getRootElement();
        IBackupParser backupParser;
        String version = root.attributeValue("version");
        if (StringUtils.isBlank(version)) {
            backupParser = new BackupParser_old(root);
        } else if (version.equals(IBackupParser.DBXML_1) || version.equals(IBackupParser.DBXML_2)) {
            backupParser = new BackupParser_1(root, version);
        } else {
            throw new RuntimeException(String.format("No backup parser found for version %s.", version));
        }
        backupParser.setMonitor(monitor);
        backupParser.run();
        site = backupParser.getSite();
    } catch (Exception e) {
        e.printStackTrace();
        throw new FatalException("While reading db.xml: " + e.getMessage(), e);
    }

    if (this.monitor != null)
        this.monitor.done();

    // unzip
    try {
        zipInfo.removeEntry("db.xml");
        if (monitor != null)
            monitor.beginTask(
                    LabelHolder.get("zip.extract").concat(String.valueOf(zipInfo.getEntryKeys().size())), //$NON-NLS-1$
                    zipInfo.getEntryKeys().size());
        Zip.extract(InitializationManager.getSitesDir(), zipInfo, monitor);
    } catch (IOException e) {
        throw new FatalException("While unzipping files: " + e.getMessage(), e);
    }

    logger.debug("[" + site.getUrl() + "] successfull imported.");
}

From source file:dk.netarkivet.deploy.XmlStructure.java

License:Open Source License

/**
 * Loading the file into the document data structure.
 *
 * @param f The XML file to be loaded./*from   ww w  .  ja v  a2 s .  co m*/
 * @param encoding the encoding to use to read the file
 * @return The XML file loaded into the document data structure
 * @throws IOFailure If the file was not correctly read
 */
private Document loadDocument(File f, final String encoding) throws IOFailure {
    ArgumentNotValid.checkNotNull(f, "File f");
    SAXReader reader = new SAXReader();
    reader.setEncoding(encoding);
    if (!f.canRead()) {
        String msg = "Could not read file: '" + f.getAbsolutePath() + "'";
        log.debug(msg);
        throw new IOFailure(msg);
    }
    try {
        return reader.read(f);
    } catch (DocumentException e) {
        String msg = "Could not parse file: '" + f.getAbsolutePath() + "' as XML.";
        log.warn(msg, e);
        throw new IOFailure(msg, e);
    }
}

From source file:net.sf.kraken.KrakenPlugin.java

License:Open Source License

/**
 * Returns the web options config for the given transport, if it exists.
 *
 * @param type type of the transport we want the options config for.
 * @return XML document with the options config.
 *///ww w  .j  av  a 2  s.c om
public Document getOptionsConfig(TransportType type) {
    // Load any custom-defined servlets.
    File optConf = new File(this.pluginDirectory, "web" + File.separator + "WEB-INF" + File.separator
            + "options" + File.separator + type.toString() + ".xml");
    Document optConfXML;
    try {
        FileReader reader = new FileReader(optConf);
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        optConfXML = xmlReader.read(reader);
    } catch (FileNotFoundException e) {
        // Non-existent: Return empty config
        optConfXML = DocumentHelper.createDocument();
        optConfXML.addElement("optionsconfig");
    } catch (DocumentException e) {
        // Bad config: Return empty config
        optConfXML = DocumentHelper.createDocument();
        optConfXML.addElement("optionsconfig");
    }
    return optConfXML;
}

From source file:net.sf.kraken.KrakenPlugin.java

License:Open Source License

/**
 * Returns the web global options, if it exists.
 *
 * @return XML document with the options config.
 *///w  w  w. j  a  v a  2  s .  c om
public Document getOptionsConfig() {
    // Load any custom-defined servlets.
    File optConf = new File(this.pluginDirectory,
            "web" + File.separator + "WEB-INF" + File.separator + "options" + File.separator + "global.xml");
    Document optConfXML;
    try {
        FileReader reader = new FileReader(optConf);
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        optConfXML = xmlReader.read(reader);
    } catch (FileNotFoundException e) {
        // Non-existent: Return empty config
        optConfXML = DocumentHelper.createDocument();
        optConfXML.addElement("optionsconfig");
    } catch (DocumentException e) {
        // Bad config: Return empty config
        optConfXML = DocumentHelper.createDocument();
        optConfXML.addElement("optionsconfig");
    }
    return optConfXML;
}

From source file:org.b5chat.crossfire.core.plugin.PluginCacheConfigurator.java

License:Open Source License

public void configure(String pluginName) {
    try {/*from  w  w w.j av  a2 s . c om*/
        SAXReader saxReader = new SAXReader();
        saxReader.setEncoding("UTF-8");
        Document cacheXml = saxReader.read(configDataStream);
        @SuppressWarnings("unchecked")
        List<Node> mappings = cacheXml.selectNodes("/cache-config/cache-mapping");
        for (Node mapping : mappings) {
            registerCache(pluginName, mapping);
        }
    } catch (DocumentException e) {
        Log.error(e.getMessage(), e);
    }
}

From source file:org.b5chat.crossfire.core.plugin.PluginManager.java

License:Open Source License

/**
 * Loads a plug-in module into the container. Loading consists of the
 * following steps:<ul>//from   w w w .ja  va2s. c om
 * <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 b5chat.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());
    IPlugin 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 crossfire
            // required to run.
            Element minServerVersion = (Element) pluginXML.selectSingleNode("/plugin/minServerVersion");
            if (minServerVersion != null) {
                String requiredVersion = minServerVersion.getTextTrim();
                Version version = XmppServer.getInstance().getServerInfo().getVersion();
                String hasVersion = version.getMajor() + "." + version.getMinor() + "." + version.getMicro();
                if (hasVersion.compareTo(requiredVersion) < 0) {
                    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("IPlugin " + pluginName + " is running in development mode.");
                Log.info("IPlugin " + 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 = (IPlugin) 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.
                @SuppressWarnings("unchecked")
                List<Object> 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) {
                    @SuppressWarnings("unchecked")
                    List<Object> 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("IPlugin " + pluginDir + " could not be loaded: no plugin.xml file found");
        }
    } catch (Throwable e) {
        Log.error("Error loading plugin: " + pluginDir, e);
    }
}

From source file:org.b5chat.crossfire.core.plugin.PluginManager.java

License:Open Source License

/**
 * Returns the value of an element selected via an xpath expression from
 * a IPlugin's plugin.xml file./*from  w ww  .j a v  a2  s  .  c o  m*/
 *
 * @param plugin the plugin.
 * @param xpath  the xpath expression.
 * @return the value of the element selected by the xpath expression.
 */
private String getElementValue(IPlugin 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.b5chat.crossfire.xmpp.privacy.PrivacyListProvider.java

License:Open Source License

public PrivacyListProvider() {
    super();/*from   w  w  w .  j av  a 2s  . c om*/
    // 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);
    }

    // Load the total number of privacy lists in the database. We're looking
    // for the (very common) special case that there are no privacy lists stored.
    // In that case, we can optimize away many database calls. In the future, a
    // better general-case solution may be to cache all privacy lists defined
    // if there are less than, say, 500.
    privacyListCount = new AtomicInteger(0);
    loadPrivacyListCount();
}