Example usage for org.jdom2 Element getChildren

List of usage examples for org.jdom2 Element getChildren

Introduction

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

Prototype

public List<Element> getChildren(final String cname, final Namespace ns) 

Source Link

Document

This returns a List of all the child elements nested directly (one level deep) within this element with the given local name and belonging to the given Namespace, returned as Element objects.

Usage

From source file:com.bc.ceres.site.util.ExclusionListBuilder.java

License:Open Source License

static void addPomToExclusionList(File exclusionList, URL pom) throws Exception {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(exclusionList, true))) {
        final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        final Document w3cDoc = builder.parse(pom.openStream());
        final DOMBuilder domBuilder = new DOMBuilder();
        final org.jdom2.Document doc = domBuilder.build(w3cDoc);
        final Element root = doc.getRootElement();
        final Namespace namespace = root.getNamespace();
        final List<Element> modules = root.getChildren(MODULES_NODE, namespace);
        if (modules != null) {
            // hard-coded index 0 is ok because xml-schema allows only one <modules>-node
            final Element modulesNode = modules.get(0);
            final List<Element> modulesList = modulesNode.getChildren(MODULE_NAME, namespace);
            for (Element module : modulesList) {
                addModuleToExclusionList(exclusionList, writer, module.getText());
            }/*from w  w w .j av a2s.  c o m*/
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.rometools.modules.atom.io.AtomModuleParser.java

License:Apache License

@Override
public Module parse(Element element, Locale locale) {
    AtomLinkModuleImpl mod = new AtomLinkModuleImpl();
    if (element.getName().equals("channel") || element.getName().equals("item")) {
        List<Element> links = element.getChildren("link", NS);
        List<Link> result = new LinkedList<Link>();
        for (Element link : links) {
            Link l = parseLink(link);//  w w  w  .  ja  va2s  . co  m
            result.add(l);
        }
        mod.setLinks(result);
        return mod;
    }
    return null;
}

From source file:com.rometools.modules.cc.io.ModuleParserRSS1.java

License:Open Source License

@Override
public Module parse(final Element element, final Locale locale) {
    final CreativeCommonsImpl module = new CreativeCommonsImpl();
    {//  w  w  w  .  jav  a  2  s .co m
        // Parsing Channel level.
        Element root = element;
        while (root.getParentElement() != null) {
            root = root.getParentElement();
        }
        final List<Element> licenseList = root.getChildren("License", NS);
        final ArrayList<License> licenses = new ArrayList<License>();
        final Iterator<Element> it = licenseList.iterator();
        while (it.hasNext()) {
            final Element licenseTag = it.next();
            final String licenseURI = licenseTag.getAttributeValue("about", RDF);
            if (licenseURI == null) {
                continue;
            }
            License license = License.findByValue(licenseURI);
            {
                final ArrayList<Behaviour> permitsValues = new ArrayList<Behaviour>();
                final ArrayList<Behaviour> requiresValues = new ArrayList<Behaviour>();
                final List<Element> permitsTags = licenseTag.getChildren("permits", NS);
                Iterator<Element> sit = permitsTags.iterator();
                while (sit.hasNext()) {
                    final Element permitTag = sit.next();
                    permitsValues
                            .add(License.Behaviour.findByValue(permitTag.getAttributeValue("resource", RDF)));
                }
                final List<Element> requiresTags = licenseTag.getChildren("requires", NS);
                sit = requiresTags.iterator();
                while (sit.hasNext()) {
                    final Element requireTag = sit.next();
                    requiresValues
                            .add(License.Behaviour.findByValue(requireTag.getAttributeValue("resource", RDF)));
                }
                license = new License(licenseURI,
                        requiresValues.toArray(new License.Behaviour[requiresValues.size()]),
                        permitsValues.toArray(new License.Behaviour[permitsValues.size()]));

            }

            licenses.add(license);
        }
        module.setAllLicenses(licenses.toArray(new License[0]));
    }
    final ArrayList<License> licenses = new ArrayList<License>();
    final List<Element> licenseTags = element.getChildren("license", NS);
    final Iterator<Element> lit = licenseTags.iterator();
    while (lit.hasNext()) {
        final Element licenseTag = lit.next();
        licenses.add(License.findByValue(licenseTag.getAttributeValue("resource", RDF)));
    }

    if (!licenses.isEmpty()) {
        module.setLicenses(licenses.toArray(new License[licenses.size()]));
    }

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

From source file:com.rometools.modules.content.io.ContentModuleParser.java

License:Open Source License

@Override
public com.rometools.rome.feed.module.Module parse(final Element element, final Locale locale) {
    boolean foundSomething = false;
    final ContentModule cm = new ContentModuleImpl();
    final List<Element> encodeds = element.getChildren("encoded", CONTENT_NS);
    final ArrayList<String> contentStrings = new ArrayList<String>();
    final ArrayList<String> encodedStrings = new ArrayList<String>();

    if (!encodeds.isEmpty()) {
        foundSomething = true;//ww w.  j a  va  2  s . c  o  m

        for (int i = 0; i < encodeds.size(); i++) {
            final Element encodedElement = encodeds.get(i);
            encodedStrings.add(encodedElement.getText());
            contentStrings.add(encodedElement.getText());
        }
    }

    final ArrayList<ContentItem> contentItems = new ArrayList<ContentItem>();
    final List<Element> items = element.getChildren("items", CONTENT_NS);

    for (int i = 0; i < items.size(); i++) {
        foundSomething = true;

        final List<Element> lis = items.get(i).getChild("Bag", RDF_NS).getChildren("li", RDF_NS);

        for (int j = 0; j < lis.size(); j++) {
            final ContentItem ci = new ContentItem();
            final Element li = lis.get(j);
            final Element item = li.getChild("item", CONTENT_NS);
            final Element format = item.getChild("format", CONTENT_NS);
            final Element encoding = item.getChild("encoding", CONTENT_NS);
            final Element value = item.getChild("value", RDF_NS);

            if (value != null) {
                if (value.getAttributeValue("parseType", RDF_NS) != null) {
                    ci.setContentValueParseType(value.getAttributeValue("parseType", RDF_NS));
                }

                if (ci.getContentValueParseType() != null && ci.getContentValueParseType().equals("Literal")) {
                    ci.setContentValue(getXmlInnerText(value));
                    contentStrings.add(getXmlInnerText(value));
                    ci.setContentValueNamespaces(value.getAdditionalNamespaces());
                } else {
                    ci.setContentValue(value.getText());
                    contentStrings.add(value.getText());
                }

                ci.setContentValueDOM(value.clone().getContent());
            }

            if (format != null) {
                ci.setContentFormat(format.getAttribute("resource", RDF_NS).getValue());
            }

            if (encoding != null) {
                ci.setContentEncoding(encoding.getAttribute("resource", RDF_NS).getValue());
            }

            if (item != null) {
                final Attribute about = item.getAttribute("about", RDF_NS);

                if (about != null) {
                    ci.setContentAbout(about.getValue());
                }
            }

            contentItems.add(ci);
        }
    }

    cm.setEncodeds(encodedStrings);
    cm.setContentItems(contentItems);
    cm.setContents(contentStrings);

    return foundSomething ? cm : null;
}

From source file:com.rometools.modules.georss.GMLParser.java

License:Apache License

static Module parseGML(final Element element) {
    GeoRSSModule geoRSSModule = null;//  w w w .  ja  v  a  2 s  . co  m

    final Element pointElement = element.getChild("Point", GeoRSSModule.GML_NS);
    final Element lineStringElement = element.getChild("LineString", GeoRSSModule.GML_NS);
    final Element polygonElement = element.getChild("Polygon", GeoRSSModule.GML_NS);
    final Element envelopeElement = element.getChild("Envelope", GeoRSSModule.GML_NS);
    if (pointElement != null) {
        final Element posElement = pointElement.getChild("pos", GeoRSSModule.GML_NS);
        if (posElement != null) {
            geoRSSModule = new GMLModuleImpl();
            final String coordinates = posElement.getText();
            final String[] coord = Strings.trimToEmpty(coordinates).split(" ");
            final Position pos = new Position(Double.parseDouble(coord[0]), Double.parseDouble(coord[1]));
            geoRSSModule.setGeometry(new Point(pos));
        }
    } else if (lineStringElement != null) {
        final Element posListElement = lineStringElement.getChild("posList", GeoRSSModule.GML_NS);
        if (posListElement != null) {
            geoRSSModule = new GMLModuleImpl();
            geoRSSModule.setGeometry(new LineString(parsePosList(posListElement)));
        }
    } else if (polygonElement != null) {
        Polygon poly = null;

        // The external ring
        final Element exteriorElement = polygonElement.getChild("exterior", GeoRSSModule.GML_NS);
        if (exteriorElement != null) {
            final Element linearRingElement = exteriorElement.getChild("LinearRing", GeoRSSModule.GML_NS);
            if (linearRingElement != null) {
                final Element posListElement = linearRingElement.getChild("posList", GeoRSSModule.GML_NS);
                if (posListElement != null) {
                    if (poly == null) {
                        poly = new Polygon();
                    }
                    poly.setExterior(new LinearRing(parsePosList(posListElement)));
                }
            }
        }

        // The internal rings (holes)
        final List<Element> interiorElementList = polygonElement.getChildren("interior", GeoRSSModule.GML_NS);
        final Iterator<Element> it = interiorElementList.iterator();
        while (it.hasNext()) {
            final Element interiorElement = it.next();
            if (interiorElement != null) {
                final Element linearRingElement = interiorElement.getChild("LinearRing", GeoRSSModule.GML_NS);
                if (linearRingElement != null) {
                    final Element posListElement = linearRingElement.getChild("posList", GeoRSSModule.GML_NS);
                    if (posListElement != null) {
                        if (poly == null) {
                            poly = new Polygon();
                        }
                        poly.getInterior().add(new LinearRing(parsePosList(posListElement)));
                    }
                }
            }

        }

        if (poly != null) {
            geoRSSModule = new GMLModuleImpl();
            geoRSSModule.setGeometry(poly);
        }
    } else if (envelopeElement != null) {
        final Element lowerElement = envelopeElement.getChild("lowerCorner", GeoRSSModule.GML_NS);
        final Element upperElement = envelopeElement.getChild("upperCorner", GeoRSSModule.GML_NS);
        if (lowerElement != null && upperElement != null) {
            geoRSSModule = new GMLModuleImpl();
            final String lowerCoordinates = lowerElement.getText();
            final String[] lowerCoord = Strings.trimToEmpty(lowerCoordinates).split(" ");
            final String upperCoordinates = upperElement.getText();
            final String[] upperCoord = Strings.trimToEmpty(upperCoordinates).split(" ");
            final Envelope envelope = new Envelope(Double.parseDouble(lowerCoord[0]),
                    Double.parseDouble(lowerCoord[1]), Double.parseDouble(upperCoord[0]),
                    Double.parseDouble(upperCoord[1]));
            geoRSSModule.setGeometry(envelope);
        }
    }

    return geoRSSModule;
}

From source file:com.rometools.modules.itunes.io.ITunesParser.java

License:Open Source License

@Override
public com.rometools.rome.feed.module.Module parse(final Element element, final Locale locale) {
    AbstractITunesObject module = null;/*from  w w w. j av a 2  s.  c o m*/

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

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

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

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

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

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

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

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

        final List<Element> categories = element.getChildren("category", ns);
        for (final Element element2 : categories) {
            final Element category = element2;
            if (category != null && category.getAttribute("text") != null) {
                final Category cat = new Category();
                cat.setName(category.getAttribute("text").getValue().trim());

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            module.setKeywords(keywordsArray);
        }

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

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

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

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

    return module;
}

From source file:com.rometools.modules.mediarss.io.MediaModuleParser.java

License:Open Source License

private MediaContent[] parseContent(final Element e) {

    final List<Element> contents = e.getChildren("content", getNS());
    final ArrayList<MediaContent> values = new ArrayList<MediaContent>();

    try {//from   w ww.  ja v  a 2 s .c  o m
        for (int i = 0; contents != null && i < contents.size(); i++) {
            final Element content = contents.get(i);
            MediaContent mc = null;

            if (content.getAttributeValue("url") != null) {
                try {
                    mc = new MediaContent(
                            new UrlReference(new URI(content.getAttributeValue("url").replace(' ', '+'))));
                    mc.setPlayer(parsePlayer(content));
                } catch (final Exception ex) {
                    LOG.warn("Exception parsing content tag.", ex);
                }
            } else {
                mc = new MediaContent(parsePlayer(content));
            }
            if (mc != null) {
                values.add(mc);
                try {
                    if (content.getAttributeValue("channels") != null) {
                        mc.setAudioChannels(Integer.valueOf(content.getAttributeValue("channels")));
                    }
                } catch (final Exception ex) {
                    LOG.warn("Exception parsing content tag.", ex);
                }
                try {
                    if (content.getAttributeValue("bitrate") != null) {
                        mc.setBitrate(Float.valueOf(content.getAttributeValue("bitrate")));
                    }
                } catch (final Exception ex) {
                    LOG.warn("Exception parsing content tag.", ex);
                }
                try {
                    if (content.getAttributeValue("duration") != null) {
                        mc.setDuration(Longs.parseDecimal(content.getAttributeValue("duration")));
                    }
                } catch (final Exception ex) {
                    LOG.warn("Exception parsing content tag.", ex);
                }

                mc.setMedium(content.getAttributeValue("medium"));

                final String expression = content.getAttributeValue("expression");

                if (expression != null) {
                    if (expression.equalsIgnoreCase("full")) {
                        mc.setExpression(Expression.FULL);
                    } else if (expression.equalsIgnoreCase("sample")) {
                        mc.setExpression(Expression.SAMPLE);
                    } else if (expression.equalsIgnoreCase("nonstop")) {
                        mc.setExpression(Expression.NONSTOP);
                    }
                }

                try {
                    if (content.getAttributeValue("fileSize") != null) {
                        mc.setFileSize(Long.valueOf(content.getAttributeValue("fileSize")));
                    }
                } catch (final Exception ex) {
                    LOG.warn("Exception parsing content tag.", ex);
                }
                try {
                    if (content.getAttributeValue("framerate") != null) {
                        mc.setFramerate(Float.valueOf(content.getAttributeValue("framerate")));
                    }
                } catch (final Exception ex) {
                    LOG.warn("Exception parsing content tag.", ex);
                }
                try {
                    if (content.getAttributeValue("height") != null) {
                        mc.setHeight(Integer.valueOf(content.getAttributeValue("height")));
                    }
                } catch (final Exception ex) {
                    LOG.warn("Exception parsing content tag.", ex);
                }

                mc.setLanguage(content.getAttributeValue("lang"));
                mc.setMetadata(parseMetadata(content));
                try {
                    if (content.getAttributeValue("samplingrate") != null) {
                        mc.setSamplingrate(Float.valueOf(content.getAttributeValue("samplingrate")));
                    }
                } catch (final Exception ex) {
                    LOG.warn("Exception parsing content tag.", ex);
                }

                mc.setType(content.getAttributeValue("type"));
                try {
                    if (content.getAttributeValue("width") != null) {
                        mc.setWidth(Integer.valueOf(content.getAttributeValue("width")));
                    }
                } catch (final Exception ex) {
                    LOG.warn("Exception parsing content tag.", ex);
                }

                if (content.getAttributeValue("isDefault") != null) {
                    mc.setDefaultContent(Boolean.valueOf(content.getAttributeValue("isDefault")));
                }
            } else {
                LOG.warn("Could not find MediaContent.");
            }

        }
    } catch (final Exception ex) {
        LOG.warn("Exception parsing content tag.", ex);
    }

    return values.toArray(new MediaContent[values.size()]);
}

From source file:com.rometools.modules.mediarss.io.MediaModuleParser.java

License:Open Source License

private MediaGroup[] parseGroup(final Element e) {
    final List<Element> groups = e.getChildren("group", getNS());
    final ArrayList<MediaGroup> values = new ArrayList<MediaGroup>();

    for (int i = 0; groups != null && i < groups.size(); i++) {
        final Element group = groups.get(i);
        final MediaGroup g = new MediaGroup(parseContent(group));

        for (int j = 0; j < g.getContents().length; j++) {
            if (g.getContents()[j].isDefaultContent()) {
                g.setDefaultContentIndex(new Integer(j));

                break;
            }//w  ww .j a v  a  2s  . c o m
        }

        g.setMetadata(parseMetadata(group));
        values.add(g);
    }

    return values.toArray(new MediaGroup[values.size()]);
}

From source file:com.rometools.modules.mediarss.io.MediaModuleParser.java

License:Open Source License

private Metadata parseMetadata(final Element e) {
    final Metadata md = new Metadata();
    // categories
    {/*from w  w  w  . j  av  a2s . com*/
        final List<Element> categories = e.getChildren("category", getNS());
        final ArrayList<Category> values = new ArrayList<Category>();

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

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

    // copyright
    try {
        final 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 (final Exception ex) {
        LOG.warn("Exception parsing copyright tag.", ex);
    }
    // credits
    {
        final List<Element> credits = e.getChildren("credit", getNS());
        final ArrayList<Credit> values = new ArrayList<Credit>();

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

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

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

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

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

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

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

            md.setKeywords(value);
        }
    }
    // ratings
    {
        final ArrayList<Rating> values = new ArrayList<Rating>();

        final List<Element> ratings = e.getChildren("rating", getNS());
        for (final Element ratingElement : ratings) {
            try {
                final String ratingText = ratingElement.getText();
                String ratingScheme = Strings.trimToNull(ratingElement.getAttributeValue("scheme"));
                if (ratingScheme == null) {
                    ratingScheme = "urn:simple";
                }
                final Rating rating = new Rating(ratingScheme, ratingText);
                values.add(rating);
            } catch (final Exception ex) {
                LOG.warn("Exception parsing rating tag.", ex);
            }
        }

        md.setRatings(values.toArray(new Rating[values.size()]));

    }
    // text
    {
        final List<Element> texts = e.getChildren("text", getNS());
        final ArrayList<Text> values = new ArrayList<Text>();

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

        md.setText(values.toArray(new Text[values.size()]));
    }
    // thumbnails
    {
        final ArrayList<Thumbnail> values = new ArrayList<Thumbnail>();

        final List<Element> thumbnails = e.getChildren("thumbnail", getNS());
        for (final Element thumb : thumbnails) {
            try {

                final String timeAttr = Strings.trimToNull(thumb.getAttributeValue("time"));
                Time time = null;
                if (timeAttr != null) {
                    time = new Time(timeAttr);
                }

                final String widthAttr = thumb.getAttributeValue("width");
                final Integer width = Integers.parse(widthAttr);

                final String heightAttr = thumb.getAttributeValue("height");
                final Integer height = Integers.parse(heightAttr);

                final String url = thumb.getAttributeValue("url");
                final URI uri = new URI(url);
                final Thumbnail thumbnail = new Thumbnail(uri, width, height, time);

                values.add(thumbnail);

            } catch (final Exception ex) {
                LOG.warn("Exception parsing thumbnail tag.", ex);
            }
        }

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

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

        for (int i = 0; i < restrictions.size(); i++) {
            final Element r = 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;
            }

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

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

        if (adult != null && md.getRatings().length == 0) {
            final 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:com.rometools.modules.opensearch.impl.OpenSearchModuleParser.java

License:Apache License

@Override
public Module parse(final Element dcRoot, final Locale locale) {

    final URL baseURI = findBaseURI(dcRoot);

    boolean foundSomething = false;
    final OpenSearchModule osm = new OpenSearchModuleImpl();

    Element e = dcRoot.getChild("totalResults", OS_NS);

    if (e != null) {
        try {//from w  w  w. j av a  2 s. c o m
            osm.setTotalResults(Integer.parseInt(e.getText()));
            foundSomething = true;
        } catch (final NumberFormatException ex) {
            // Ignore setting the field and post a warning
            System.err
                    .println("Warning: The element totalResults must be an integer value: " + ex.getMessage());
        }
    }

    e = dcRoot.getChild("itemsPerPage", OS_NS);
    if (e != null) {
        try {
            osm.setItemsPerPage(Integer.parseInt(e.getText()));
            foundSomething = true;
        } catch (final NumberFormatException ex) {
            // Ignore setting the field and post a warning
            System.err
                    .println("Warning: The element itemsPerPage must be an integer value: " + ex.getMessage());
        }
    }

    e = dcRoot.getChild("startIndex", OS_NS);
    if (e != null) {
        try {
            osm.setStartIndex(Integer.parseInt(e.getText()));
            foundSomething = true;
        } catch (final NumberFormatException ex) {
            // Ignore setting the field and post a warning
            System.err.println("Warning: The element startIndex must be an integer value: " + ex.getMessage());
        }
    }

    final List<Element> queries = dcRoot.getChildren("Query", OS_NS);

    if (queries != null && !queries.isEmpty()) {

        // Create the OSQuery list
        final List<OSQuery> osqList = new LinkedList<OSQuery>();

        for (final Iterator<Element> iter = queries.iterator(); iter.hasNext();) {
            e = iter.next();
            osqList.add(parseQuery(e));
        }

        osm.setQueries(osqList);
    }

    e = dcRoot.getChild("link", OS_NS);

    if (e != null) {
        osm.setLink(parseLink(e, baseURI));
    }

    return foundSomething ? osm : null;
}