Example usage for org.jdom2 Element getTextTrim

List of usage examples for org.jdom2 Element getTextTrim

Introduction

In this page you can find the example usage for org.jdom2 Element getTextTrim.

Prototype

public String getTextTrim() 

Source Link

Document

Returns the textual content of this element with all surrounding whitespace removed.

Usage

From source file:org.mycore.mods.MCRMODSDateHelper.java

License:Open Source License

public static Date getDate(Element element) {
    if (element == null) {
        return null;
    }/*from  ww  w  . j  a  va2 s. c om*/

    String text = element.getTextTrim();
    if ((text == null) || text.isEmpty()) {
        return null;
    }

    String encoding = element.getAttributeValue("encoding", "unknown").toLowerCase(DATE_LOCALE);
    String key = encoding + "-" + text.length();
    MCRMODSDateFormat format = firstNonNull(MCRMODSDateFormat.getFormat(key),
            MCRMODSDateFormat.getFormat(encoding));
    if (format == null) {
        throw reportParseException(encoding, text, null);
    }
    try {
        return format.parseDate(text);
    } catch (ParseException ex) {
        throw reportParseException(encoding, text, ex);
    }
}

From source file:org.mycore.mods.MCRMODSWrapper.java

License:Open Source License

public String getElementValue(String xPath) {
    Element element = getElement(xPath);
    return (element == null ? null : element.getTextTrim());
}

From source file:org.mycore.services.fieldquery.MCRQuery.java

License:Open Source License

/**
 * Parses a XML representation of a query.
 * /*from ww w.  j av a 2  s  . c o m*/
 * @param doc
 *            the XML document
 * @return the parsed MCRQuery
 */
public static MCRQuery parseXML(Document doc) {
    Element xml = doc.getRootElement();
    Element conditions = xml.getChild("conditions");
    MCRQuery query = null;
    if (conditions.getAttributeValue("format", "xml").equals("xml")) {
        Element condElem = (Element) conditions.getChildren().get(0);
        query = new MCRQuery(new MCRQueryParser().parse(condElem));
    } else {
        String queryString = conditions.getTextTrim();
        query = new MCRQuery(new MCRQueryParser().parse(queryString));
    }

    String max = xml.getAttributeValue("maxResults", "");
    if (max.length() > 0) {
        query.setMaxResults(Integer.parseInt(max));
    }

    List<MCRSortBy> sortBy = null;
    Element sortByElem = xml.getChild("sortBy");

    if (sortByElem != null) {
        List children = sortByElem.getChildren();
        sortBy = new ArrayList<MCRSortBy>(children.size());

        for (Object aChildren : children) {
            Element sortByChild = (Element) aChildren;
            String name = sortByChild.getAttributeValue("name");
            String ad = sortByChild.getAttributeValue("order");

            boolean direction = "ascending".equals(ad) ? MCRSortBy.ASCENDING : MCRSortBy.DESCENDING;
            sortBy.add(new MCRSortBy(name, direction));
        }
    }
    if (sortBy != null) {
        query.setSortBy(sortBy);
    }

    return query;
}

From source file:org.mycore.user2.MCRRealmFactory.java

License:Open Source License

/**
 * //from   ww w. j a v  a2  s .c  o m
 */
