Example usage for org.jdom2 Element getAttributeValue

List of usage examples for org.jdom2 Element getAttributeValue

Introduction

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

Prototype

public String getAttributeValue(final String attname) 

Source Link

Document

This returns the attribute value for the attribute with the given name and within no namespace, null if there is no such attribute, and the empty string if the attribute value is empty.

Usage

From source file:de.nava.informa.parsers.Atom_0_3_Parser.java

License:Open Source License

/**
 * Returns the title from title element.
 *//*www  . ja v a  2s  .  c o m*/
static String getTitle(Element elt) {
    if (elt == null) {
        return "";
    }

    String type = getContentType(elt);
    String value;

    if ("application/xhtml+xml".equals(type)) {
        value = elt.getValue();
    } else {
        value = AtomParserUtils.getValue(elt, elt.getAttributeValue("mode"));

        if (!"text/plain".equals(type)) {
            value = ParserUtils.unEscape(value);
        }
    }

    return value;
}

From source file:de.nava.informa.parsers.Atom_1_0_Parser.java

License:Open Source License

/**
 * Returns the content type of element. Default is 'text'.
 */// ww  w .j a v a  2s  .  c om
private static String getContentType(Element elt) {
    String type = elt.getAttributeValue("type");

    return (type == null) ? "text" : type;
}

From source file:de.nava.informa.parsers.Atom_1_0_Parser.java

License:Open Source License

/**
 * @see de.nava.informa.core.ChannelParserIF#parse(de.nava.informa.core.ChannelBuilderIF, org.jdom2.Element)
 */// w w  w .  j av  a  2  s. c  o  m
