Example usage for org.jdom2 Namespace getURI

List of usage examples for org.jdom2 Namespace getURI

Introduction

In this page you can find the example usage for org.jdom2 Namespace getURI.

Prototype

public String getURI() 

Source Link

Document

This returns the namespace URI for this Namespace.

Usage

From source file:ca.nrc.cadc.caom2.xml.ObservationReader.java

License:Open Source License

/**
 * Construct an Observation from a Reader.
 *
 * @param reader/* w w  w .  j a va 2 s.  c om*/
 *            A Reader.
 * @return An Observation.
 * @throws ObservationParsingException
 *             if there is an error parsing the XML.
 */
public Observation read(Reader reader) throws ObservationParsingException, IOException {
    if (reader == null) {
        throw new IllegalArgumentException("reader must not be null");
    }

    init();

    Document document;
    try {
        document = XmlUtil.buildDocument(reader, schemaMap);
    } catch (JDOMException jde) {
        String error = "XML failed schema validation: " + jde.getMessage();
        throw new ObservationParsingException(error, jde);
    }

    // Root element and namespace of the Document
    Element root = document.getRootElement();
    Namespace namespace = root.getNamespace();
    log.debug("obs namespace uri: " + namespace.getURI());
    log.debug("obs namespace prefix: " + namespace.getPrefix());

    ReadContext rc = new ReadContext();
    if (XmlConstants.CAOM2_0_NAMESPACE.equals(namespace.getURI())) {
        rc.docVersion = 20;
    } else if (XmlConstants.CAOM2_1_NAMESPACE.equals(namespace.getURI())) {
        rc.docVersion = 21;
    } else if (XmlConstants.CAOM2_2_NAMESPACE.equals(namespace.getURI())) {
        rc.docVersion = 22;
    }

    // Simple or Composite
    Attribute type = root.getAttribute("type", xsiNamespace);
    String tval = type.getValue();

    String collection = getChildText("collection", root, namespace, false);
    String observationID = getChildText("observationID", root, namespace, false);

    // Algorithm.
    Algorithm algorithm = getAlgorithm(root, namespace, rc);

    // Create the Observation.
    Observation obs;
    String simple = namespace.getPrefix() + ":" + SimpleObservation.class.getSimpleName();
    String comp = namespace.getPrefix() + ":" + CompositeObservation.class.getSimpleName();
    if (simple.equals(tval)) {
        obs = new SimpleObservation(collection, observationID);
        obs.setAlgorithm(algorithm);
    } else if (comp.equals(tval)) {
        obs = new CompositeObservation(collection, observationID, algorithm);
    } else {
        throw new ObservationParsingException("unexpected observation type: " + tval);
    }

    // Observation children.
    String intent = getChildText("intent", root, namespace, false);
    if (intent != null) {
        obs.intent = ObservationIntentType.toValue(intent);
    }
    obs.type = getChildText("type", root, namespace, false);

    obs.metaRelease = getChildTextAsDate("metaRelease", root, namespace, false, rc.dateFormat);
    obs.sequenceNumber = getChildTextAsInteger("sequenceNumber", root, namespace, false);
    obs.proposal = getProposal(root, namespace, rc);
    obs.target = getTarget(root, namespace, rc);
    obs.targetPosition = getTargetPosition(root, namespace, rc);
    obs.requirements = getRequirements(root, namespace, rc);
    obs.telescope = getTelescope(root, namespace, rc);
    obs.instrument = getInstrument(root, namespace, rc);
    obs.environment = getEnvironment(root, namespace, rc);

    addPlanes(obs.getPlanes(), root, namespace, rc);

    if (obs instanceof CompositeObservation) {
        addMembers(((CompositeObservation) obs).getMembers(), root, namespace, rc);
    }

    assignEntityAttributes(root, obs, rc);

    return obs;
}

From source file:ca.nrc.cadc.vos.NodeReader.java