private static void loadRealms() {
    Element root;
    try {
        root = getRealms().getRootElement();
    } catch (SAXException | JDOMException | TransformerException | IOException e) {
        throw new MCRException("Could not load realms from URI: " + realmsURI);
    }
    String localRealmID = root.getAttributeValue("local");
    /** Map of defined realms, key is the ID of the realm */
    HashMap<String, MCRRealm> realmsMap = new HashMap<String, MCRRealm>();

    HashMap<String, MCRUserAttributeMapper> attributeMapper = new HashMap<String, MCRUserAttributeMapper>();

    /** List of defined realms */
    List<MCRRealm> realmsList = new ArrayList<MCRRealm>();

    List<Element> realms = (List<Element>) (root.getChildren("realm"));
    for (Element child : realms) {
        String id = child.getAttributeValue("id");
        MCRRealm realm = new MCRRealm(id);

        List<Element> labels = (List<Element>) (child.getChildren("label"));
        for (Element label : labels) {
            String text = label.getTextTrim();
            String lang = label.getAttributeValue("lang", Namespace.XML_NAMESPACE);
            realm.setLabel(lang, text);
        }

        realm.setPasswordChangeURL(child.getChildTextTrim("passwordChangeURL"));
        Element login = child.getChild("login");
        if (login != null) {
            realm.setLoginURL(login.getAttributeValue("url"));
            realm.setRedirectParameter(login.getAttributeValue("redirectParameter"));
            realm.setRealmParameter(login.getAttributeValue("realmParameter"));
        }
        Element createElement = child.getChild("create");
        if (createElement != null) {
            realm.setCreateURL(createElement.getAttributeValue("url"));
        }

        attributeMapper.put(id, MCRUserAttributeMapper.instance(child));

        realmsMap.put(id, realm);
        realmsList.add(realm);
        if (localRealmID.equals(id)) {
            localRealm = realm;
        }
    }
    MCRRealmFactory.realmsDocument = root.getDocument();
    MCRRealmFactory.realmsMap = realmsMap;
    MCRRealmFactory.realmsList = realmsList;
    MCRRealmFactory.attributeMapper = attributeMapper;
}

From source file:org.rometools.feed.module.base.io.CustomTagParser.java

License:Open Source License

public Module parse(Element element) {
    CustomTags module = new CustomTagsImpl();
    ArrayList tags = new ArrayList();
    List elements = element.getChildren();
    Iterator it = elements.iterator();
    while (it.hasNext()) {
        Element child = (Element) it.next();
        if (child.getNamespace().equals(NS)) {
            String type = child.getAttributeValue("type");
            try {
                if (type == null) {
                    continue;
                } else if (type.equals("string")) {
                    tags.add(new CustomTagImpl(child.getName(), child.getText()));
                } else if (type.equals("int")) {
                    tags.add(new CustomTagImpl(child.getName(), new Integer(child.getTextTrim())));
                } else if (type.equals("float")) {
                    tags.add(new CustomTagImpl(child.getName(), new Float(child.getTextTrim())));
                } else if (type.equals("intUnit")) {
                    tags.add(new CustomTagImpl(child.getName(), new IntUnit(child.getTextTrim())));
                } else if (type.equals("floatUnit")) {
                    tags.add(new CustomTagImpl(child.getName(), new FloatUnit(child.getTextTrim())));
                } else if (type.equals("date")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(),
                                new ShortDate(GoogleBaseParser.SHORT_DT_FMT.parse(child.getTextTrim()))));
                    } catch (ParseException e) {
                        log.log(Level.WARNING, "Unable to parse date type on " + child.getName(), e);
                    }//from ww  w .  ja va  2  s  .  c om
                } else if (type.equals("dateTime")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(),
                                GoogleBaseParser.LONG_DT_FMT.parse(child.getTextTrim())));
                    } catch (ParseException e) {
                        log.log(Level.WARNING, "Unable to parse date type on " + child.getName(), e);
                    }
                } else if (type.equals("dateTimeRange")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(),
                                new DateTimeRange(
                                        GoogleBaseParser.LONG_DT_FMT.parse(
                                                child.getChild("start", CustomTagParser.NS).getText().trim()),
                                        GoogleBaseParser.LONG_DT_FMT.parse(
                                                child.getChild("end", CustomTagParser.NS).getText().trim()))));
                    } catch (Exception e) {
                        log.log(Level.WARNING, "Unable to parse date type on " + child.getName(), e);
                    }
                } else if (type.equals("url")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(), new URL(child.getTextTrim())));
                    } catch (MalformedURLException e) {
                        log.log(Level.WARNING, "Unable to parse URL type on " + child.getName(), e);
                    }
                } else if (type.equals("boolean")) {
                    tags.add(
                            new CustomTagImpl(child.getName(), new Boolean(child.getTextTrim().toLowerCase())));
                } else if (type.equals("location")) {
                    tags.add(new CustomTagImpl(child.getName(), new CustomTagImpl.Location(child.getText())));
                } else {
                    throw new Exception("Unknown type: " + type);
                }
            } catch (Exception e) {
                log.log(Level.WARNING, "Unable to parse type on " + child.getName(), e);
            }
        }
    }
    module.setValues(tags);
    return module;
}