public ChannelIF parse(ChannelBuilderIF cBuilder, Element channel) throws ParseException {
    if (cBuilder == null) {
        throw new RuntimeException("Without builder no channel can " + "be created.");
    }

    Date dateParsed = new Date();
    Namespace defNS = ParserUtils.getDefaultNS(channel);

    if (defNS == null) {
        defNS = Namespace.NO_NAMESPACE;
        LOGGER.info("No default namespace found.");
    } else if ((defNS.getURI() == null) || !defNS.getURI().equals("http://www.w3.org/2005/Atom")) {
        LOGGER.warn("Namespace is not really supported, still trying assuming Atom 1.0 format");
    }

    LOGGER.debug("start parsing.");

    // --- read in channel information

    // Lower the case of these tags to simulate case-insensitive parsing
    ParserUtils.matchCaseOfChildren(channel, new String[] { "title", "subtitle", "updated", "published",
            "author", "generator", "rights", "link", "entry" });

    // TODO icon and logo: Feed element can have upto 1 logo and icon.
    // TODO id: Feed and all entries have a unique id string. This can
    // be the URL of the website. Supporting this will require API change.
    // TODO: Feed can optionally have category information

    // title element
    ChannelIF chnl = cBuilder.createChannel(channel, channel.getChildTextTrim("title", defNS));

    chnl.setFormat(ChannelFormat.ATOM_1_0);

    // description element
    if (channel.getChild("subtitle") != null) {
        chnl.setDescription(channel.getChildTextTrim("subtitle", defNS));
    }

    // TODO: should we use summary element?

    // lastbuild element : updated ?
    Element updated = channel.getChild("updated", defNS);

    if (updated != null) {
        chnl.setPubDate(ParserUtils.getDate(updated.getTextTrim()));
    }

    // author element
    List authors = channel.getChildren("author", defNS);

    chnl.setCreator(getAuthorString(authors, defNS));

    // TODO we are ignoring contributors information

    // generator element
    Element generator = channel.getChild("generator", defNS);

    if (generator != null) {
        chnl.setGenerator(generator.getTextTrim());
    }

    // TODO generator can have URI and version information

    // copyright element
    Element rights = channel.getChild("rights", defNS);

    if (rights != null) {
        chnl.setCopyright(AtomParserUtils.getValue(rights, getMode(rights)));
    }

    List links = channel.getChildren("link", defNS);
    Iterator i = links.iterator();

    URL linkUrl = null;

    while (i.hasNext()) {
        Element linkElement = (Element) i.next();

        // use first 'alternate' link
        // if rel is not present, use first link without rel
        String rel = linkElement.getAttributeValue("rel");
        String href = linkElement.getAttributeValue("href");

        // TODO we need to handle relative links also
        if ((rel == null) && (href != null) && (linkUrl == null)) {
            linkUrl = ParserUtils.getURL(href);
        } else if ((rel != null) && (href != null) && rel.equals("alternate")) {
            linkUrl = ParserUtils.getURL(href);

            break;
        }
    }

    if (linkUrl != null) {
        chnl.setSite(linkUrl);
    }

    List items = channel.getChildren("entry", defNS);

    i = items.iterator();

    while (i.hasNext()) {
        Element item = (Element) i.next();

        // Lower the case of these tags to simulate case-insensitive parsing
        ParserUtils.matchCaseOfChildren(item,
                new String[] { "title", "link", "content", "summary", "published", "author" });

        // TODO entry, if copied from some other feed, may have source element
        // TODO each entry can have its own rights declaration

        // get title element
        Element elTitle = item.getChild("title", defNS);
        String strTitle = "<No Title>";

        if (elTitle != null) {
            strTitle = AtomParserUtils.getValue(elTitle, getMode(elTitle));
            LOGGER.debug("Parsing title " + elTitle.getTextTrim() + "->" + strTitle);
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Entry element found (" + strTitle + ").");
        }

        // get link element
        String strLink = AtomParserUtils.getItemLink(item, defNS);

        // get description element
        String strDesc = getDescription(item, defNS);

        // generate new news item (link to article)
        ItemIF curItem = cBuilder.createItem(item, chnl, strTitle, strDesc, ParserUtils.getURL(strLink));

        //TODO enclosure data
        curItem.setFound(dateParsed);

        List itemAuthors = item.getChildren("author", defNS);

        curItem.setCreator(getAuthorString(itemAuthors, defNS));

        // get published element
        Element elIssued = item.getChild("published", defNS);

        if (elIssued == null) {
            // published element may not be present (but updated should be)
            Element elUpdated = item.getChild("updated", defNS);

            // TODO there should be some way to determining which one are we
            // returning
            if (elUpdated != null) {
                curItem.setDate(ParserUtils.getDate(elUpdated.getTextTrim()));
            }
        } else {
            curItem.setDate(ParserUtils.getDate(elIssued.getTextTrim()));
        }

        // get list of category elements
        List elCategoryList = item.getChildren("category", defNS);

        // categories present will be stored here
        Collection<CategoryIF> categories = new ArrayList<>();

        // multiple category elements may be present
        for (Object elCategoryItem : elCategoryList) {

            Element elCategory = (Element) elCategoryItem;

            // notice: atom spec. forbids to have category "term" (="subject")
            // set as inner text of category tags, so we have to read it from
            // the "term" attribute

            if (elCategory != null) {
                // TODO: what if we have more than one category element present?
                // subject would be overwritten each loop and therefore represent only
                // the last category read, so does this make any sense?

                // TODO: what about adding functionality for accessing "label" or "scheme" attributes?
                // if set, a label should be displayed instead of the value set in term

                // we keep this line not to break up things which
                // use getSubject() to read an item category
                curItem.setSubject(elCategory.getAttributeValue("term"));

                CategoryIF c = new Category(elCategory.getAttributeValue("term"));

                // add current category to category list
                categories.add(c);
            }
        }

        // assign categories
        curItem.setCategories(categories);
    }

    // set to current date
    chnl.setLastUpdated(dateParsed);

    return chnl;
}

From source file:de.nava.informa.parsers.RSS_0_91_Parser.java

License:Open Source License

/**
 * @see de.nava.informa.core.ChannelParserIF#parse(de.nava.informa.core.ChannelBuilderIF, org.jdom2.Element)
 *///from   w ww .  jav a  2 s  .co  m