License:Open Source License

/**
 *  Construct a Node from a Reader./* ww w.  j av  a 2  s. c o  m*/
 *
 * @param reader Reader.
 * @return Node Node.
 * @throws NodeParsingException if there is an error parsing the XML.
 */
public Node read(Reader reader) throws NodeParsingException, IOException {
    if (reader == null)
        throw new IllegalArgumentException("reader must not be null");

    // Create a JDOM Document from the XML
    Document document;
    try {
        // TODO: investigate creating a SAXBuilder once and re-using it
        // as long as we can detect concurrent access (a la java collections)
        document = XmlUtil.validateXml(reader, schemaMap);
    } catch (JDOMException jde) {
        String error = "XML failed schema validation: " + jde.getMessage();
        throw new NodeParsingException(error, jde);
    }

    // Root element and namespace of the Document
    Element root = document.getRootElement();
    Namespace namespace = root.getNamespace();
    log.debug("node namespace uri: " + namespace.getURI());
    log.debug("node namespace prefix: " + namespace.getPrefix());

    /* Node base elements */
    // uri attribute of the node element
    String uri = root.getAttributeValue("uri");
    if (uri == null) {
        String error = "uri attribute not found in root element";
        throw new NodeParsingException(error);
    }
    log.debug("node uri: " + uri);

    // Get the xsi:type attribute which defines the Node class
    String xsiType = root.getAttributeValue("type", xsiNamespace);
    if (xsiType == null) {
        String error = "xsi:type attribute not found in node element " + uri;
        throw new NodeParsingException(error);
    }

    // Split the type attribute into namespace and Node type
    String[] types = xsiType.split(":");
    String type = types[1];
    log.debug("node type: " + type);

    try {
        if (type.equals(ContainerNode.class.getSimpleName()))
            return buildContainerNode(root, namespace, uri);
        else if (type.equals(DataNode.class.getSimpleName()))
            return buildDataNode(root, namespace, uri);
        else if (type.equals(UnstructuredDataNode.class.getSimpleName()))
            return buildUnstructuredDataNode(root, namespace, uri);
        else if (type.equals(LinkNode.class.getSimpleName()))
            return buildLinkNode(root, namespace, uri);
        else if (type.equals(StructuredDataNode.class.getSimpleName()))
            return buildStructuredDataNode(root, namespace, uri);
        else
            throw new NodeParsingException("unsupported node type " + type);
    } catch (URISyntaxException e) {
        throw new NodeParsingException("invalid uri in xml: " + e.getMessage());
    }
}

From source file:ca.nrc.cadc.xml.JsonOutputter.java

License:Open Source License

private boolean writeSchemaAttributes(Element e, PrintWriter w, int i) throws IOException {
    boolean ret = false;

    // getNamespacesIntroduced: only write for newly introduced namespaces;
    // this correctly handles the current context of namespaces from root to 
    // current element
    for (Namespace ans : e.getNamespacesIntroduced()) {
        String uri = ans.getURI();
        String pre = ans.getPrefix();
        if (ret) {
            w.print(",");
        }/*from   w w w .j a  v a  2  s  . c om*/
        ret = true;
        indent(w, i);
        writeSchema(uri, pre, w);
    }
    return ret;
}

From source file:com.cybernostics.jsp2thymeleaf.api.elements.ActiveNamespaces.java

public static void add(Namespace ns) {
    namespaces.putIfAbsent(ns.getURI(), ns);
}

From source file:com.init.octo.schema.XSDCache.java

License:Open Source License

private void cacheNamespace(Namespace namespace) {

    String prefix = namespace.getPrefix();
    String uri = namespace.getURI();

    namespaceCache[namespaceIdx].put(prefix, uri);

}

From source file:com.rometools.rome.io.impl.RSS091UserlandGenerator.java

License:Open Source License