From source file:org.rometools.feed.module.cc.io.ModuleParserRSS2.java

License:Open Source License

public Module parse(Element element) {
    CreativeCommonsImpl module = new CreativeCommonsImpl();
    //Do channel global
    {//from  w ww  .  j  a  v  a2 s.  c o m
        Element root = element;
        while (!root.getName().equals("channel") && !root.getName().equals("feed"))
            root = root.getParentElement();
        ArrayList licenses = new ArrayList();
        List items = null;
        if (root.getName().equals("channel"))
            items = root.getChildren("item");
        else
            items = root.getChildren("entry");

        Iterator iit = items.iterator();
        while (iit.hasNext()) {
            Element item = (Element) iit.next();
            List licenseTags = item.getChildren("license", NS);
            Iterator lit = licenseTags.iterator();
            while (lit.hasNext()) {
                Element licenseTag = (Element) lit.next();
                License license = License.findByValue(licenseTag.getTextTrim());
                if (!licenses.contains(license))
                    ;
                licenses.add(license);
            }
        }
        if (licenses.size() > 0) {
            module.setAllLicenses((License[]) licenses.toArray(new License[0]));
        }
    }
    // do element local
    ArrayList licenses = new ArrayList();
    List licenseTags = element.getChildren("license", NS);
    Iterator it = licenseTags.iterator();
    while (it.hasNext()) {
        Element licenseTag = (Element) it.next();
        licenses.add(License.findByValue(licenseTag.getTextTrim()));
    }
    if (licenses.size() > 0) {
        module.setLicenses((License[]) licenses.toArray(new License[0]));
    }

    if (module.getLicenses() != null && module.getAllLicenses() != null) {
        return module;
    } else {
        return null;
    }
}

From source file:org.rometools.feed.module.itunes.io.ITunesParser.java

License:Open Source License