public ChannelIF parse(ChannelBuilderIF cBuilder, Element root) throws ParseException {
    if (cBuilder == null) {
        throw new RuntimeException("Without builder no channel can " + "be created.");
    }
    Date dateParsed = new Date();
    logger.debug("start parsing.");

    // Get the channel element (only one occurs)
    ParserUtils.matchCaseOfChildren(root, "channel");
    Element channel = root.getChild("channel");
    if (channel == null) {
        logger.warn("Channel element could not be retrieved from feed.");
        throw new ParseException("No channel element found in feed.");
    }

    // --- read in channel information

    ParserUtils.matchCaseOfChildren(channel,
            new String[] { "title", "description", "link", "language", "item", "image", "textinput",
                    "copyright", "rating", "pubDate", "lastBuildDate", "docs", "managingEditor", "webMaster",
                    "cloud" });

    // 1 title element
    ChannelIF chnl = cBuilder.createChannel(channel, channel.getChildTextTrim("title"));

    chnl.setFormat(ChannelFormat.RSS_0_91);

    // 1 description element
    chnl.setDescription(channel.getChildTextTrim("description"));

    // 1 link element
    chnl.setSite(ParserUtils.getURL(channel.getChildTextTrim("link")));

    // 1 language element
    chnl.setLanguage(channel.getChildTextTrim("language"));

    // 1..n item elements
    List items = channel.getChildren("item");
    Iterator i = items.iterator();
    while (i.hasNext()) {
        Element item = (Element) i.next();

        ParserUtils.matchCaseOfChildren(item,
                new String[] { "title", "link", "description", "source", "enclosure" });

        // get title element
        Element elTitle = item.getChild("title");
        String strTitle = "<No Title>";
        if (elTitle != null) {
            strTitle = elTitle.getTextTrim();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Item element found (" + strTitle + ").");
        }

        // get link element
        Element elLink = item.getChild("link");
        String strLink = "";
        if (elLink != null) {
            strLink = elLink.getTextTrim();
        }

        // get description element
        Element elDesc = item.getChild("description");
        String strDesc = "";
        if (elDesc != null) {
            strDesc = elDesc.getTextTrim();
        }

        // generate new RSS item (link to article)
        ItemIF rssItem = cBuilder.createItem(item, chnl, strTitle, strDesc, ParserUtils.getURL(strLink));
        rssItem.setFound(dateParsed);

        // get source element (an RSS 0.92 element)
        Element source = item.getChild("source");
        if (source != null) {
            String sourceName = source.getTextTrim();
            Attribute sourceAttribute = source.getAttribute("url");
            if (sourceAttribute != null) {
                String location = sourceAttribute.getValue().trim();
                ItemSourceIF itemSource = cBuilder.createItemSource(rssItem, sourceName, location, null);
                rssItem.setSource(itemSource);
            }
        }

        // get enclosure element (an RSS 0.92 element)
        Element enclosure = item.getChild("enclosure");
        if (enclosure != null) {
            URL location = null;
            String type = null;
            int length = -1;
            Attribute urlAttribute = enclosure.getAttribute("url");
            if (urlAttribute != null) {
                location = ParserUtils.getURL(urlAttribute.getValue().trim());
            }
            Attribute typeAttribute = enclosure.getAttribute("type");
            if (typeAttribute != null) {
                type = typeAttribute.getValue().trim();
            }
            Attribute lengthAttribute = enclosure.getAttribute("length");
            if (lengthAttribute != null) {
                try {
                    length = Integer.parseInt(lengthAttribute.getValue().trim());
                } catch (NumberFormatException e) {
                    logger.warn(e);
                }
            }
            ItemEnclosureIF itemEnclosure = cBuilder.createItemEnclosure(rssItem, location, type, length);
            rssItem.setEnclosure(itemEnclosure);
        }
    }

    // 0..1 image element
    Element image = channel.getChild("image");
    if (image != null) {

        ParserUtils.matchCaseOfChildren(image,
                new String[] { "title", "url", "link", "width", "height", "description" });

        ImageIF rssImage = cBuilder.createImage(image.getChildTextTrim("title"),
                ParserUtils.getURL(image.getChildTextTrim("url")),
                ParserUtils.getURL(image.getChildTextTrim("link")));
        Element imgWidth = image.getChild("width");
        if (imgWidth != null) {
            try {
                rssImage.setWidth(Integer.parseInt(imgWidth.getTextTrim()));
            } catch (NumberFormatException e) {
                logger.warn(e);
            }
        }
        Element imgHeight = image.getChild("height");
        if (imgHeight != null) {
            try {
                rssImage.setHeight(Integer.parseInt(imgHeight.getTextTrim()));
            } catch (NumberFormatException e) {
                logger.warn(e);
            }
        }
        Element imgDescr = image.getChild("description");
        if (imgDescr != null) {
            rssImage.setDescription(imgDescr.getTextTrim());
        }
        chnl.setImage(rssImage);
    }

    // 0..1 textinput element
    Element txtinp = channel.getChild("textinput");
    if (txtinp != null) {

        ParserUtils.matchCaseOfChildren(txtinp, new String[] { "title", "description", "name", "link" });

        TextInputIF rssTextInput = cBuilder.createTextInput(txtinp.getChild("title").getTextTrim(),
                txtinp.getChild("description").getTextTrim(), txtinp.getChild("name").getTextTrim(),
                ParserUtils.getURL(txtinp.getChild("link").getTextTrim()));
        chnl.setTextInput(rssTextInput);
    }

    // 0..1 copyright element
    Element copyright = channel.getChild("copyright");
    if (copyright != null) {
        chnl.setCopyright(copyright.getTextTrim());
    }

    // 0..1 rating element
    Element rating = channel.getChild("rating");
    if (rating != null) {
        chnl.setRating(rating.getTextTrim());
    }

    // 0..1 pubDate element
    Element pubDate = channel.getChild("pubDate");
    if (pubDate != null) {
        chnl.setPubDate(ParserUtils.getDate(pubDate.getTextTrim()));
    }

    // 0..1 lastBuildDate element
    Element lastBuildDate = channel.getChild("lastBuildDate");
    if (lastBuildDate != null) {
        chnl.setLastBuildDate(ParserUtils.getDate(lastBuildDate.getTextTrim()));
    }

    // 0..1 docs element
    Element docs = channel.getChild("docs");
    if (docs != null) {
        chnl.setDocs(docs.getTextTrim());
    }

    // 0..1 managingEditor element
    Element managingEditor = channel.getChild("managingEditor");
    if (managingEditor != null) {
        chnl.setCreator(managingEditor.getTextTrim());
    }

    // 0..1 webMaster element
    Element webMaster = channel.getChild("webMaster");
    if (webMaster != null) {
        chnl.setPublisher(webMaster.getTextTrim());
    }

    // 0..1 cloud element
    Element cloud = channel.getChild("cloud");
    if (cloud != null) {
        String _port = cloud.getAttributeValue("port");
        int port = -1;
        if (_port != null) {
            try {
                port = Integer.parseInt(_port);
            } catch (NumberFormatException e) {
                logger.warn(e);
            }
        }
        chnl.setCloud(
                cBuilder.createCloud(cloud.getAttributeValue("domain"), port, cloud.getAttributeValue("path"),
                        cloud.getAttributeValue("registerProcedure"), cloud.getAttributeValue("protocol")));
    }

    chnl.setLastUpdated(dateParsed);
    // 0..1 skipHours element
    // 0..1 skipDays element

    return chnl;
}