@Override
protected void populateItem(final Item item, final Element eItem, final int index) {

    super.populateItem(item, eItem, index);

    final Description description = item.getDescription();
    if (description != null) {
        eItem.addContent(generateSimpleElement("description", description.getValue()));
    }//from www . j av  a 2s.  c om

    final Namespace contentNamespace = getContentNamespace();
    final Content content = item.getContent();
    if (item.getModule(contentNamespace.getURI()) == null && content != null) {
        final Element elem = new Element("encoded", contentNamespace);
        elem.addContent(content.getValue());
        eItem.addContent(elem);
    }

}

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. java  2  s . co  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.FeedParser.java

License:Open Source License

private static synchronized ChannelIF parse(ChannelBuilderIF cBuilder, Document doc) throws ParseException {

    if (cBuilder == null) {
        throw new RuntimeException("Without builder no channel can " + "be created.");
    }/*from   w  w w  .  ja  va 2 s.c o m*/
    LOGGER.debug("start parsing.");
    // Get the root element (must be rss)
    Element root = doc.getRootElement();
    String rootElement = root.getName().toLowerCase();
    // Decide which parser to use
    if (rootElement.startsWith("rss")) {
        String rssVersion = root.getAttribute("version").getValue();
        if (rssVersion.contains("0.91")) {
            LOGGER.info("Channel uses RSS root element (Version 0.91).");
            return RSS_0_91_Parser.getInstance().parse(cBuilder, root);
        } else if (rssVersion.contains("0.92")) {
            LOGGER.info("Channel uses RSS root element (Version 0.92).");
            // logger.warn("RSS 0.92 not fully supported yet, fall back to 0.91.");
            // TODO: support RSS 0.92 when aware of all subtle differences.
            return RSS_0_91_Parser.getInstance().parse(cBuilder, root);
        } else if (rootElement.contains("0.93")) {
            LOGGER.info("Channel uses RSS root element (Version 0.93).");
            LOGGER.warn("RSS 0.93 not fully supported yet, fall back to 0.91.");
            // TODO: support RSS 0.93 when aware of all subtle differences.
        } else if (rootElement.contains("0.94")) {
            LOGGER.info("Channel uses RSS root element (Version 0.94).");
            LOGGER.warn("RSS 0.94 not fully supported yet, will use RSS 2.0");
            // TODO: support RSS 0.94 when aware of all subtle differences.
            return RSS_2_0_Parser.getInstance().parse(cBuilder, root);
        } else if (rssVersion.contains("2.0") || rssVersion.equals("2")) {
            LOGGER.info("Channel uses RSS root element (Version 2.0).");
            return RSS_2_0_Parser.getInstance().parse(cBuilder, root);
        } else {
            throw new UnsupportedFormatException("Unsupported RSS version [" + rssVersion + "].");
        }
    } else if (rootElement.contains("rdf")) {
        return RSS_1_0_Parser.getInstance().parse(cBuilder, root);
    } else if (rootElement.contains("feed")) {
        Attribute versionAttr = root.getAttribute("version");
        Namespace namespace = ParserUtils.getDefaultNS(root);
        if (versionAttr != null) {
            String feedVersion = versionAttr.getValue();
            if (feedVersion.contains("0.1") || feedVersion.contains("0.2")) {
                LOGGER.info("Channel uses feed root element (Version " + feedVersion + ").");
                LOGGER.warn("This atom version is not really supported yet, assume Atom 0.3 format");
                return Atom_0_3_Parser.getInstance().parse(cBuilder, root);
            } else if (feedVersion.contains("0.3")) {
                LOGGER.info("Channel uses feed root element (Version 0.3).");
                return Atom_0_3_Parser.getInstance().parse(cBuilder, root);
            }
        } else if (namespace != null && namespace.getURI() != null) {
            if (!namespace.getURI().equals("http://www.w3.org/2005/Atom")) {
                LOGGER.warn("Channel uses unknown namespace in feed root element, assume Atom 1.0 format.");
            } else {
                LOGGER.info("Channel uses feed root element (Atom 1.0 format).");
            }
            return Atom_1_0_Parser.getInstance().parse(cBuilder, root);
        }
    }

    // did not match anything
    throw new UnsupportedFormatException("Unsupported root element [" + rootElement + "].");
}

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