public com.sun.syndication.feed.module.Module parse(org.jdom2.Element element) {
    AbstractITunesObject module = null;// ww w.  j  a v  a  2 s  .  co m

    if (element.getName().equals("channel")) {
        FeedInformationImpl feedInfo = new FeedInformationImpl();
        module = feedInfo;

        //Now I am going to get the channel specific tags
        Element owner = element.getChild("owner", ns);

        if (owner != null) {
            Element name = owner.getChild("name", ns);

            if (name != null) {
                feedInfo.setOwnerName(name.getValue().trim());
            }

            Element email = owner.getChild("email", ns);

            if (email != null) {
                feedInfo.setOwnerEmailAddress(email.getValue().trim());
            }
        }

        Element image = element.getChild("image", ns);

        if ((image != null) && (image.getAttributeValue("href") != null)) {
            try {
                URL imageURL = new URL(image.getAttributeValue("href").trim());
                feedInfo.setImage(imageURL);
            } catch (MalformedURLException e) {
                log.finer(
                        "Malformed URL Exception reading itunes:image tag: " + image.getAttributeValue("href"));
            }
        }

        List categories = element.getChildren("category", ns);
        for (Iterator it = categories.iterator(); it.hasNext();) {
            Element category = (Element) it.next();
            if ((category != null) && (category.getAttribute("text") != null)) {
                Category cat = new Category();
                cat.setName(category.getAttribute("text").getValue().trim());

                Element subcategory = category.getChild("category", ns);

                if (subcategory != null && subcategory.getAttribute("text") != null) {
                    Subcategory subcat = new Subcategory();
                    subcat.setName(subcategory.getAttribute("text").getValue().trim());
                    cat.setSubcategory(subcat);
                }

                feedInfo.getCategories().add(cat);
            }
        }

    } else if (element.getName().equals("item")) {
        EntryInformationImpl entryInfo = new EntryInformationImpl();
        module = entryInfo;

        //Now I am going to get the item specific tags

        Element duration = element.getChild("duration", ns);

        if (duration != null && duration.getValue() != null) {
            Duration dur = new Duration(duration.getValue().trim());
            entryInfo.setDuration(dur);
        }
    }
    if (module != null) {
        //All these are common to both Channel and Item
        Element author = element.getChild("author", ns);

        if (author != null && author.getText() != null) {
            module.setAuthor(author.getText());
        }

        Element block = element.getChild("block", ns);

        if (block != null) {
            module.setBlock(true);
        }

        Element explicit = element.getChild("explicit", ns);

        if ((explicit != null) && explicit.getValue() != null
                && explicit.getValue().trim().equalsIgnoreCase("yes")) {
            module.setExplicit(true);
        }

        Element keywords = element.getChild("keywords", ns);

        if (keywords != null) {
            StringTokenizer tok = new StringTokenizer(getXmlInnerText(keywords).trim(), ",");
            String[] keywordsArray = new String[tok.countTokens()];

            for (int i = 0; tok.hasMoreTokens(); i++) {
                keywordsArray[i] = tok.nextToken();
            }

            module.setKeywords(keywordsArray);
        }

        Element subtitle = element.getChild("subtitle", ns);

        if (subtitle != null) {
            module.setSubtitle(subtitle.getTextTrim());
        }

        Element summary = element.getChild("summary", ns);

        if (summary != null) {
            module.setSummary(summary.getTextTrim());
        }
    }

    return module;
}

From source file:org.rometools.feed.module.mediarss.io.MediaModuleParser.java

License:Open Source License