From source file:de.nava.informa.utils.AtomParserUtils.java

License:Open Source License

/**
 * Looks for link sub-elements of type "link" and selects the most preferred.
 *
 * @param item  item element.//from ww w .j  ava  2s .com
 * @param defNS default namespace.
 * @return link in string or <code>null</code>.
 */
public static String getItemLink(Element item, Namespace defNS) {
    String currentHref = null;
    int currentOrder = Integer.MAX_VALUE;

    List links = item.getChildren("link", defNS);

    for (int i = 0; (currentOrder != 0) && (i < links.size()); i++) {
        Element link = (Element) links.get(i);

        // get type of the link
        String type = link.getAttributeValue("type");
        String rel = link.getAttributeValue("rel");

        if (type != null) {
            type = type.trim().toLowerCase();
        }

        // if we prefer this type more than the one we already have then
        // replace current href with new one and update preference order
        // value.
        int preferenceOrder = getPreferenceOrderForItemLinkType(type, rel);

        LOGGER.info("Link " + link.getAttributeValue("href") + " with pref "
                + getPreferenceOrderForItemLinkType(type, rel) + " " + type + " " + rel);

        if (preferenceOrder < currentOrder) {
            String href = link.getAttributeValue("href");

            if (href != null) {
                currentHref = href.trim();
                currentOrder = preferenceOrder;
            }
        }
    }

    LOGGER.debug("url read : " + currentHref);

    return currentHref;
}

