Example usage for org.dom4j Element getText

List of usage examples for org.dom4j Element getText

Introduction

In this page you can find the example usage for org.dom4j Element getText.

Prototype

String getText();

Source Link

Document

Returns the text value of this element without recursing through child elements.

Usage

From source file:de.fmaul.android.cmis.repo.CmisItem.java

License:Apache License

private Date getModificationDate(Element entry) {
    Element updated = entry.element("updated");
    if (updated != null) {
        return parseXmlDate(updated.getText());
    } else/*ww w  .  jav  a  2s.  c om*/
        return null;
}

From source file:de.fmaul.android.cmis.repo.CmisItem.java

License:Apache License

private String getAuthorName(Element entry) {
    Element author = entry.element("author");
    if (author != null) {
        Element name = author.element("name");
        if (name != null) {
            return name.getText();
        }/* w  ww .j av a  2  s . c  o  m*/
    }
    return "";
}

From source file:de.fmaul.android.cmis.utils.FeedUtils.java

License:Apache License

public static List<String> getWorkspacesFromRepoFeed(Document doc) {
    List<String> listWorkspace = new ArrayList<String>(2);
    if (doc != null) {
        List<Element> workspaces = doc.getRootElement().elements("workspace");
        if (workspaces.size() > 0) {
            for (Element workspace : workspaces) {
                Element repoInfo = workspace.element(CMISRA_REPO_INFO);
                Element repoId = repoInfo.element(CMIS_REPO_NAME);
                listWorkspace.add(repoId.getText());
            }/*  w  w w.j  a  v  a 2 s  .  c  om*/
        }
    }
    return listWorkspace;
}

From source file:de.fmaul.android.cmis.utils.FeedUtils.java

License:Apache License

public static int getNumItemsFeed(Document doc) {
    if (doc != null) {
        Element numItems = doc.getRootElement().element(CMISRA_NUMITEMS);
        if (numItems != null) {
            return Integer.parseInt(numItems.getText());
        }// w  ww.jav  a2s.c  o m
    }
    return 0;
}

From source file:de.fmaul.android.cmis.utils.FeedUtils.java

License:Apache License

public static Map<String, ArrayList<CmisProperty>> getCmisRepositoryProperties(Element feedEntry) {
    Map<String, ArrayList<CmisProperty>> infoServerList = new HashMap<String, ArrayList<CmisProperty>>();
    ArrayList<CmisProperty> propsList = new ArrayList<CmisProperty>();
    ArrayList<CmisProperty> propsCapabilities = new ArrayList<CmisProperty>();
    ArrayList<CmisProperty> propsACLCapabilities = new ArrayList<CmisProperty>();

    Element objectElement = feedEntry.element(CMISRA_REPO_INFO);
    if (objectElement != null) {
        List<Element> properties = objectElement.elements();
        for (Element property : properties) {
            if (CMIS_REPO_CAPABILITES.equals(property.getQName())) {
                List<Element> props = property.elements();
                for (Element prop : props) {
                    propsCapabilities.add(new CmisProperty(null, null, null,
                            prop.getName().replace("capability", ""), prop.getText()));
                }//from   w w  w.j ava  2s.  c o  m
            } else if (CMIS_REPO_ACL_CAPABILITES.equals(property.getQName())) {
                /*List<Element> props = property.elements();
                for (Element prop : props) {
                   propsACLCapabilities.add(new CmisProperty(null, null, null, prop.getName().replace("cmis:", ""), prop.getText()));
                }*/
            } else {
                propsList.add(new CmisProperty(null, null, null, property.getName(), property.getText()));
            }
        }
        infoServerList.put(Server.INFO_GENERAL, propsList);
        infoServerList.put(Server.INFO_CAPABILITIES, propsCapabilities);
        infoServerList.put(Server.INFO_ACL_CAPABILITIES, propsACLCapabilities);
    }
    return infoServerList;
}

From source file:de.innovationgate.wga.common.beans.LuceneIndexFileRule.java

License:Apache License

/**
 * get rules from configfile element lucene
 * @param lucene configfile element//from  www . j ava  2 s  .  c om
 * @return list LuceneIndexFileRules
 */
public static List getRules(Element lucene) {
    ArrayList list = new ArrayList();
    Element rules = lucene.element("filerules");
    if (rules == null) {
        return null;
    }
    Iterator rulesIt = rules.elementIterator("filerule");
    while (rulesIt.hasNext()) {
        Element ruleElement = (Element) rulesIt.next();
        LuceneIndexFileRule rule = new LuceneIndexFileRule();
        rule.setFilePattern(ruleElement.getText());
        rule.setFileSizeLimit(Integer.parseInt(ruleElement.attributeValue("filesizelimit")));
        if (ruleElement.attributeValue("includedinallcontent").equals("true")) {
            rule.setIncludedInAllContent(true);
        } else {
            rule.setIncludedInAllContent(false);
        }
        rule.setBoost(Float.parseFloat(ruleElement.attributeValue("boost", "1.0")));
        list.add(rule);
    }
    return list;
}

From source file:de.innovationgate.wga.common.beans.LuceneIndexItemRule.java

License:Apache License

/**
 * get rules from configfile element lucene
 * @param lucene configfile element/* www.  jav  a  2 s .c  o  m*/
 * @return list LuceneIndexItemRules
 */
public static List getRules(Element lucene) {
    ArrayList list = new ArrayList();
    Element itemrules = lucene.element("itemrules");
    Iterator itemrulesIt = itemrules.elementIterator("itemrule");
    while (itemrulesIt.hasNext()) {
        Element itemruleElement = (Element) itemrulesIt.next();
        LuceneIndexItemRule rule = new LuceneIndexItemRule();
        rule.setItemExpression(itemruleElement.getText());
        rule.setIndexType(itemruleElement.attributeValue("indextype"));
        rule.setContentType(itemruleElement.attributeValue("contenttype"));
        if (itemruleElement.attributeValue("sortable").equals("true")) {
            rule.setSortable(true);
        } else {
            rule.setSortable(false);
        }
        rule.setBoost(Float.parseFloat(itemruleElement.attributeValue("boost", "1.0")));
        list.add(rule);
    }
    return list;
}

