Example usage for org.dom4j Element getStringValue

List of usage examples for org.dom4j Element getStringValue

Introduction

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

Prototype

String getStringValue();

Source Link

Document

Returns the XPath string-value of this node.

Usage

From source file:com.thoughtworks.cruise.utils.configfile.CruiseConfigDom.java

License:Apache License

public Map<String, String> replacePackageRepositoryURIForFileSystemBasedRepos() {
    Map<String, String> packageURI = new HashMap<String, String>();
    List<Element> list = root().selectNodes("/cruise/repositories/repository/configuration/property/value");

    for (Element element : list) {
        String initial = element.getStringValue();

        String replaced = initial.matches("^\\$repo*[0-9]+$")
                ? PackageRepository.getPackageRepositoryURI(initial)
                : initial;//from  ww  w. j a  va 2 s . c o m

        if (initial != replaced) {
            for (Element propertyElem : (List<Element>) root()
                    .selectNodes("//property/value[text()='" + initial + "']")) {
                propertyElem.setText("file://" + replaced);
            }
            packageURI.put(initial.replace("$", ""), replaced);
        }

    }
    return packageURI;
}

From source file:com.xpn.xwiki.plugin.packaging.Package.java

License:Open Source License

private boolean documentExistInPackageFile(String docName, String language, Document xml) {
    Element docFiles = xml.getRootElement();
    Element infosFiles = docFiles.element("files");

    @SuppressWarnings("unchecked")
    List<Element> fileList = infosFiles.elements("file");

    for (Element el : fileList) {
        String tmpDocName = el.getStringValue();
        if (tmpDocName.compareTo(docName) != 0) {
            continue;
        }/*from  w  w  w.j a  va  2s  .  co m*/
        String tmpLanguage = el.attributeValue("language");
        if (tmpLanguage == null) {
            tmpLanguage = "";
        }
        if (tmpLanguage.compareTo(language) == 0) {
            return true;
        }
    }

    return false;
}

From source file:com.xpn.xwiki.plugin.packaging.Package.java

License:Open Source License

private void updateFileInfos(Document xml) {
    Element docFiles = xml.getRootElement();
    Element infosFiles = docFiles.element("files");

    @SuppressWarnings("unchecked")
    List<Element> fileList = infosFiles.elements("file");
    for (Element el : fileList) {
        String defaultAction = el.attributeValue("defaultAction");
        String language = el.attributeValue("language");
        if (language == null) {
            language = "";
        }/*  ww w.  j a  va  2 s. c om*/
        String docName = el.getStringValue();
        setDocumentDefaultAction(docName, language, Integer.parseInt(defaultAction));
    }
}

From source file:com.zimbra.cs.dav.client.CalDavClient.java

License:Open Source License

private String getCurrentUserPrincipal() {
    DavRequest propfind = DavRequest.PROPFIND("/.well-known/caldav");
    propfind.addRequestProp(DavElements.E_CURRENT_USER_PRINCIPAL);
    HttpMethod m = null;/*from   w w w. j av a  2  s. c  o m*/
    try {
        m = executeFollowRedirect(propfind);
        int status = m.getStatusCode();
        if (status >= 400) {
            return null;
        }
        Document doc = W3cDomUtil.parseXMLToDom4jDocUsingSecureProcessing(m.getResponseBodyAsStream());
        Element top = doc.getRootElement();
        for (Object obj : top.elements(DavElements.E_RESPONSE)) {
            if (obj instanceof Element) {
                DavObject davObject = new DavObject((Element) obj);
                Element e = davObject.getProperty(DavElements.E_CURRENT_USER_PRINCIPAL);
                if (e != null) {
                    return e.getStringValue().trim();
                }
            }
        }
    } catch (Exception e) {
        ZimbraLog.dav.debug("Exception thrown getting Current User Principal", e);
        return null;
    } finally {
        if (m != null) {
            m.releaseConnection();
        }
    }
    return null;
}

From source file:Data.Storage.java

License:Apache License

/**
 * helper for adding xml/*from  w  w w .jav  a 2 s  .c  om*/
 * @param path where the xml will be added
 * @param xmlData the data as an xml Element
 */