From source file:de.nava.informa.utils.XmlPathUtils.java

License:Open Source License

/**
 * Get the value corresponding to an <code>Element</code> and an attribute.
 *
 * @param element   the <code>Element</code>.
 *                  <code>null</code> is not acceptable.
 * @param attribute the attribute./*from   w  w  w  .j a va2  s .  com*/
 *                  May contain a namespace specifier e.g. "rdf:resource".
 *                  <code>null</code> is not acceptable.
 * @return the value. The value of the <code>Element's</code> attribute,
 * or <code>null</code> if element is <code>null</code>.
 */
private static String getAttributeValue(Element element, String attribute) {

    if (element == null)
        return null;
    int prefixPos = attribute.indexOf(prefixDelim);

    if ((prefixPos == 0) || (prefixPos >= attribute.length() - 1)) {
        return null;
    } else if (prefixPos == -1) { // no prefix
        return element.getAttributeValue(attribute);
    } else {
        String prefix = attribute.substring(0, prefixPos);
        String attributeName = attribute.substring(prefixPos + 1);
        return element.getAttributeValue(attributeName, getNamespace(element, prefix));
    }
}

From source file:de.openVJJ.basic.Module.java

License:Open Source License

/**
 * @see de.openVJJ.basic.Plugable#setConfig(org.jdom2.Element)
 *//*from www.j  ava  2 s  .  com*/