From source file:de.innovationgate.wga.common.WGAXML.java

License:Apache License

/**
 * Performs normalization on the wga.xml by creating mandatory elements and attributes and doing some
 * additional validations, like converting obsolete structures, defining yet undefined domains etc.
 * @param doc The wga.xml//from   ww w.  jav  a  2  s .c  om
 */
public static void normalize(Document doc) {

    // Remove obsolete namespace
    String ns = "urn:de.innovationgate.webgate.api.query.domino.WGDatabaseImpl";
    Iterator nodes = doc.selectNodes("//*[namespace-uri(.)='" + ns + "']").iterator();
    Element element;
    while (nodes.hasNext()) {
        element = (Element) nodes.next();
        element.setQName(QName.get(element.getName()));
    }

    // Build necessary elements
    Element wga = (Element) doc.selectSingleNode("wga");

    // Licenses
    Element licenses = WGUtils.getOrCreateElement(wga, "licenses");
    Iterator licenseTags = licenses.elements("authorlicense").iterator();
    while (licenseTags.hasNext()) {
        Element licenseTag = (Element) licenseTags.next();
        //WGUtils.getOrCreateAttribute(licenseTag, "type", "WGA.Client");
        // B0000486E
        licenseTag.addAttribute("type", "WGA.Client");
    }

    // administrators
    WGUtils.getOrCreateElement(wga, "administrators");

    // configuration
    Element configuration = WGUtils.getOrCreateElement(wga, "configuration");
    Element defaultdb = WGUtils.getOrCreateElement(configuration, "defaultdb");
    WGUtils.getOrCreateAttribute(defaultdb, "key", "");
    WGUtils.getOrCreateAttribute(defaultdb, "favicon", "");
    WGUtils.getOrCreateAttribute(defaultdb, "datacache", "10000");
    WGUtils.getOrCreateAttribute(defaultdb, "staticexpiration", "10");

    Element features = WGUtils.getOrCreateElement(configuration, "features");
    WGUtils.getOrCreateAttribute(features, "bi", "true");
    WGUtils.getOrCreateAttribute(features, "adminpage", "true");
    WGUtils.getOrCreateAttribute(features, "manager", "true");
    WGUtils.getOrCreateAttribute(features, "startpage", "true");
    WGUtils.getOrCreateAttribute(features, "webdav", "true");
    WGUtils.getOrCreateAttribute(features, "webservice", "true");
    WGUtils.getOrCreateAttribute(features, "adminport", "");
    WGUtils.getOrCreateAttribute(features, "authoringport", "");
    WGUtils.getOrCreateAttribute(features, "clusterport", "");

    Element warnings = WGUtils.getOrCreateElement(configuration, "warnings");
    WGUtils.getOrCreateAttribute(warnings, "enabled", "true");
    WGUtils.getOrCreateAttribute(warnings, "consoleOutput", "false");
    WGUtils.getOrCreateAttribute(warnings, "pageOutput", "true");

    Element tml = WGUtils.getOrCreateElement(configuration, "tml");
    WGUtils.getOrCreateAttribute(tml, "characterEncoding", "");
    WGUtils.getOrCreateAttribute(tml, "linkEncoding", "UTF-8");
    Element tmlheader = WGUtils.getOrCreateElement(tml, "tmlheader");
    WGUtils.getOrCreateAttribute(tmlheader, "buffer", "8kb");

    Element authoringconfig = WGUtils.getOrCreateElement(configuration, "authoringconfig");
    WGUtils.getOrCreateAttribute(authoringconfig, "dbfile", "");

    Element applog = WGUtils.getOrCreateElement(configuration, "applog");
    WGUtils.getOrCreateAttribute(applog, "level", "INFO");
    WGUtils.getOrCreateAttribute(applog, "logserver", "false");

    Element compression = WGUtils.getOrCreateElement(configuration, "compression");
    WGUtils.getOrCreateAttribute(compression, "enabled", "false");

    Element listeners = WGUtils.getOrCreateElement(configuration, "listeners");

    Element lucene = WGUtils.getOrCreateElement(configuration, "lucene");
    WGUtils.getOrCreateAttribute(lucene, "dir", "");
    WGUtils.getOrCreateAttribute(lucene, "enabled", "false");
    WGUtils.getOrCreateAttribute(lucene, "booleanQueryMaxClauseCount", "1024");
    WGUtils.getOrCreateAttribute(lucene, "maxDocsPerDBSession", "50");

    // read old lucene enabled dbs
    Attribute dbs = WGUtils.getOrCreateAttribute(lucene, "dbs", "");
    List oldLuceneEnabledDBKeys = WGUtils.deserializeCollection(dbs.getText(), ",");
    // remove old attribute for lucene enabled dbs
    lucene.remove(dbs);

    Element persoconfig = WGUtils.getOrCreateElement(configuration, "personalisation");

    // Element for TestCore - config
    Element testcore = WGUtils.getOrCreateElement(configuration, "testcore");
    WGUtils.getOrCreateAttribute(testcore, "dir", "");
    WGUtils.getOrCreateAttribute(testcore, "enabled", "false");

    Element design = WGUtils.getOrCreateElement(configuration, "designsync");
    WGUtils.getOrCreateAttribute(design, "fileEncoding", "");
    WGUtils.getOrCreateAttribute(design, "interval", "1");
    WGUtils.getOrCreateAttribute(design, "throttling", "false");
    WGUtils.getOrCreateAttribute(design, "throttlingactivation", "10");

    Element jdbcDrivers = WGUtils.getOrCreateElement(configuration, "jdbcdrivers");

    WGUtils.getOrCreateElement(configuration, "defaultdboptions");
    WGUtils.getOrCreateElement(configuration, "defaultpublisheroptions");

    Element mailConfig = WGUtils.getOrCreateElement(configuration, "mailconfig");
    WGUtils.getOrCreateAttribute(mailConfig, "mailHost", "");
    WGUtils.getOrCreateAttribute(mailConfig, "mailUser", "");
    WGUtils.getOrCreateAttribute(mailConfig, "mailPassword", "");
    WGUtils.getOrCreateAttribute(mailConfig, "mailFrom", "");
    WGUtils.getOrCreateAttribute(mailConfig, "mailTo", "");
    WGUtils.getOrCreateAttribute(mailConfig, "mailWGARootURL", "");
    WGUtils.getOrCreateAttribute(mailConfig, "useAsDefaultForWF", "false");
    WGUtils.getOrCreateAttribute(mailConfig, "enableAdminNotifications", "true");

    // Mappings
    Element mappings = WGUtils.getOrCreateElement(wga, "mappings");
    Attribute mappingLibraries = WGUtils.getOrCreateAttribute(mappings, "libraries", "");

    Element elementmappings = WGUtils.getOrCreateElement(mappings, "elementmappings");
    if (elementmappings.attribute("libraries") != null && mappingLibraries.getText().equals("")) {
        mappingLibraries.setText(elementmappings.attributeValue("libraries", ""));
        elementmappings.remove(elementmappings.attribute("libraries"));
    }

    List elementsToRemove = new ArrayList();
    Iterator elementmappingTags = elementmappings.selectNodes("elementmapping").iterator();
    while (elementmappingTags.hasNext()) {
        Element elementmapping = (Element) elementmappingTags.next();
        if (elementmapping.attribute("binary") != null) {
            elementmapping.remove(elementmapping.attribute("binary"));
        }
        // remove old FOP implementation reference (F000040EE)
        String implClass = elementmapping.attributeValue("class", null);
        if (implClass != null && implClass.equals("de.innovationgate.wgpublisher.webtml.elements.FOP")) {
            elementsToRemove.add(elementmapping);
        }
    }
    Iterator toRemove = elementsToRemove.iterator();
    while (toRemove.hasNext()) {
        Element elementmapping = (Element) toRemove.next();
        elementmappings.remove(elementmapping);
    }

    Element mediamappings = WGUtils.getOrCreateElement(mappings, "mediamappings");
    Iterator mediamappingTags = mediamappings.selectNodes("mediamapping").iterator();
    while (mediamappingTags.hasNext()) {
        Element mediamapping = (Element) mediamappingTags.next();
        WGUtils.getOrCreateAttribute(mediamapping, "binary", "false");
        WGUtils.getOrCreateAttribute(mediamapping, "httplogin", "false");
    }

    WGUtils.getOrCreateElement(mappings, "encodermappings");
    WGUtils.getOrCreateElement(mappings, "syncmappings");

    Element analyzermappings = WGUtils.getOrCreateElement(mappings, "analyzermappings");
    WGUtils.getOrCreateAttribute(analyzermappings, "defaultAnalyzerClass",
            "de.innovationgate.wgpublisher.lucene.analysis.StandardAnalyzer");

    removeDefaultFileHandlerMappings(WGUtils.getOrCreateElement(mappings, "filehandlermappings"));

    WGUtils.getOrCreateElement(mappings, "filtermappings");

    Element scheduler = WGUtils.getOrCreateElement(wga, "scheduler");
    WGUtils.getOrCreateAttribute(scheduler, "loggingdir", "");

    // Domains
    Element domains = WGUtils.getOrCreateElement(wga, "domains");
    Iterator domainsIt = domains.elementIterator("domain");
    while (domainsIt.hasNext()) {
        Element domain = (Element) domainsIt.next();
        WGUtils.getOrCreateAttribute(domain, "name", "");
        WGUtils.getOrCreateAttribute(domain, "loginattempts", "5");
        WGUtils.getOrCreateAttribute(domain, "defaultmanager", "");
        Element login = WGUtils.getOrCreateElement(domain, "login");
        WGUtils.getOrCreateAttribute(login, "mode", "user");
        WGUtils.getOrCreateAttribute(login, "username", "");
        WGUtils.getOrCreateAttribute(login, "password", "");
        Element errorpage = WGUtils.getOrCreateElement(domain, "errorpage");
        WGUtils.getOrCreateAttribute(errorpage, "enabled", "false");
        WGUtils.getOrCreateElement(domain, "defaultdboptions");
        WGUtils.getOrCreateElement(domain, "defaultpublisheroptions");
    }

    // content dbs
    Element contentdbs = WGUtils.getOrCreateElement(wga, "contentdbs");
    Iterator contentdbTags = contentdbs.selectNodes("contentdb").iterator();
    Set usedDomains = new HashSet();
    while (contentdbTags.hasNext()) {
        Element contentdb = (Element) contentdbTags.next();
        WGUtils.getOrCreateAttribute(contentdb, "enabled", "true");
        WGUtils.getOrCreateAttribute(contentdb, "lazyconnect", "false");

        Element type = WGUtils.getOrCreateElement(contentdb, "type");
        String typeName = type.getStringValue();
        if (typeName.equals("de.innovationgate.webgate.api.domino.local.WGDatabaseImpl")) {
            type.setText("de.innovationgate.webgate.api.domino.WGDatabaseImpl");
        }

        boolean isFullContentStore = false;
        DbType dbType = DbType.getByImplClass(DbType.GENTYPE_CONTENT, typeName);
        if (dbType != null) {
            isFullContentStore = dbType.isFullContentStore();
        }

        //lowercase dbkey
        Element dbkey = WGUtils.getOrCreateElement(contentdb, "dbkey");
        dbkey.setText(dbkey.getText().trim().toLowerCase());

        WGUtils.getOrCreateElement(contentdb, "title");
        Element domain = WGUtils.getOrCreateElement(contentdb, "domain");
        String domainStr = domain.getTextTrim();
        if (domainStr.equals("")) {
            domainStr = "masterloginonly";
            domain.setText("masterloginonly");
        }
        usedDomains.add(domainStr);
        WGUtils.getOrCreateElement(contentdb, "login");

        Element dboptions = WGUtils.getOrCreateElement(contentdb, "dboptions");
        Iterator options = dboptions.selectNodes("option").iterator();
        Element option;
        String optionName;
        while (options.hasNext()) {
            option = (Element) options.next();
            optionName = option.attributeValue("name");
            if (optionName.indexOf(":") != -1) {
                option.addAttribute("name", optionName.substring(optionName.indexOf(":") + 1));
            }
        }

        WGUtils.getOrCreateElement(contentdb, "publisheroptions");
        WGUtils.getOrCreateElement(contentdb, "storedqueries");
        WGUtils.getOrCreateElement(contentdb, "fieldmappings");

        if (isFullContentStore) {
            WGUtils.getOrCreateElement(contentdb, "shares");
        } else {
            if (contentdb.element("shares") != null) {
                contentdb.remove(contentdb.element("shares"));
            }
        }

        Element cache = WGUtils.getOrCreateElement(contentdb, "cache");
        WGUtils.getOrCreateAttribute(cache, "type", "de.innovationgate.wgpublisher.cache.WGACacheHSQLDB");
        WGUtils.getOrCreateAttribute(cache, "path", "");
        WGUtils.getOrCreateAttribute(cache, "maxpages", "5000");

        // Design - Migrate old designsync element
        Element designsync = contentdb.element("designsync");
        design = contentdb.element("design");
        if (designsync != null && design == null) {
            design = contentdb.addElement("design");
            if (designsync.attributeValue("enabled", "false").equals("true")) {
                design.addAttribute("provider", "sync");
            } else {
                design.addAttribute("provider", "none");
            }
            design.addAttribute("mode", designsync.attributeValue("mode", ""));
            design.addAttribute("key", designsync.attributeValue("key", ""));
            design.setText(designsync.getText());
        } else {
            design = WGUtils.getOrCreateElement(contentdb, "design");
            WGUtils.getOrCreateAttribute(design, "provider", "none");
            WGUtils.getOrCreateAttribute(design, "mode", "");
            WGUtils.getOrCreateAttribute(design, "key", "");
        }

        // create default lucene config for old enabled dbs
        if (oldLuceneEnabledDBKeys.contains(dbkey.getText().toLowerCase())) {
            Element luceneDBConfig = WGUtils.getOrCreateElement(contentdb, "lucene");
            WGUtils.getOrCreateAttribute(luceneDBConfig, "enabled", "true");
            WGUtils.getOrCreateElement(luceneDBConfig, "itemrules");
            // create defaultrule
            LuceneIndexItemRule.addDefaultRule(luceneDBConfig);
        }

        //lucene config per db
        Element luceneDBConfig = WGUtils.getOrCreateElement(contentdb, "lucene");
        WGUtils.getOrCreateAttribute(luceneDBConfig, "enabled", "false");
        WGUtils.getOrCreateElement(luceneDBConfig, "itemrules");
        //check for default rule
        ArrayList rules = (ArrayList) LuceneIndexItemRule.getRules(luceneDBConfig);
        if (rules.size() > 0) {
            //check if last rule is defaultrule
            LuceneIndexItemRule checkDefaultRule = (LuceneIndexItemRule) rules.get(rules.size() - 1);
            if (!checkDefaultRule.getItemExpression().equals(LuceneIndexItemRule.EXPRESSION_WILDCARD)) {
                //last rule is no defaultRule, create defaultRule
                LuceneIndexItemRule.addDefaultRule(luceneDBConfig);
            }
        } else {
            //no rules present, create defaultRule
            LuceneIndexItemRule.addDefaultRule(luceneDBConfig);
        }
        // lucene file rules
        WGUtils.getOrCreateElement(luceneDBConfig, "filerules");
        //check for default filerule
        rules = (ArrayList) LuceneIndexFileRule.getRules(luceneDBConfig);
        if (rules.size() > 0) {
            //check if last rule is defaultrule
            LuceneIndexFileRule checkDefaultRule = (LuceneIndexFileRule) rules.get(rules.size() - 1);
            if (!checkDefaultRule.isDefaultRule()) {
                //last rule is no defaultRule, create defaultRule
                LuceneIndexFileRule.addDefaultRule(luceneDBConfig);
            }
        } else {
            //no rules present, create defaultRule
            LuceneIndexFileRule.addDefaultRule(luceneDBConfig);
        }

        // client restrictions
        Element clientRestrictions = WGUtils.getOrCreateElement(contentdb, "clientrestrictions");
        WGUtils.getOrCreateAttribute(clientRestrictions, "enabled", "false");
        WGUtils.getOrCreateElement(clientRestrictions, "restrictions");
    }

    // Personalisation dbs
    Element persodbs = WGUtils.getOrCreateElement(wga, "personalisationdbs");
    Iterator persodbTags = persodbs.selectNodes("personalisationdb").iterator();
    while (persodbTags.hasNext()) {
        Element persodb = (Element) persodbTags.next();
        WGUtils.getOrCreateAttribute(persodb, "enabled", "true");
        WGUtils.getOrCreateAttribute(persodb, "lazyconnect", "false");

        Element type = WGUtils.getOrCreateElement(persodb, "type");
        if (type.getStringValue().equals("de.innovationgate.webgate.api.domino.local.WGDatabaseImpl")) {
            type.setText("de.innovationgate.webgate.api.domino.WGDatabaseImpl");
        }

        Element domain = WGUtils.getOrCreateElement(persodb, "domain");
        String domainStr = domain.getTextTrim();
        if (domainStr.equals("")) {
            domainStr = "masterloginonly";
            domain.setText("masterloginonly");
        }
        usedDomains.add(domainStr);
        WGUtils.getOrCreateElement(persodb, "login");

        Element persConfig = WGUtils.getOrCreateElement(persodb, "persconfig");
        WGUtils.getOrCreateAttribute(persConfig, "mode", "auto");
        WGUtils.getOrCreateAttribute(persConfig, "statistics", "off");

        Element dboptions = WGUtils.getOrCreateElement(persodb, "dboptions");
        Iterator options = dboptions.selectNodes("option").iterator();
        Element option;
        String optionName;
        while (options.hasNext()) {
            option = (Element) options.next();
            optionName = option.attributeValue("name");
            if (optionName.indexOf(":") != -1) {
                option.addAttribute("name", optionName.substring(optionName.indexOf(":") + 1));
            }
        }

        WGUtils.getOrCreateElement(persodb, "publisheroptions");
    }

    //  **** Post-Processings **** 

    // Turn stored queries into CDATA-Sections
    List queries = doc.selectNodes("/wga/contentdbs/contentdb/storedqueries/storedquery/query");
    for (Iterator iter = queries.iterator(); iter.hasNext();) {
        Element query = (Element) iter.next();
        Node text = query.selectSingleNode("text()");
        if (text != null && text instanceof Text) {
            query.addCDATA(text.getText());
            query.remove(text);
        }
    }

    // Create domains from database definitions
    Iterator usedDomainsIt = usedDomains.iterator();
    String usedDomain;
    while (usedDomainsIt.hasNext()) {
        usedDomain = (String) usedDomainsIt.next();
        Element domain = (Element) domains.selectSingleNode("domain[@name='" + usedDomain + "']");
        if (domain == null) {
            domain = domains.addElement("domain");
            domain.addAttribute("name", usedDomain);
            Element login = domain.addElement("login");
            if (usedDomain.equals("masterloginonly")) {
                login.addAttribute("mode", "master");
            } else {
                login.addAttribute("mode", "user");
            }
            login.addAttribute("username", "");
            login.addAttribute("password", "");
            Element errorPage = domain.addElement("errorpage");
            errorPage.addAttribute("enabled", "false");
            Element defDBOptions = domain.addElement("defaultdboptions");
            Element defPublisherOptions = domain.addElement("defaultpublisheroptions");
        }
    }

    // Reorder content dbs, so design providers are first
    pullupDesignProviders(doc);
}