License:Open Source License

public ChannelIF parse(ChannelBuilderIF cBuilder, Element root) throws ParseException {
    if (cBuilder == null) {
        throw new RuntimeException("Without builder no channel can " + "be created.");
    }//  w  w w  .  j av  a2  s.  c  o m
    Date dateParsed = new Date();
    Namespace defNS = ParserUtils.getDefaultNS(root);
    if (defNS == null) {
        defNS = Namespace.NO_NAMESPACE;
        logger.info("No default namespace found.");
    }

    // RSS 1.0 Dublin Core Module namespace
    Namespace dcNS = ParserUtils.getNamespace(root, "dc");
    // fall back to default name space (for retrieving descriptions)
    if (dcNS == null) {
        dcNS = defNS;
    }

    // RSS 1.0 Syndication Module namespace
    Namespace syNS = ParserUtils.getNamespace(root, "sy");

    // RSS 1.0 Aggregation Module namespace
    Namespace agNS = ParserUtils.getNamespace(root, "ag");

    // RSS 1.0 Administration Module namespace
    Namespace adminNS = ParserUtils.getNamespace(root, "admin");

    // RSS 1.0 DCTerms Module namespace
    Namespace dctermsNS = ParserUtils.getNamespace(root, "dcterms");

    // RSS 1.0 Annotation Module namespace
    Namespace annotateNS = ParserUtils.getNamespace(root, "annotate");

    // RSS091 Module namespace
    Namespace rss091NS = ParserUtils.getNamespace(root, "rss091");

    // Content namespace
    Namespace contentNS = ParserUtils.getNamespace(root, "content");

    ParserUtils.matchCaseOfChildren(root, new String[] { "channel", "item", "image", "textinput" });

    // Get the channel element (only one occurs)
    Element channel = root.getChild("channel", defNS);
    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", "creator", "managingEditor", "publisher",
                    "errorReportsTo", "webMaster", "language", "rights", "copyright", "rating", "date",
                    "issued", "pubdate", "lastBuildDate", "modified", "generatorAgent", "updatePeriod",
                    "updateFrequency", "updateBase" });

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

    // set channel format
    chnl.setFormat(ChannelFormat.RSS_1_0);

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

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

    // creator element
    Element creator = channel.getChild("creator", dcNS);
    if (creator == null) {
        creator = channel.getChild("managingEditor", rss091NS);
    }
    if (creator != null) {
        chnl.setCreator(creator.getTextTrim());
    }

    // publisher element
    String publisher = channel.getChildTextTrim("publisher", dcNS);
    if (publisher == null) {
        Element elErrorReportsTo = channel.getChild("errorReportsTo", adminNS);
        if (elErrorReportsTo != null) {
            publisher = elErrorReportsTo.getAttributeValue("resource",
                    ParserUtils.getNamespace(elErrorReportsTo, "rdf"));
        }
    }
    if (publisher == null) {
        publisher = channel.getChildTextTrim("webMaster", rss091NS);
    }
    chnl.setPublisher(publisher);

    // language element
    Element language = channel.getChild("language", dcNS);
    if (language == null) {
        language = channel.getChild("language", rss091NS);
    }
    if (language != null) {
        chnl.setLanguage(language.getTextTrim());
    }

    // rights element
    Element copyright = channel.getChild("rights", dcNS);
    if (copyright == null) {
        copyright = channel.getChild("copyright", rss091NS);
    }
    if (copyright != null) {
        chnl.setCopyright(copyright.getTextTrim());
    }

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

    // 0..1 Docs element
    // use namespace URI
    chnl.setDocs(defNS.getURI());

    // 0..1 pubDate element
    Element pubDate = channel.getChild("date", dcNS);
    if (pubDate == null) {
        pubDate = channel.getChild("issued", dctermsNS);
    }
    if (pubDate == null) {
        pubDate = channel.getChild("pubdate", rss091NS);
    }
    if (pubDate != null) {
        chnl.setPubDate(ParserUtils.getDate(pubDate.getTextTrim()));
    }

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

    // RSS 1.0 Administration Module support

    // 0..1 generator element
    Element elGenerator = channel.getChild("generatorAgent", adminNS);
    if (elGenerator != null) {
        Attribute generator = elGenerator.getAttribute("resource",
                ParserUtils.getNamespace(elGenerator, "rdf"));
        if (generator != null) {
            chnl.setGenerator(generator.getValue());
        }
    }

    // RSS 1.0 Syndication Module support

    // 0..1 update period element
    Element updatePeriod = channel.getChild("updatePeriod", syNS);
    if (updatePeriod != null) {
        try {
            ChannelUpdatePeriod channelUpdatePeriod = ChannelUpdatePeriod
                    .valueFromText(updatePeriod.getTextTrim());
            chnl.setUpdatePeriod(channelUpdatePeriod);
        } catch (IllegalArgumentException ex) {
            logger.warn(updatePeriod.getTextTrim(), ex);
        }
    }

    // 0..1 update frequency element
    Element updateFrequency = channel.getChild("updateFrequency", syNS);
    if (updateFrequency != null) {
        chnl.setUpdateFrequency((new Integer(updateFrequency.getTextTrim())).intValue());
    }

    // 0..1 update base element
    Element updateBase = channel.getChild("updateBase", syNS);
    if (updateBase != null) {
        chnl.setUpdateBase(ParserUtils.getDate(updateBase.getTextTrim()));
    }

    if ((updatePeriod != null) && updateFrequency != null) {
        int ttl = getTTL(chnl.getUpdatePeriod(), chnl.getUpdateFrequency());
        chnl.setTtl(ttl);
    }

    // item elements
    List items = root.getChildren("item", defNS);
    Iterator i = items.iterator();
    while (i.hasNext()) {
        Element item = (Element) i.next();

        ParserUtils.matchCaseOfChildren(item, new String[] { "title", "link", "encoded", "description",
                "creator", "subject", "date", "sourceURL", "source", "timestamp", "reference" });

        // get title element
        Element elTitle = item.getChild("title", defNS);
        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", defNS);
        String strLink = "";
        if (elLink != null) {
            strLink = elLink.getTextTrim();
        }

        // get description element
        Element elDesc = item.getChild("encoded", contentNS);
        if (elDesc == null) {
            elDesc = item.getChild("description", defNS);
        }
        if (elDesc == null) {
            elDesc = item.getChild("description", dcNS);
        }
        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 creator element
        Element elCreator = item.getChild("creator", dcNS);
        if (elCreator != null) {
            rssItem.setCreator(elCreator.getTextTrim());
        }

        // get subject element
        Element elSubject = item.getChild("subject", dcNS);
        if (elSubject != null) {
            // TODO: Mulitple subject elements not handled currently
            rssItem.setSubject(elSubject.getTextTrim());
        }

        // get date element
        Element elDate = item.getChild("date", dcNS);
        if (elDate != null) {
            rssItem.setDate(ParserUtils.getDate(elDate.getTextTrim()));
        }

        // get source element - default to Aggregation module, then try Dublin Core
        String sourceName = null;
        String sourceLocation = null;
        Date sourceTimestamp = null;

        Element elSourceURL = item.getChild("sourceURL", agNS);
        if (elSourceURL == null) { //  No Aggregation module - try Dublin Core
            elSourceURL = item.getChild("source", dcNS);
            if (elSourceURL != null) {
                sourceLocation = elSourceURL.getTextTrim();
                sourceName = "Source";
            }
        } else { // Aggregation module
            sourceLocation = elSourceURL.getTextTrim();
            Element elSourceName = item.getChild("source", agNS);
            if (elSourceName != null) {
                sourceName = elSourceName.getTextTrim();
            }
            Element elSourceTimestamp = item.getChild("timestamp", agNS);
            if (elSourceTimestamp != null) {
                sourceTimestamp = ParserUtils.getDate(elSourceTimestamp.getTextTrim());
            }
        }

        if (sourceLocation != null) {
            ItemSourceIF itemSource = cBuilder.createItemSource(rssItem, sourceName, sourceLocation,
                    sourceTimestamp);
            rssItem.setSource(itemSource);
        }

        // comments element - use Annotation module
        Element elReference = item.getChild("reference", annotateNS);
        if (elReference != null) {
            Attribute resource = elReference.getAttribute("resource",
                    ParserUtils.getNamespace(elReference, "rdf"));
            if (resource != null) {
                URL resourceURL = ParserUtils.getURL(resource.getValue());
                if (resourceURL != null) {
                    rssItem.setComments(resourceURL);
                }
            }
        }

    }

    // image element
    Element image = root.getChild("image", defNS);
    if (image != null) {

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

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

    // textinput element
    Element txtinp = root.getChild("textinput", defNS);
    if (txtinp != null) {

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

        String tiTitle = null;
        if (txtinp.getChild("title", defNS) != null) {
            tiTitle = txtinp.getChild("title", defNS).getTextTrim();
        }
        String tiDescr = null;
        if (txtinp.getChild("description", defNS) != null) {
            tiDescr = txtinp.getChild("description", defNS).getTextTrim();
        }
        String tiName = null;
        if (txtinp.getChild("name", defNS) != null) {
            tiName = txtinp.getChild("name", defNS).getTextTrim();
        }
        URL tiLink = null;
        if (txtinp.getChild("link", defNS) != null) {
            tiLink = ParserUtils.getURL(txtinp.getChild("link", defNS).getTextTrim());
        }
        TextInputIF rssTextInput = cBuilder.createTextInput(tiTitle, tiDescr, tiName, tiLink);
        chnl.setTextInput(rssTextInput);
    }

    chnl.setLastUpdated(dateParsed);

    return chnl;
}