private Metadata parseMetadata(Element e) {
    Metadata md = new Metadata();
    // categories
    {/*w w  w  .j  a  va  2  s  .  c o m*/
        List categories = e.getChildren("category", getNS());
        ArrayList values = new ArrayList();

        for (int i = 0; (categories != null) && (i < categories.size()); i++) {
            try {
                Element cat = (Element) categories.get(i);
                values.add(new Category(cat.getAttributeValue("scheme"), cat.getAttributeValue("label"),
                        cat.getText()));
            } catch (Exception ex) {
                LOG.log(Level.WARNING, "Exception parsing category tag.", ex);
            }
        }

        md.setCategories((Category[]) values.toArray(new Category[values.size()]));
    }

    // copyright
    try {
        Element copy = e.getChild("copyright", getNS());

        if (copy != null) {
            md.setCopyright(copy.getText());
            md.setCopyrightUrl(
                    (copy.getAttributeValue("url") != null) ? new URI(copy.getAttributeValue("url")) : null);
        }
    } catch (Exception ex) {
        LOG.log(Level.WARNING, "Exception parsing copyright tag.", ex);
    }
    // credits
    {
        List credits = e.getChildren("credit", getNS());
        ArrayList values = new ArrayList();

        for (int i = 0; (credits != null) && (i < credits.size()); i++) {
            try {
                Element cred = (Element) credits.get(i);
                values.add(new Credit(cred.getAttributeValue("scheme"), cred.getAttributeValue("role"),
                        cred.getText()));
                md.setCredits((Credit[]) values.toArray(new Credit[values.size()]));
            } catch (Exception ex) {
                LOG.log(Level.WARNING, "Exception parsing credit tag.", ex);
            }
        }
    }

    // description
    try {
        Element description = e.getChild("description", getNS());

        if (description != null) {
            md.setDescription(description.getText());
            md.setDescriptionType(description.getAttributeValue("type"));
        }
    } catch (Exception ex) {
        LOG.log(Level.WARNING, "Exception parsing description tag.", ex);
    }

    // hash
    try {
        Element hash = e.getChild("hash", getNS());

        if (hash != null) {
            md.setHash(new Hash(hash.getAttributeValue("algo"), hash.getText()));
        }
    } catch (Exception ex) {
        LOG.log(Level.WARNING, "Exception parsing hash tag.", ex);
    }
    // keywords
    {
        Element keywords = e.getChild("keywords", getNS());

        if (keywords != null) {
            StringTokenizer tok = new StringTokenizer(keywords.getText(), ",");
            String[] value = new String[tok.countTokens()];

            for (int i = 0; tok.hasMoreTokens(); i++) {
                value[i] = tok.nextToken().trim();
            }

            md.setKeywords(value);
        }
    }
    // ratings
    {
        List ratings = e.getChildren("rating", getNS());
        ArrayList values = new ArrayList();

        for (int i = 0; (ratings != null) && (i < ratings.size()); i++) {
            try {
                Element rat = (Element) ratings.get(i);
                values.add(new Rating(rat.getAttributeValue("scheme"), rat.getText()));
            } catch (Exception ex) {
                LOG.log(Level.WARNING, "Exception parsing rating tag.", ex);
            }
        }

        md.setRatings((Rating[]) values.toArray(new Rating[values.size()]));
    }
    // text
    {
        List texts = e.getChildren("text", getNS());
        ArrayList values = new ArrayList();

        for (int i = 0; (texts != null) && (i < texts.size()); i++) {
            try {
                Element text = (Element) texts.get(i);
                Time start = (text.getAttributeValue("start") == null) ? null
                        : new Time(text.getAttributeValue("start"));
                Time end = (text.getAttributeValue("end") == null) ? null
                        : new Time(text.getAttributeValue("end"));
                values.add(new Text(text.getAttributeValue("type"), text.getTextTrim(), start, end));
            } catch (Exception ex) {
                LOG.log(Level.WARNING, "Exception parsing text tag.", ex);
            }
        }

        md.setText((Text[]) values.toArray(new Text[values.size()]));
    }
    // thumbnails
    {
        List thumbnails = e.getChildren("thumbnail", getNS());
        ArrayList values = new ArrayList();

        for (int i = 0; (thumbnails != null) && (i < thumbnails.size()); i++) {
            try {
                Element thumb = (Element) thumbnails.get(i);
                Time t = (thumb.getAttributeValue("time") == null) ? null
                        : new Time(thumb.getAttributeValue("time"));
                Integer width = (thumb.getAttributeValue("width") == null) ? null
                        : new Integer(thumb.getAttributeValue("width"));
                Integer height = (thumb.getAttributeValue("height") == null) ? null
                        : new Integer(thumb.getAttributeValue("height"));
                values.add(new Thumbnail(new URI(thumb.getAttributeValue("url")), width, height, t));
            } catch (Exception ex) {
                LOG.log(Level.WARNING, "Exception parsing thumbnail tag.", ex);
            }
        }

        md.setThumbnail((Thumbnail[]) values.toArray(new Thumbnail[values.size()]));
    }
    // title
    {
        Element title = e.getChild("title", getNS());

        if (title != null) {
            md.setTitle(title.getText());
            md.setTitleType(title.getAttributeValue("type"));
        }
    }
    // restrictions
    {
        List restrictions = e.getChildren("restriction", getNS());
        ArrayList values = new ArrayList();

        for (int i = 0; i < restrictions.size(); i++) {
            Element r = (Element) restrictions.get(i);
            Restriction.Type type = null;

            if (r.getAttributeValue("type").equalsIgnoreCase("uri")) {
                type = Restriction.Type.URI;
            } else if (r.getAttributeValue("type").equalsIgnoreCase("country")) {
                type = Restriction.Type.COUNTRY;
            }

            Restriction.Relationship relationship = null;

            if (r.getAttributeValue("relationship").equalsIgnoreCase("allow")) {
                relationship = Restriction.Relationship.ALLOW;
            } else if (r.getAttributeValue("relationship").equalsIgnoreCase("deny")) {
                relationship = Restriction.Relationship.DENY;
            }

            Restriction value = new Restriction(relationship, type, r.getTextTrim());
            values.add(value);
        }

        md.setRestrictions((Restriction[]) values.toArray(new Restriction[values.size()]));
    }
    // handle adult
    {
        Element adult = e.getChild("adult", getNS());

        if ((adult != null) && (md.getRatings().length == 0)) {
            Rating[] r = new Rating[1];

            if (adult.getTextTrim().equals("true")) {
                r[0] = new Rating("urn:simple", "adult");
            } else {
                r[0] = new Rating("urn:simple", "nonadult");
            }

            md.setRatings(r);
        }
    }

    return md;
}