From source file:de.innovationgate.wga.config.WGAConfigurationMigrator.java

License:Apache License

public static MigrationResult createFromWGAXML(InputStream wgaXML, String configPath)
        throws DocumentException, IOException, NoSuchAlgorithmException {
    MigrationResult migrationResult = new MigrationResult();
    migrationResult.logInfo("Starting migration of 'wga.xml'.");

    SAXReader reader = new SAXReader();
    Document doc = reader.read(wgaXML);
    WGAXML.normalize(doc);//  w w w  .j  av  a 2 s . c o m

    WGAConfiguration config = new WGAConfiguration();
    config.createDefaultResources();

    // Add a file system design source that will register all design directories that are not at default location
    DesignSource fsDesignSource = new DesignSource(
            "de.innovationgate.wgpublisher.design.fs.FileSystemDesignSource");
    fsDesignSource.setDescription("Migrated design directories that are not in the default folder");
    fsDesignSource.setTitle("Migrated design directories");
    String dir = System.getProperty(WGAConfiguration.SYSPROP_DESIGN_ROOT);
    if (dir == null) {
        dir = WGAConfiguration.DEFAULT_DESIGNROOT;
    }
    fsDesignSource.getOptions().put("Path", dir);
    config.getDesignConfiguration().getDesignSources().add(fsDesignSource);

    Element root = doc.getRootElement();

    Iterator administrators = root.element("administrators").elementIterator("administrator");
    while (administrators.hasNext()) {
        Element adminElement = (Element) administrators.next();
        String name = adminElement.attributeValue("name");
        String password = adminElement.attributeValue("password");
        if (!adminElement.attributeValue("encode", "").equals("hash")) {
            password = WGUtils.hashPassword(password);
        }

        Administrator admin = new Administrator(name, password, SHA1HashingScheme.NAME);
        migrationResult.logInfo("Migrating admin login '" + name + "'.");
        config.add(admin);
    }

    migrationResult.logInfo("Migrating general configuration.");
    Element configuration = root.element("configuration");

    Element defaultDB = configuration.element("defaultdb");
    config.setDefaultDatabase(defaultDB.attributeValue("key"));
    config.setFavicon(defaultDB.attributeValue("favicon"));
    config.setCacheExpirationForStaticResources(Integer.parseInt(defaultDB.attributeValue("staticexpiration")));
    config.setUsePermanentRedirect(
            Boolean.parseBoolean(defaultDB.attributeValue("permanentredirect", "false")));

    Element warnings = configuration.element("warnings");
    config.setWarningsEnabled(Boolean.parseBoolean(warnings.attributeValue("enabled")));
    config.setWarningsOutputOnConsole(Boolean.parseBoolean(warnings.attributeValue("consoleOuput")));
    config.setWarningsOutputViaTML(
            Boolean.parseBoolean(warnings.attributeValue("pageOutput")) == true ? Constants.WARNINGS_TML_AS_HTML
                    : Constants.WARNINGS_TML_OFF);

    Element tml = configuration.element("tml");
    String enc = tml.attributeValue("characterEncoding", null);
    if (enc != null && !enc.trim().equals("")) {
        config.setCharacterEncoding(enc);
    }
    Element tmlHeader = tml.element("tmlheader");
    if (tmlHeader != null) {
        String tmlBufferStr = tmlHeader.attributeValue("buffer").toLowerCase();
        if (tmlBufferStr.indexOf("kb") != -1) {
            tmlBufferStr = tmlBufferStr.substring(0, tmlBufferStr.indexOf("kb"));
        }
        try {
            int tmlBuffer = Integer.parseInt(tmlBufferStr);
            config.setTmlBuffer(tmlBuffer);
        } catch (NumberFormatException e) {
            migrationResult.logError(
                    "Unable to parse WebTML output buffer size: " + tmlBufferStr + ". Falling back to default: "
                            + WGAConfiguration.SERVEROPTIONDEFAULT_WEBTML_OUTPUT_BUFFER);
        }
        config.setTmlHeader(tmlHeader.getText());
    }

    Element features = configuration.element("features");
    /* Deprecated in WGA5
    config.setAuthoringApplicationsEnabled(Boolean.parseBoolean(features.attributeValue("bi")));
            
    config.setStartPageEnabled(Boolean.parseBoolean(features.attributeValue("startpage")));
    */
    config.setAdminPageEnabled(Boolean.parseBoolean(features.attributeValue("adminpage")));
    config.setWebservicesEnabled(Boolean.parseBoolean(features.attributeValue("webservice")));
    config.clearAdminToolsPortRestrictions();
    String port = features.attributeValue("adminport");
    if (port != null && !port.trim().equals("")) {
        config.addAdminToolsPortRestriction(Integer.parseInt(port));
    }
    config.clearAuthoringDesignAccessPortRestrictions();
    port = features.attributeValue("authoringport");
    if (port != null && !port.trim().equals("")) {
        config.addAuthoringDesignAccessPortRestriction(Integer.parseInt(port));
    }

    Element applog = configuration.element("applog");
    config.setApplicationLogLevel(applog.attributeValue("level"));
    config.setApplicationLogDirectory(applog.attributeValue("dir", null));

    Iterator listeners = configuration.element("listeners").elementIterator("listener");
    while (listeners.hasNext()) {
        Element listener = (Element) listeners.next();
        config.getCoreEventListeners().add(listener.attributeValue("class"));
    }

    // personalisation agent exclusions
    Element personalisation = configuration.element("personalisation");
    Iterator agentExclusions = personalisation.elementIterator("agentexclusion");
    while (agentExclusions.hasNext()) {
        Element agentExclusion = (Element) agentExclusions.next();
        config.getPersonalisationConfiguration().getPersonalisationAgentExclusions()
                .add(agentExclusion.attributeValue("name"));
    }

    migrationResult.logInfo("Migrating global lucene configuration.");
    Element lucene = configuration.element("lucene");
    config.getLuceneManagerConfiguration().setEnabled(Boolean.parseBoolean(lucene.attributeValue("enabled")));
    config.getLuceneManagerConfiguration()
            .setPath(System.getProperty(WGAConfiguration.SYSPROP_LUCENE_ROOT, lucene.attributeValue("dir")));
    config.getLuceneManagerConfiguration()
            .setMaxBooleanClauseCount(Integer.parseInt(lucene.attributeValue("booleanQueryMaxClauseCount")));
    config.getLuceneManagerConfiguration()
            .setMaxDocsPerDBSession(Integer.parseInt(lucene.attributeValue("maxDocsPerDBSession")));
    if (WGUtils.isEmpty(config.getLuceneManagerConfiguration().getPath())) {
        File lucenePath = new File(configPath, "lucene");
        if (!lucenePath.exists()) {
            lucenePath.mkdir();
        }
        config.getLuceneManagerConfiguration().setPath(lucenePath.getAbsolutePath());
    }

    migrationResult.logInfo("Migrating global designsync configuration.");
    Element designSync = configuration.element("designsync");
    config.getDesignConfiguration().setDefaultEncoding(designSync.attributeValue("fileEncoding"));
    config.getDesignConfiguration().setPollingInterval(Integer.parseInt(designSync.attributeValue("interval")));
    config.getDesignConfiguration()
            .setThrottlingEnabled(Boolean.parseBoolean(designSync.attributeValue("throttling")));
    config.getDesignConfiguration()
            .setThrottlingPeriodMinutes(Integer.parseInt(designSync.attributeValue("throttlingactivation")));
    Iterator fileExclusions = designSync.elementIterator("fileexclusion");
    while (fileExclusions.hasNext()) {
        Element fileExclusion = (Element) fileExclusions.next();
        config.getDesignConfiguration().getFileExclusions().add(fileExclusion.attributeValue("name"));
    }

    migrationResult.logInfo("Migrating global database options.");
    Iterator defaultDBOptions = configuration.element("defaultdboptions").elementIterator("option");
    while (defaultDBOptions.hasNext()) {
        Element option = (Element) defaultDBOptions.next();
        config.getGlobalDatabaseOptions().put(option.attributeValue("name"), option.attributeValue("value"));
    }
    migrationResult.logInfo("Migrating global publishing options.");
    Iterator defaultPublisherOptions = configuration.element("defaultpublisheroptions")
            .elementIterator("option");
    while (defaultPublisherOptions.hasNext()) {
        Element option = (Element) defaultPublisherOptions.next();
        config.getGlobalPublisherOptions().put(option.attributeValue("name"), option.attributeValue("value"));
    }

    migrationResult.logInfo("Migrating global mail configuration.");
    Element mailconfig = configuration.element("mailconfig");
    config.getMailConfiguration().setServer(mailconfig.attributeValue("mailHost"));
    config.getMailConfiguration().setUser(mailconfig.attributeValue("mailUser"));
    config.getMailConfiguration().setPassword(mailconfig.attributeValue("mailPassword"));
    config.getMailConfiguration().setFromAddress(mailconfig.attributeValue("mailFrom"));
    config.getMailConfiguration().setToAddress(mailconfig.attributeValue("mailTo"));
    config.getMailConfiguration().setEnableAdminNotifications(
            Boolean.parseBoolean(mailconfig.attributeValue("enableAdminNotifications")));
    config.setRootURL(mailconfig.attributeValue("mailWGARootURL"));

    Element domains = root.element("domains");
    migrateDomains(migrationResult, config, domains);

    // create dbservers & content dbs
    migrationResult.logInfo("Starting migration of content dbs ...");
    int mysqlServerCount = 0;
    int hsqlServerCount = 0;
    int notesServerCount = 0;
    int oracleServerCount = 0;
    int jdbcServerCount = 0;
    int dummyServerCount = 0;
    Map<String, DatabaseServer> dbServersByUniqueID = new HashMap<String, DatabaseServer>();

    Iterator dbPaths = root.selectNodes("//contentdb/dbpath").iterator();
    while (dbPaths.hasNext()) {
        Element dbPathElement = (Element) dbPaths.next();
        String dbType = dbPathElement.getParent().elementTextTrim("type");
        String path = dbPathElement.getTextTrim();
        String user = determineUser(dbPathElement.getParent());
        String password = determinePassword(dbPathElement.getParent());

        // migration for mysql dbs
        if (path.startsWith("jdbc:mysql")) {
            mysqlServerCount = createMySqlServerAndDB(configPath, migrationResult, config, mysqlServerCount,
                    dbServersByUniqueID, dbPathElement, path, user, password, false, fsDesignSource);
        }

        else if (dbType.contains("domino.remote")) {
            notesServerCount = createDominoServerAndDB(configPath, migrationResult, config, notesServerCount,
                    dbServersByUniqueID, dbPathElement, path, user, password, false, fsDesignSource);
        }

        else if (dbType.contains("de.innovationgate.webgate.api.hsql") || path.startsWith("jdbc:hsqldb:")) {
            hsqlServerCount = createHSQLServerAndDB(configPath, migrationResult, config, hsqlServerCount,
                    dbServersByUniqueID, dbPathElement, path, user, password, false, fsDesignSource);
        } else if (path.startsWith("jdbc:oracle:")) {
            oracleServerCount = createOracleServerAndDB(configPath, migrationResult, config, oracleServerCount,
                    dbServersByUniqueID, dbPathElement, path, user, password, false, fsDesignSource);
        } else if (dbType.contains(".jdbc.")) {
            jdbcServerCount = createJDBCServerAndDB(configPath, migrationResult, config, jdbcServerCount,
                    dbServersByUniqueID, dbPathElement, path, user, password, false, fsDesignSource);
        }

        else {
            // migrate other dbs with same user/password combination to
            // "other sources" server
            DatabaseServer server = new DatabaseServer(
                    "de.innovationgate.webgate.api.servers.OtherSourcesDatabaseServer");
            server.setUid(WGAConfiguration.SINGLETON_SERVER_PREFIX
                    + "de.innovationgate.webgate.api.servers.OtherSourcesDatabaseServer");
            addContentDB(config, dbPathElement.getParent(), server, migrationResult, configPath, fsDesignSource,
                    path);
        }
    }

    // migrate personalisation dbs
    migrationResult.logInfo("Starting migration of personalisation dbs ...");
    Iterator persDBPaths = root.selectNodes("//personalisationdb/dbpath").iterator();
    while (persDBPaths.hasNext()) {
        Element dbPathElement = (Element) persDBPaths.next();
        String dbType = dbPathElement.getParent().elementTextTrim("type");
        String domain = dbPathElement.getParent().elementTextTrim("domain");
        String path = dbPathElement.getTextTrim();
        String user = determineUser(dbPathElement.getParent());
        String password = determinePassword(dbPathElement.getParent());
        // migration for mysql dbs
        if (path.startsWith("jdbc:mysql")) {
            mysqlServerCount = createMySqlServerAndDB(configPath, migrationResult, config, mysqlServerCount,
                    dbServersByUniqueID, dbPathElement, path, user, password, true, fsDesignSource);
        } else if (dbType.contains("domino.remote")) {
            mysqlServerCount = createDominoServerAndDB(configPath, migrationResult, config, notesServerCount,
                    dbServersByUniqueID, dbPathElement, path, user, password, true, fsDesignSource);
        } else if (dbType.contains("de.innovationgate.webgate.api.hsql")) {
            hsqlServerCount = createHSQLServerAndDB(configPath, migrationResult, config, hsqlServerCount,
                    dbServersByUniqueID, dbPathElement, path, user, password, true, fsDesignSource);
        } else if (path.startsWith("jdbc:oracle:")) {
            oracleServerCount = createOracleServerAndDB(configPath, migrationResult, config, oracleServerCount,
                    dbServersByUniqueID, dbPathElement, path, user, password, false, fsDesignSource);
        } else {
            // migrate other dbs to "other sources" server
            // migrate other dbs with same user/password combination to
            // "other sources" server
            DatabaseServer server = new DatabaseServer(
                    "de.innovationgate.webgate.api.servers.OtherSourcesDatabaseServer");
            server.setUid(WGAConfiguration.SINGLETON_SERVER_PREFIX
                    + "de.innovationgate.webgate.api.servers.OtherSourcesDatabaseServer");
            addPersonalisationDB(config, dbPathElement.getParent(), server, migrationResult, null);
        }
    }

    // migrate first found access log
    migrationResult.logWarning("Accessloggers will not be migrated.");

    // migrate libraries
    migrationResult.logInfo("Migrating library mappings");
    String libraries = root.element("mappings").attributeValue("libraries", null);
    if (libraries != null && !libraries.trim().equals("")) {
        config.getServerOptions().put(WGAConfiguration.SERVEROPTION_LIBRARIES, libraries);
    }

    // migrate mappings
    migrationResult.logInfo("Migrating filter mappings.");
    Iterator filterMappings = root.element("mappings").element("filtermappings")
            .elementIterator("filtermapping");
    while (filterMappings.hasNext()) {
        Element filterMappingElement = (Element) filterMappings.next();
        FilterMapping mapping = new FilterMapping(filterMappingElement.attributeValue("filtername"),
                filterMappingElement.attributeValue("class"));
        Iterator patterns = filterMappingElement.elementIterator("filterurlpattern");
        while (patterns.hasNext()) {
            Element pattern = (Element) patterns.next();
            mapping.getUrlPatterns().add(pattern.attributeValue("urlpattern"));
        }
        Iterator params = filterMappingElement.elementIterator("filterinitparam");
        while (params.hasNext()) {
            Element param = (Element) params.next();
            mapping.getInitParameters().put(param.attributeValue("name"), param.attributeValue("value"));
        }
    }

    // migrate jobs
    migrationResult.logInfo("Migrating configured jobs & schedules.");
    Element scheduler = (Element) root.element("scheduler");
    if (scheduler != null) {
        config.getSchedulerConfiguration().setLoggingDir(scheduler.attributeValue("loggingdir", null));
        Iterator jobs = scheduler.elementIterator("job");
        while (jobs.hasNext()) {
            Element jobElement = (Element) jobs.next();
            Job job = new Job(jobElement.attributeValue("name"));
            String desc = jobElement.attributeValue("description", null);
            if (desc != null && !desc.trim().equalsIgnoreCase("(Enter description here)")) {
                job.setDescription(desc);
            }
            Iterator options = jobElement.element("joboptions").elementIterator("option");
            Element option;
            while (options.hasNext()) {
                option = (Element) options.next();
                String value = option.attributeValue("value");
                if (value != null && !value.trim().equalsIgnoreCase("(database containing the script module)")
                        && !value.trim().equalsIgnoreCase("(Script module to execute)")) {
                    job.getOptions().put(option.attributeValue("name"), option.attributeValue("value"));
                }
            }
            Iterator tasks = jobElement.element("tasks").elementIterator("task");
            while (tasks.hasNext()) {
                Element taskElem = (Element) tasks.next();
                Task task = new Task(taskElem.attributeValue("class"));
                Iterator taskOptions = taskElem.attributeIterator();
                while (taskOptions.hasNext()) {
                    Attribute attribute = (Attribute) taskOptions.next();
                    if (!attribute.getName().equals("name") && !attribute.getName().equals("class")) {
                        String value = attribute.getValue();
                        if (value != null
                                && !value.trim().equalsIgnoreCase("(database containing the script module)")
                                && !value.trim().equalsIgnoreCase("(Script module to execute)")) {
                            task.getOptions().put(attribute.getName(), attribute.getValue());
                        }
                    }
                }
                job.getTasks().add(task);
            }
            Iterator schedules = jobElement.element("schedules").elementIterator("schedule");
            SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy hh:mm");
            while (schedules.hasNext()) {
                Element scheduleElement = (Element) schedules.next();
                Schedule schedule = new Schedule(scheduleElement.attributeValue("type"),
                        scheduleElement.getText());
                schedule.setEnabled(Boolean.parseBoolean(scheduleElement.attributeValue("enabled", "true")));
                String sStarting = scheduleElement.attributeValue("starting", null);
                if (sStarting != null && !sStarting.trim().equals("")) {
                    try {
                        schedule.setStartDate(df.parse(sStarting));
                    } catch (ParseException e) {
                        migrationResult.logError("Unable to parse start date of job '" + job.getName() + "'.",
                                e);
                    }
                }
                String sEnding = scheduleElement.attributeValue("ending", null);
                if (sEnding != null && !sEnding.trim().equals("")) {
                    try {
                        schedule.setEndDate(df.parse(sEnding));
                    } catch (ParseException e) {
                        migrationResult.logError("Unable to parse end date of job '" + job.getName() + "'.", e);
                    }
                }
                job.getSchedules().add(schedule);
            }

            config.getSchedulerConfiguration().getJobs().add(job);
        }
    }

    List<ValidationError> errors = config.validate();
    if (!errors.isEmpty()) {
        migrationResult.logError("Migration failed:");
        Iterator<ValidationError> it = errors.iterator();
        while (it.hasNext()) {
            migrationResult.logError(it.next().getMessage());
        }
    } else {

        // write the config once to apply simple-xml-api validation
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            WGAConfiguration.write(config, out);
            out.close();
            migrationResult.setConfig(
                    (WGAConfiguration) WGAConfiguration.read(new ByteArrayInputStream(out.toByteArray())));

        } catch (Exception e) {
            migrationResult.logError("Unable to serialize or deserialize configuration", e);
            if (e instanceof ConfigValidationException) {
                errors = ((ConfigValidationException) e).getValidationErrors();
                if (errors != null) {
                    Iterator<ValidationError> it = errors.iterator();
                    while (it.hasNext()) {
                        migrationResult.logError(it.next().getMessage());
                    }
                }
            }
        }
        migrationResult.logInfo("Migrating of 'wga.xml' finished.");
    }

    return migrationResult;
}