private void addXmlWithPath(ArrayList<String> path, Element xmlData) {
    boolean isXml = xmlData.elements().size() > 0;

    //set the key
    String[] thePath = new String[path.size()];
    path.toArray(thePath);

    //put either the value or an imbeded object
    if (isXml && !has(thePath)) {
        put(thePath, new Storage());
    } else {
        put(thePath, xmlData.getStringValue());
    }
    for (int i = 0; i < xmlData.attributeCount(); ++i) {
        //get attribute data
        Attribute attr = xmlData.attribute(i);

        //save attribute
        putAttribute(thePath, attr.getName(), attr.getValue());
    }

    //if it is xml need to see all children
    if (isXml) {
        recurseOverElements(path, xmlData);
    }
}

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   w  w  w .java 2 s  .  c  o  m
 */
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.wgpublisher.webtml.utils.TagOutputFormatter.java

License:Open Source License

public String format(Object obj) throws FormattingException {

    try {/*from w w w. ja v a2  s.  c o m*/
        if (obj == null) {
            return "";
        } else if (obj instanceof java.util.Date) {
            return this.getDateFormatter().format((java.util.Date) obj);
        } else if (obj instanceof Number) {
            return this.getNumberFormatter().format((Number) obj);
        } else if (obj instanceof Element) {
            Element element = (Element) obj;
            if (element.hasMixedContent()) {
                Iterator nodes = element.content().iterator();
                Node node;
                StringBuffer output = new StringBuffer();
                while (nodes.hasNext()) {
                    node = (Node) nodes.next();
                    output.append(node.asXML());
                }
                return (trim ? output.toString().trim() : output.toString());
            } else {
                return (trim ? element.getStringValue().trim() : element.getStringValue());
            }

        } else if (obj instanceof Node) {
            return ((Node) obj).getStringValue();
        } else {
            return (trim ? obj.toString().trim() : obj.toString());
        }
    } catch (WGException e) {
        throw new FormattingException("Exception formatting tag", e);
    }

}

From source file:edu.common.dynamicextensions.entitymanager.DataTypeFactory.java

License:BSD License

/**
 * This method updates module map by parsing xml file
 * @param xmlFileName file to be parsed//from   ww  w. j  a va 2 s  . co  m
 * @return dataType Map
 * @throws DataTypeFactoryInitializationException on Exception
 */
public final Map populateDataTypeMap(String xmlFileName) throws DataTypeFactoryInitializationException {
    dataTypeMap = new HashMap<String, String>();

    SAXReader saxReader = new SAXReader();
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(xmlFileName);

    Document document = null;

    try {
        document = saxReader.read(inputStream);
        Element name = null;
        Element databaseDataType = null;

        Element primitiveAttributesElement = document.getRootElement();
        Iterator primitiveAttributeElementIterator = primitiveAttributesElement
                .elementIterator("Primitive-Attribute");

        Element primitiveAttributeElement = null;

        while (primitiveAttributeElementIterator.hasNext()) {
            primitiveAttributeElement = (Element) primitiveAttributeElementIterator.next();

            name = primitiveAttributeElement.element("name");
            databaseDataType = primitiveAttributeElement.element("database-datatype");

            dataTypeMap.put(name.getStringValue(), databaseDataType.getStringValue());
        }
    } catch (DocumentException documentException) {
        throw new DataTypeFactoryInitializationException(documentException);
    }

    return dataTypeMap;
}

From source file:edu.ku.brc.dbsupport.ImportExportDB.java

License:Open Source License