From source file:edu.pitt.apollo.runmanagerservice.methods.stage.StageExperimentMethod.java

License:Apache License

@Override
public void runApolloService() {

    XMLSerializer serializer = new XMLSerializer();
    XMLDeserializer deserializer = new XMLDeserializer();

    InfectiousDiseaseScenario baseScenario = idtes.getInfectiousDiseaseScenarioWithoutIntervention();
    // clear all set control strategies in base
    baseScenario.getInfectiousDiseaseControlStrategies().clear();

    List<SoftwareIdentification> modelIds = idtes.getInfectiousDiseaseTransmissionModelIds();
    try {/*from   w  w  w  .j  ava2s. c  om*/
        DataServiceAccessor dataServiceAccessor = new DataServiceAccessor();

        for (SoftwareIdentification modelId : modelIds) {

            // create a base scenario copy
            String baseXml = serializer.serializeObject(baseScenario);
            InfectiousDiseaseScenario baseScenarioCopy = deserializer.getObjectFromMessage(baseXml,
                    InfectiousDiseaseScenario.class);
            for (InfectiousDiseaseControlStrategy strategy : idtes.getInfectiousDiseaseControlStrategies()) {

                for (InfectiousDiseaseControlMeasure controlMeasure : strategy.getControlMeasures()) {
                    baseScenarioCopy.getInfectiousDiseaseControlStrategies().add(controlMeasure);
                }
            }

            List<SensitivityAnalysisSpecification> sensitivityAnalyses = idtes.getSensitivityAnalyses();
            for (SensitivityAnalysisSpecification sensitivityAnalysis : sensitivityAnalyses) {
                if (sensitivityAnalysis instanceof OneWaySensitivityAnalysisOfContinousVariableSpecification) {
                    OneWaySensitivityAnalysisOfContinousVariableSpecification owsaocv = (OneWaySensitivityAnalysisOfContinousVariableSpecification) sensitivityAnalysis;
                    double min = owsaocv.getMinimumValue();
                    double max = owsaocv.getMaximumValue();
                    double increment = (max - min) / owsaocv.getNumberOfDiscretizations().intValueExact();

                    String scenarioXML = serializer.serializeObject(baseScenarioCopy);

                    double val = min;
                    while (val <= max) {

                        String param = owsaocv.getUniqueApolloLabelOfParameter();

                        Document jdomDocument;
                        SAXBuilder jdomBuilder = new SAXBuilder();
                        try {
                            jdomDocument = jdomBuilder.build(
                                    new ByteArrayInputStream(scenarioXML.getBytes(StandardCharsets.UTF_8)));
                        } catch (JDOMException | IOException ex) {
                            ErrorUtils.reportError(runId,
                                    "Error inserting experiment run. Error was " + ex.getMessage(),
                                    authentication);
                            return;
                        }

                        Element e = jdomDocument.getRootElement();
                        List<Namespace> namespaces = e.getNamespacesInScope();

                        for (Namespace namespace : namespaces) {
                            if (namespace.getURI().contains("http://types.apollo.pitt.edu")) {
                                param = param.replaceAll("/", "/" + namespace.getPrefix() + ":");
                                param = param.replaceAll("\\[", "\\[" + namespace.getPrefix() + ":");
                                break;
                            }
                        }

                        XPathFactory xpf = XPathFactory.instance();
                        XPathExpression<Element> expr;
                        expr = xpf.compile(param, Filters.element(), null, namespaces);
                        List<Element> elements = expr.evaluate(jdomDocument);

                        for (Element element : elements) {
                            element.setText(Double.toString(val));
                        }

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        XMLOutputter xmlOutputter = new XMLOutputter();
                        xmlOutputter.output(jdomDocument, baos);

                        InfectiousDiseaseScenario newScenario = deserializer.getObjectFromMessage(
                                new String(baos.toByteArray()), InfectiousDiseaseScenario.class);

                        // new scenario is ready to be staged
                        RunSimulationMessage runSimulationMessage = new RunSimulationMessage();
                        runSimulationMessage.setAuthentication(authentication);
                        runSimulationMessage
                                .setSimulatorTimeSpecification(message.getSimulatorTimeSpecification());
                        runSimulationMessage.setSoftwareIdentification(modelId);
                        runSimulationMessage.setInfectiousDiseaseScenario(newScenario);

                        StageMethod stageMethod = new StageMethod(runSimulationMessage, runId);
                        InsertRunResult result = stageMethod.stage();
                        BigInteger newRunId = result.getRunId();

                        MethodCallStatus status = dataServiceAccessor.getRunStatus(newRunId, authentication);
                        if (status.getStatus().equals(MethodCallStatusEnum.FAILED)) {
                            ErrorUtils.reportError(runId,
                                    "Error inserting run in experiment with run ID " + runId + ""
                                            + ". Error was for inserting ID " + newRunId + " with message "
                                            + status.getMessage(),
                                    authentication);
                            return;
                        }

                        val += increment;
                    }
                }
            }
        }

        dataServiceAccessor.updateStatusOfRun(runId, MethodCallStatusEnum.TRANSLATION_COMPLETED,
                "All runs for this experiment have been translated", authentication);
    } catch (DeserializationException | IOException | SerializationException | RunManagementException ex) {
        ErrorUtils.reportError(runId, "Error inserting experiment run. Error was " + ex.getMessage(),
                authentication);
        return;
    }
}