From source file:org.skfiy.maven.plugin.fastconfig.FastconfigMojo.java

License:Apache License

private Fastconfig buildFastconfig() throws Exception {
    PluginParameterExpressionEvaluator pel = new PluginParameterExpressionEvaluator(session, execution);
    Fastconfig fastconfig = new Fastconfig();

    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(config);
    Element root = doc.getRootElement();

    // config-file
    for (Element cf : root.getChildren()) {
        String path = String.valueOf(pel.evaluate(cf.getAttributeValue("path")));
        File file = new File(path);
        if (!file.isAbsolute()) {
            file = new File(outputDirectory, path);
        }/*from   ww w  .  jav  a  2 s .  co  m*/

        ConfigFile.Mode mode;
        if (StringUtils.isNotEmpty(cf.getAttributeValue("mode"))) {
            mode = ConfigFile.Mode.valueOf(cf.getAttributeValue("mode"));
        } else {
            mode = toMode(path.substring(path.lastIndexOf(".") + 1));
        }

        if (mode == null) {
            throw new FastconfigException("Not found file[" + path + "] replace mode");
        }

        ConfigFile configFile = new ConfigFile(file, mode);
        // replacement
        for (Element rt : cf.getChildren()) {
            String expression = rt.getAttributeValue("expression");
            String value = String.valueOf(pel.evaluate(rt.getTextTrim()));
            configFile.addReplacement(new Replacement(expression, value));
        }
        fastconfig.addConfigFile(configFile);
    }
    return fastconfig;
}

From source file:org.sonar.cxx.sensors.rats.CxxRatsSensor.java

License:Open Source License

@Override
protected void processReport(final SensorContext context, File report)
        throws org.jdom2.JDOMException, java.io.IOException {
    LOG.debug("Parsing 'RATS' format");

    try {/*from   w ww.j  a  v a 2  s. c om*/
        SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);
        Element root = builder.build(report).getRootElement();
        List<Element> vulnerabilities = root.getChildren("vulnerability");
        for (Element vulnerability : vulnerabilities) {
            String type = getVulnerabilityType(vulnerability.getChild("type"));
            String message = vulnerability.getChild("message").getTextTrim();

            List<Element> files = vulnerability.getChildren("file");

            for (Element file : files) {
                String fileName = file.getChild("name").getTextTrim();

                List<Element> lines = file.getChildren("line");
                for (Element lineElem : lines) {
                    String line = lineElem.getTextTrim();

                    CxxReportIssue issue = new CxxReportIssue(type, fileName, line, message);
                    saveUniqueViolation(context, issue);
                }
            }
        }
    } catch (org.jdom2.input.JDOMParseException e) {
        // when RATS fails the XML file might be incomplete
        LOG.error("Ignore incomplete XML output from RATS '{}'", CxxUtils.getStackTrace(e));
    }
}