/**
     * Imports a table from a given xml file
     * @param dbImport the opend xml file elememt
     * @param dbTable the class name of the table
     *//*from ww w.  j a  v a 2  s  . c  om*/
    @SuppressWarnings("unchecked")
    protected void dynamicXMLImport(Element dbImport, String dbTable) {
        try {
            String id = new String();
            DBTableInfo parentInfo = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase());

            List records = dbImport.selectNodes("//" + dbTable); //$NON-NLS-1$
            String lowerdbTable = lowerFirstChar(dbTable);
            // List attributes = dbImport.selectNodes("//@"+lowerdbTable+"Id");
            List ids = dbImport.selectNodes("//" + lowerdbTable + "Id");// assume this is dbs id //$NON-NLS-1$ //$NON-NLS-2$
                                                                        // name
            if (records.size() < 1) {
                log.debug("Cannot import. Given database type:" + dbTable //$NON-NLS-1$
                        + " does not exsist in import file"); //$NON-NLS-1$
            } else {
                // loop for each record
                for (int k = 0; k < records.size(); k++) {
                    // keep this id to compare against it's collection
                    Element idElement = (Element) ids.get(k);
                    // id = attribute.getText();
                    id = idElement.getStringValue();
                    // make the agent and the element
                    Object agent = parentInfo.getClassObj().newInstance();
                    Map<String, Object> agentMap = new HashMap<String, Object>();
                    Element dbElement = (Element) records.get(k);
                    Iterator i = dbElement.elementIterator();
                    do {// do for each element in the record
                        Element element = (Element) i.next();

                        Object value = findType(element, dbTable, agent, " ");// the parent is //$NON-NLS-1$
                                                                              // itself, just a
                                                                              // dummy variable
                                                                              // if(value!=null && value != "collection")
                        if (value != null && value != "OneToMany" && value != "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                        {
                            agentMap.put(element.getName(), value);
                        }
                        // ignore many-to-many for now
                        else if (value == "OneToMany" || value == "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                        {// RECURSE
                         // is it a collection, add all associated records
                         // get assoicated ids
                         // List collectingevent_ids =
                         // element.selectNodes("//"+dbTable+"[@"+lowerdbTable+"Id='"+id+"']/"+element.getName()+"/"+lowerElement);
                         // TODO shouldl not assume things are in order
                            List collectingevent_ids = element.selectNodes("//" + dbTable + "[" //$NON-NLS-1$ //$NON-NLS-2$
                                    + id + "]/" + element.getName() + "/*");// +upperElement); //$NON-NLS-1$ //$NON-NLS-2$

                            if (!collectingevent_ids.isEmpty()) {
                                // add all the assoctions to aDbElement
                                // get child dbName
                                String childDbName = getDbName(collectingevent_ids);
                                // make a parent object
                                BeanUtils.populate(agent, agentMap);

                                // Collection collection = xmlImportRecursion(locality,
                                // upperElement, collectingevent_ids, parent, lowerdbTable);
                                Set collection = xmlImportRecursion(agentMap, childDbName, collectingevent_ids,
                                        agent, lowerdbTable);
                                if (collection != null) {
                                    agentMap.put(element.getName(), collection);
                                } else {
                                    log.debug("error on the collection " //$NON-NLS-1$
                                            + element.getName() + " with parent " + dbTable); //$NON-NLS-1$
                                }
                            }
                        } else
                        // else, dont add it
                        {
                            // if it is the tables id, just ignore. otherwise print out error
                            if (!element.getName().equals(lowerdbTable + "Id")) //$NON-NLS-1$
                            {
                                log.debug("did not add " + element.getName() //$NON-NLS-1$
                                        + " to the element " + dbTable); //$NON-NLS-1$
                            }
                        }
                    } while (i.hasNext());

                    // populate and save
                    BeanUtils.populate(agent, agentMap);

                    this.session.saveOrUpdate(agent);
                }
            }
        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex);
            // the last par tof the string conatins the class
            // if(err.startsWith("org.hibernate.PropertyValueException")){
            try {
                // try again
                // flush
                // do reference work
                // importTable("ReferenceWork");
                // the import aagain
            } catch (Exception ex1) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex1);
                ex1.printStackTrace();
            }
            // }else{
            ex.printStackTrace();
            // }
        }
    }

From source file:edu.ku.brc.dbsupport.ImportExportDB.java

License:Open Source License