@Override
public void setConfig(Element element) {
    super.setConfig(element);

    Map<Integer, Plugable> plugabelNrMap = new HashMap<Integer, Plugable>();
    Element plugablesElement = element.getChild(ELEMENT_NAME_PLUGABLES);
    if (plugablesElement != null) {
        for (Element plugableElement : plugablesElement.getChildren(ELEMENT_NAME_PLUGABLE)) {
            String plugableClass = plugableElement.getAttributeValue(ELEMENT_ATTRIBUTE_PLUGABLE_CLASS);
            Plugable plugable = null;
            if (plugableClass != null) {
                try {
                    Class<?> c = Class.forName(plugableClass);
                    Object classInstance = c.newInstance();
                    plugable = (Plugable) classInstance;
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
            if (plugable == null) {
                System.err.println("Was not abel to create instance of Plugabe");
                continue;
            }
            String plugableNr = plugableElement.getAttributeValue(ELEMENT_ATTRIBUTE_PLUGABLE_NR);
            if (plugableNr != null) {
                plugabelNrMap.put(Integer.parseInt(plugableNr), plugable);
            }
            addPlugable(plugable);

            Element plugableElementConfig = plugableElement.getChild(ELEMENT_NAME_PLUGABLE_CONFIG);
            if (plugableElementConfig != null) {
                plugable.setConfig(plugableElementConfig);
            }
        }
    }

    Element connectionsElement = element.getChild(ELEMENT_NAME_CONNECTIONS);
    if (connectionsElement != null) {
        for (Element connectionElement : connectionsElement.getChildren(ELEMENT_NAME_CONNECTION)) {
            String inNRString = connectionElement.getAttributeValue(ELEMENT_ATTRIBUTE_IN_PLUGABLE_NR);
            Plugable inPlugable = null;
            if (inNRString != null) {
                inPlugable = plugabelNrMap.get(Integer.parseInt(inNRString));
            }
            String outNRString = connectionElement.getAttributeValue(ELEMENT_ATTRIBUTE_OUT_PLUGABLE_NR);
            Plugable outPlugable = null;
            if (outNRString != null) {
                outPlugable = plugabelNrMap.get(Integer.parseInt(outNRString));
            }
            String inName = connectionElement.getAttributeValue(ELEMENT_ATTRIBUTE_IN_NAME);
            String outName = connectionElement.getAttributeValue(ELEMENT_ATTRIBUTE_OUT_NAME);

            if (inPlugable == null || outPlugable == null || inName == null || outName == null) {
                System.err.println("Connection not fully defined: " + inNRString + ":" + inName + " -> "
                        + outNRString + ":" + outName);
                continue;
            }

            Connection outCon = outPlugable.getConnection(outName);
            inPlugable.setInput(inName, outCon);
        }
    }
}

From source file:de.openVJJ.basic.Plugable.java

License:Open Source License

/**
 * for restoring from saved configuration
 * @param element XML Element//from  www  .ja va2  s. c  o  m
 */
public void setConfig(Element element) {
    Element guiPositionElement = element.getChild(ELEMENT_NAME_GUI_POSITION);
    if (guiPositionElement != null) {
        Rectangle guiPosition = getGuiPosition();
        String val = guiPositionElement.getAttributeValue("x");
        if (val != null) {
            guiPosition.x = Integer.parseInt(val);
        }
        val = guiPositionElement.getAttributeValue("y");
        if (val != null) {
            guiPosition.y = Integer.parseInt(val);
        }
        val = guiPositionElement.getAttributeValue("height");
        if (val != null) {
            guiPosition.height = Integer.parseInt(val);
        }
        val = guiPositionElement.getAttributeValue("width");
        if (val != null) {
            guiPosition.width = Integer.parseInt(val);
        }
    }
}

From source file:de.openVJJ.plugins.LineFromSorbel2DIntArray.java

License:Open Source License

/**
 * for restoring from saved configuration
 * @param element XML Element//from  w w  w. jav a  2 s. c  om
 */
public void setConfig(Element element) {
    Element myConfigElement = element.getChild(ELEMENT_NAME_LineFromSorbel2DIntArray_CONFIG);
    if (myConfigElement != null) {
        String val = myConfigElement.getAttributeValue("directionx");
        if (val != null) {
            xDirection = Boolean.parseBoolean(val);
        }
        val = myConfigElement.getAttributeValue("lineLimit");
        if (val != null) {
            lineLimit = Integer.parseInt(val);
        }
        val = myConfigElement.getAttributeValue("histery");
        if (val != null) {
            histery = Integer.parseInt(val);
        }
        val = myConfigElement.getAttributeValue("minLength");
        if (val != null) {
            minLength = Integer.parseInt(val);
        }
    }
    super.setConfig(element);
}

From source file:de.openVJJ.plugins.PixelLineToVectors.java

License:Open Source License

/**
 * for restoring from saved configuration
 * @param element XML Element//from w ww . java  2 s .co  m
 */
public void setConfig(Element element) {
    Element myConfigElement = element.getChild(ELEMENT_NAME_PixelLineToVectors_CONFIG);
    if (myConfigElement != null) {
        String val = myConfigElement.getAttributeValue("horizontal");
        if (val != null) {
            horizontal = Boolean.parseBoolean(val);
        }
    }
    super.setConfig(element);
}