@SuppressWarnings("unchecked")
    protected void sequentialXMLImport(Element dbImport, String dbTable, String parentName, long parentId) {
        try {//from  www .ja va 2  s  .c o  m
            String id = new String();
            DBTableInfo parentInfo = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase());

            List records = dbImport.selectNodes("//" + dbTable); //$NON-NLS-1$
            String lowerdbTable = lowerFirstChar(dbTable);
            // TODO: should not assume that is the id name, use getPrimaryKeyName
            DBTableInfo info = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase());
            String primaryKey = info.getPrimaryKeyName();
            // List ids = dbImport.selectNodes("//"+lowerdbTable+"Id");//assume this is dbs id name
            List ids = dbImport.selectNodes("//" + primaryKey); //$NON-NLS-1$

            if (records.size() < 1) {
                log.debug("Cannot import. Given database type:" + dbTable //$NON-NLS-1$
                        + " does not exsist in import file"); //$NON-NLS-1$
            } else {
                // loop for each record
                for (int k = 0; k < records.size(); k++) { //
                    Vector collectionIds = new Vector(20);
                    Vector<String> collectionNames = new Vector(20);
                    // keep this id to compare against it's collection
                    Element idElement = (Element) ids.get(k);
                    // id = attribute.getText();
                    id = idElement.getStringValue();
                    // make the agent and the element
                    Object agent = parentInfo.getClassObj().newInstance();
                    Map<String, Object> agentMap = new HashMap<String, Object>();
                    Element dbElement = (Element) records.get(k);
                    Iterator i = dbElement.elementIterator();
                    do {// do for each element in the record
                        Element element = (Element) i.next();

                        Object value = findTypeSequential(element, dbTable, parentId, parentName);// the
                                                                                                  // parent
                                                                                                  // is
                                                                                                  // itself,
                                                                                                  // just
                                                                                                  // a
                                                                                                  // dummy
                                                                                                  // variable
                                                                                                  // if(value!=null && value != "collection")
                        if (value != null && value != "OneToMany" && value != "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                        {
                            agentMap.put(element.getName(), value);

                        }
                        // ignore many-to-many for now
                        else if (value == "OneToMany" || value == "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                        {// RECURSE
                         // get assoicated ids
                         // List temp_collection_ids =
                         // element.selectNodes("//"+dbTable+"["+id+"]/"+element.getName()+"/*");//+upperElement);
                            List temp_collection_ids = element
                                    .selectNodes("//" + dbTable + "[" + primaryKey + " = \"" + id //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                                            + "\"]/" + element.getName() + "/*"); //$NON-NLS-1$ //$NON-NLS-2$
                            // get collection info and still dont add it
                            if (!temp_collection_ids.isEmpty()) {
                                // get child dbName
                                String childDbName = getDbName(temp_collection_ids);
                                collectionNames.addElement(childDbName);
                                for (int index = 0; index < temp_collection_ids.size(); index++) {
                                    collectionIds.addElement(temp_collection_ids.get(index));
                                }
                            }
                        } else
                        // else, dont add it
                        {
                            // if it is an id, just ignore. otherwise print out error
                            if (!element.getName().equals(lowerdbTable + "Id")) //$NON-NLS-1$
                            {
                                log.debug("did not add " + element.getName() //$NON-NLS-1$
                                        + " to the element " + dbTable); //$NON-NLS-1$
                            }
                        }
                    } while (i.hasNext());

                    // populate and save
                    BeanUtils.populate(agent, agentMap);

                    this.session.save(agent);
                    // session.lock(agent, LockMode.NONE);

                    // if there was a collection, then recurse
                    if (!collectionIds.isEmpty()) {
                        long newParentId = new Long(session.getIdentifier(agent).toString()).longValue();

                        sequentialXMLImportRecursion(collectionNames, collectionIds, dbTable, newParentId);
                    }
                }
            }
        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex);
            // String err = ex.toString();
            // the last par tof the string conatins the class
            // if(err.startsWith("org.hibernate.PropertyValueException")){
            try {
                // try again
                // flush
                // do reference work
                // importTable("ReferenceWork");
                // the import aagain
            } catch (Exception ex1) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex1);
                ex1.printStackTrace();
            }
            // }else{
            ex.printStackTrace();
            // }
        }
    }