Example usage for org.w3c.dom Node hasAttributes

List of usage examples for org.w3c.dom Node hasAttributes

Introduction

In this page you can find the example usage for org.w3c.dom Node hasAttributes.

Prototype

public boolean hasAttributes();

Source Link

Document

Returns whether this node (if it is an element) has any attributes.

Usage

From source file:org.kepler.objectmanager.cache.ActorCacheObject.java

/**
 * deserialize this class/*from   www .  j  a  v  a2s. c o m*/
 * 
 *@param in
 *            Description of the Parameter
 *@exception IOException
 *                Description of the Exception
 *@exception ClassNotFoundException
 *                Description of the Exception
 */
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    if (isDebugging)
        log.debug("readExternal(" + in.getClass().getName() + ")");

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] b = new byte[1024];
    int numread = in.read(b, 0, 1024);
    while (numread != -1) {
        bos.write(b, 0, numread);
        numread = in.read(b, 0, 1024);
    }
    bos.flush();
    _actorString = bos.toString();
    try {
        StringReader strR = new StringReader(_actorString);
        InputSource xmlIn = new InputSource(strR);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                if (MOML_PUBLIC_ID_1.equals(publicId)) {
                    return new InputSource(MoMLParser.class.getResourceAsStream("MoML_1.dtd"));
                } else {
                    return null;
                }
            }
        });
        Document doc = builder.parse(xmlIn);
        Node rootNode = doc.getDocumentElement();
        _rootname = rootNode.getNodeName();
        NamedNodeMap nnm = rootNode.getAttributes();
        Node namenode = nnm.getNamedItem("name");
        String nameStr = namenode.getNodeValue();
        this._name = nameStr;
        NodeList probNodes = rootNode.getChildNodes();
        for (int i = 0; i < probNodes.getLength(); i++) {
            Node child = probNodes.item(i);
            if (child.hasAttributes()) {
                NamedNodeMap childAttrs = child.getAttributes();
                Node idNode = childAttrs.getNamedItem("name");
                if (idNode != null) {
                    String nameval = idNode.getNodeValue();
                    if (nameval.equals(NamedObjId.NAME)) {
                        Node idNode1 = childAttrs.getNamedItem("value");
                        String idval = idNode1.getNodeValue();
                        this._lsid = new KeplerLSID(idval);
                    }
                    if (nameval.equals("class")) {
                        Node idNode3 = childAttrs.getNamedItem("value");
                        String classname = idNode3.getNodeValue();
                        this._className = classname;
                    }
                    if (nameval.startsWith("semanticType")) {
                        Node idNode2 = childAttrs.getNamedItem("value");
                        String semtype = idNode2.getNodeValue();
                        _semanticTypes.add(semtype);
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException("Error in ActorCacheObject(ReadExternal): " + e.getMessage());
    }
}

From source file:org.kmallan.azureus.rssfeed.Scheduler.java

public synchronized void runFeed(final UrlBean urlBean) {
    String url = urlBean.getLocation();
    String title, link, description;

    ListGroup listBeans = urlBean.getGroup();

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setIgnoringComments(true);
    docFactory.setIgnoringElementContentWhitespace(true);
    DocumentBuilder docBuild;//from  w  w w . j  a v  a2s. c  o m
    Document feed;

    File xmlTmp = null;
    try {
        docBuild = docFactory.newDocumentBuilder();
        Downloader downloader = new Downloader();
        downloader.addListener(new DownloaderListener() {
            public boolean completed = false, error = false;

            public void downloaderUpdate(int state, int percent, int amount, String err) {
                if (completed || error)
                    return;
                String status = new String("Pending");
                switch (state) {
                case Downloader.DOWNLOADER_NON_INIT:
                    status = "Pending";
                    break;
                case Downloader.DOWNLOADER_INIT:
                    status = "Connecting";
                    break;
                case Downloader.DOWNLOADER_START:
                    status = "Download Starting";
                    break;
                case Downloader.DOWNLOADER_DOWNLOADING:
                    status = "Downloading";
                    break;
                case Downloader.DOWNLOADER_FINISHED:
                    status = "Download Finished";
                    completed = true;
                    break;
                case Downloader.DOWNLOADER_NOTMODIFIED:
                    status = "Not modified";
                    completed = true;
                    break;
                case Downloader.DOWNLOADER_ERROR:
                    status = "Error";
                    error = true;
                    break;
                }
                urlBean.setStatus(status);
                if (percent > 0)
                    urlBean.setPercent(percent);
                if (amount > 0)
                    urlBean.setAmount(amount);
                if (!err.equalsIgnoreCase(""))
                    urlBean.setError(err);

                if (view.isOpen() && view.display != null && !view.display.isDisposed())
                    view.display.asyncExec(new Runnable() {
                        public void run() {
                            if (view.listTable == null || view.listTable.isDisposed())
                                return;
                            ListTreeItem listGroup = view.treeViewManager.getItem(urlBean);
                            listGroup.setText(1, urlBean.getStatus() + " " + (!urlBean.getError()
                                    .equalsIgnoreCase("") && urlBean.getStatus() == "Error"
                                            ? "- " + urlBean.getError()
                                            : (urlBean.getStatus() == "Downloading" ? (urlBean.getPercent() > 0
                                                    ? Integer.toString(urlBean.getPercent()) + "%"
                                                    : (urlBean.getAmount() > 0 ? Double.toString(Math.floor(
                                                            new Integer(urlBean.getAmount()).doubleValue()
                                                                    / (double) 1024 * (double) 100)
                                                            / (double) 100) + "KB" : ""))
                                                    : "")));
                            if (!urlBean.getError().equalsIgnoreCase(""))
                                listGroup.setForeground(new Color(view.display, 255, 0, 0));
                            else
                                listGroup.resetForeground();
                        }
                    });
            }
        });
        downloader.init(url, "text/xml, text/html, text/plain, application/x-httpd-php", null,
                (urlBean.getUseCookie() ? urlBean.getCookie() : null), urlBean.getLastModifed(),
                urlBean.getLastEtag());

        if (downloader.getState() == Downloader.DOWNLOADER_ERROR)
            return;

        if (downloader.getState() == Downloader.DOWNLOADER_NOTMODIFIED) {
            // no change, add the old items again
            for (Iterator iter = listBeans.getPreviousItems().iterator(); iter.hasNext();) {
                addTableElement(urlBean, listBeans, (ListBean) iter.next());
            }
            addBacklogElements(urlBean);
            downloader.notModified();
            // use the last seen TTL value if available
            if (urlBean.getObeyTTL() && listBeans.getPreviousDelay() > 0)
                listBeans.setDelay(listBeans.getPreviousDelay());
            return;
        }

        Plugin.debugOut(
                urlBean.getName() + " Last-Modified: " + downloader.lastModified + " ETag: " + downloader.etag);

        urlBean.setLastModifed(downloader.lastModified);
        urlBean.setLastEtag(downloader.etag);

        xmlTmp = new File(Plugin.getPluginDirectoryName(), "tmp-" + urlBean.getID() + ".xml");
        xmlTmp.createNewFile();
        FileOutputStream fileout = new FileOutputStream(xmlTmp, false);

        byte[] buf = new byte[2048];
        int read = 0;
        do {
            if (downloader.getState() == Downloader.DOWNLOADER_CANCELED)
                break;
            read = downloader.read(buf);
            if (read > 0) {
                System.err.print(".");
                fileout.write(buf, 0, read);
            } else if (read == 0) {
                System.err.print("?");
                try {
                    long numMillisecondsToSleep = 100;
                    Thread.sleep(numMillisecondsToSleep);
                } catch (InterruptedException e) {
                }
            }
        } while (read >= 0);

        fileout.flush();
        fileout.close();

        docBuild.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                // System.out.println( publicId + ", " + systemId );

                // handle bad DTD external refs

                if (Plugin.getProxyOption() == Plugin.PROXY_TRY_PLUGIN) {

                    return new InputSource(
                            new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
                }

                try {
                    URL url = new URL(systemId);

                    String host = url.getHost();

                    InetAddress.getByName(host);

                    // try connecting too as connection-refused will also bork XML parsing

                    InputStream is = null;

                    try {
                        URLConnection con = url.openConnection();

                        con.setConnectTimeout(15 * 1000);
                        con.setReadTimeout(15 * 1000);

                        is = con.getInputStream();

                        byte[] buffer = new byte[32];

                        int pos = 0;

                        while (pos < buffer.length) {

                            int len = is.read(buffer, pos, buffer.length - pos);

                            if (len <= 0) {

                                break;
                            }

                            pos += len;
                        }

                        String str = new String(buffer, "UTF-8").trim().toLowerCase(Locale.US);

                        if (!str.contains("<?xml")) {

                            // not straightforward to check for naked DTDs, could be lots of <!-- commentry preamble which of course can occur
                            // in HTML too

                            buffer = new byte[32000];

                            pos = 0;

                            while (pos < buffer.length) {

                                int len = is.read(buffer, pos, buffer.length - pos);

                                if (len <= 0) {

                                    break;
                                }

                                pos += len;
                            }

                            str += new String(buffer, "UTF-8").trim().toLowerCase(Locale.US);

                            if (str.contains("<html") && str.contains("<head")) {

                                throw (new Exception("Bad DTD"));
                            }
                        }
                    } catch (Throwable e) {

                        return new InputSource(
                                new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));

                    } finally {

                        if (is != null) {

                            try {
                                is.close();

                            } catch (Throwable e) {

                            }
                        }
                    }
                    return (null);

                } catch (UnknownHostException e) {

                    return new InputSource(
                            new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));

                } catch (Throwable e) {

                    return (null);
                }
            }
        });

        try {
            feed = docBuild.parse(xmlTmp);

        } catch (Exception e) {

            feed = null;

            String msg = Debug.getNestedExceptionMessage(e);

            if ((msg.contains("entity") && msg.contains("was referenced"))
                    || msg.contains("entity reference")) {

                FileInputStream fis = new FileInputStream(xmlTmp);

                try {

                    feed = docBuild.parse(new EntityFudger(fis));

                } catch (Throwable f) {

                } finally {

                    fis.close();
                }
            }

            if (feed == null) {
                if (e instanceof ParserConfigurationException) {
                    throw ((ParserConfigurationException) e);
                } else if (e instanceof SAXException) {
                    throw ((SAXException) e);
                } else if (e instanceof IOException) {
                    throw ((IOException) e);
                } else {
                    throw (new IOException(msg));
                }
            }
        }

        xmlTmp.delete();
        downloader.done();

        if (downloader.getState() == Downloader.DOWNLOADER_ERROR)
            return;
    } catch (ParserConfigurationException e) {
        if (xmlTmp != null)
            xmlTmp.delete();
        urlBean.setError("Malformed RSS XML: " + e.getMessage());
        return;
    } catch (SAXException e) {
        if (xmlTmp != null)
            xmlTmp.delete();
        urlBean.setError("Malformed RSS XML: " + e.getMessage());
        return;
    } catch (IOException e) {
        if (xmlTmp != null)
            xmlTmp.delete();
        urlBean.setError("IO Exception: " + e.getMessage());
        return;
    }

    if (urlBean.getObeyTTL()) {
        NodeList feedTTL = feed.getElementsByTagName("ttl");
        if (feedTTL.getLength() == 1) {
            int newDelay = Integer.parseInt(getText(feedTTL.item(0))) * 60;
            if (newDelay > 0)
                urlBean.getGroup().setDelay(newDelay, true);
        }
    }

    // Parse the channel's "item"s
    NodeList feedItems = feed.getElementsByTagName("item");
    int feedItemLen = feedItems.getLength();
    for (int iLoop = 0; iLoop < feedItemLen; iLoop++) {
        Node item = feedItems.item(iLoop);
        NodeList params = item.getChildNodes();
        int paramsLen = params.getLength();

        title = link = description = "";

        for (int i = 0; i < paramsLen; i++) {
            Node param = params.item(i);
            if (param.getNodeType() == Node.ELEMENT_NODE) {
                if (param.getNodeName().equalsIgnoreCase("title")) {
                    title = getText(param);
                } else if (param.getNodeName().equalsIgnoreCase("enclosure") && param.hasAttributes()) {
                    if ((((param.getAttributes()).getNamedItem("type")).getNodeValue())
                            .equalsIgnoreCase("application/x-bittorrent")) {
                        link = ((param.getAttributes()).getNamedItem("url")).getNodeValue();
                    }
                } else if (param.getNodeName().equalsIgnoreCase("link") && link.length() == 0) {
                    link = getText(param);
                } else if (param.getNodeName().equalsIgnoreCase("description")) {
                    description = getText(param);
                    if (description != null && description.trim().startsWith("<")) {
                        // strip html tags and entity references from description
                        HtmlAnalyzer parser = new HtmlAnalyzer();
                        try {
                            new ParserDelegator().parse(new StringReader(description), parser, true);
                            description = parser.getPlainText();
                        } catch (IOException e) {
                        }
                    }
                    description += "\n";
                }
            }
        }

        if (link.length() == 0)
            continue;
        if (link.indexOf("://") < 0 && !link.toLowerCase().startsWith("magnet")) {
            try {
                link = HtmlAnalyzer.resolveRelativeURL(urlBean.getLocation(), link);
            } catch (MalformedURLException e) {
                Plugin.debugOut("Bad link URL: " + link + " -> " + e.getMessage());
                continue;
            }
        }

        int state = ListBean.NO_DOWNLOAD;

        String titleTest = title.toLowerCase();
        String linkTest = link.toLowerCase();

        FilterBean curFilter = null;
        for (int i = 0; i < view.rssfeedConfig.getFilterCount(); i++) {
            curFilter = view.rssfeedConfig.getFilter(i);
            if (curFilter == null)
                continue;
            if (curFilter.matches(urlBean.getID(), titleTest, linkTest)) {
                if (curFilter.getMode().equalsIgnoreCase("Pass")) {
                    state = ListBean.DOWNLOAD_INCL;
                } else {
                    state = ListBean.DOWNLOAD_EXCL;
                }
                break;
            }
        }
        Episode e = null;
        Movie m = null;
        final FilterBean filterBean = curFilter;
        if (filterBean != null) {
            if ("TVShow".equalsIgnoreCase(filterBean.getType())) {
                try {
                    e = FilterBean.getSeason(titleTest);
                } catch (Exception ee) {
                }
                try {
                    if (e == null) {
                        e = FilterBean.getSeason(linkTest);
                    }
                } catch (Exception ee) {
                }
            } else if ("Movie".equalsIgnoreCase(filterBean.getType())) {
                m = FilterBean.getMovie(titleTest);
                if (m == null) {
                    m = FilterBean.getMovie(linkTest);
                }
                Plugin.debugOut("Download is a movie: " + m);
            }
        }

        if (state == ListBean.DOWNLOAD_INCL) {
            Plugin.debugOut("testing for download: " + linkTest);
            if (filterBean.getUseSmartHistory()) {
                for (int i = 0; i < view.rssfeedConfig.getHistoryCount(); i++) {
                    HistoryBean histBean = view.rssfeedConfig.getHistory(i);
                    if (linkTest.equalsIgnoreCase(histBean.getLocation())) {
                        Plugin.debugOut("found location match: " + histBean);
                        state = ListBean.DOWNLOAD_HIST;
                        break;
                    }

                    if (e != null && histBean.getSeasonStart() >= 0 && filterBean.getUseSmartHistory()) {
                        final String showTitle = histBean.getTitle();

                        // Old history beans may not have set showTitle so keep using the old way of matching
                        if (showTitle == null ? (histBean.getFiltID() == filterBean.getID())
                                : showTitle.equalsIgnoreCase(e.showTitle)) {
                            // "Proper" episode is not skipped unless history is also proper
                            if (histBean.isProper() || !e.isProper()) {
                                int seasonStart = histBean.getSeasonStart();
                                int episodeStart = histBean.getEpisodeStart();
                                int seasonEnd = histBean.getSeasonEnd();
                                int episodeEnd = histBean.getEpisodeEnd();
                                Plugin.debugOut(e + " vs s" + seasonStart + "e" + episodeStart + " - s"
                                        + seasonEnd + "e" + episodeEnd);
                                if (e.inRange(seasonStart, episodeStart, seasonEnd, episodeEnd)) {
                                    Plugin.debugOut("found filter and episode match: " + e);
                                    state = ListBean.DOWNLOAD_HIST;
                                    break;
                                }
                            }
                        }
                    } else if (m != null && m.getTitle().equals(histBean.getTitle())
                            && m.getYear() == histBean.getYear()) {
                        if (histBean.isProper() || !m.isProper()) {
                            Plugin.debugOut("found movie match: " + m);
                            state = ListBean.DOWNLOAD_HIST;
                        }
                    }
                }
            } else
                Plugin.debugOut("Filter doesn't use smart history: " + filterBean);
        }

        final ListBean listBean = addTableElement(urlBean, listBeans, title, link, description, state);

        if (state == ListBean.DOWNLOAD_INCL) {
            // Add the feed
            final String curLink = link;
            boolean success = view.torrentDownloader.addTorrent(curLink, urlBean, filterBean, listBean);
            if (success && filterBean.getType().equalsIgnoreCase("Other") && filterBean.getDisableAfter())
                filterBean.setEnabled(false);

            if (view.isOpen() && view.display != null && !view.display.isDisposed())
                view.display.asyncExec(new Runnable() {
                    public void run() {
                        ListTreeItem listItem = view.treeViewManager.getItem(listBean);
                        if (listItem != null)
                            listItem.update();
                    }
                });
        }
    }
}

From source file:org.openmicroscopy.shoola.env.data.model.FileObject.java

/**
 * Returns the Pixels node matching the index.
 *
 * @param doc The document to handle.//w ww .  java2 s.  c  o m
 * @return See above.
 */
private Node getPixelsNode(Document doc) {

    NodeList l = doc.getElementsByTagName("Image");
    if (l == null || l.getLength() == 0)
        return null;
    NamedNodeMap attributes;
    String value;
    Node node;
    NodeList nodeList;
    int series = getIndex();
    for (int i = 0; i < l.getLength(); i++) {
        node = l.item(i);
        if (node.hasAttributes()) {
            attributes = node.getAttributes();
            value = attributes.getNamedItem("ID").getNodeValue();
            if (value.equals("Image:" + series)) {
                nodeList = node.getChildNodes();
                if (nodeList != null && nodeList.getLength() > 0) {
                    for (int j = 0; j < nodeList.getLength(); j++) {
                        Node n = nodeList.item(j);
                        if ("Pixels".equals(n.getNodeName())) {
                            return n;
                        }
                    }
                }
            }
        }
    }
    return null;
}

From source file:org.openmicroscopy.shoola.util.file.modulo.ModuloParser.java

/** 
 * Retrieves the content of the tags that we handle.
 * Stores their DOM representation (DOM node) into a list.
 *//*from  ww w.j a  va2 s  .  c  om*/
private void readModuloEntries() {
    NodeList list;
    Node n;
    for (int k = 0; k < tagsModulo.length; ++k) {
        list = document.getElementsByTagName(tagsModulo[k]);
        for (int i = 0; i < list.getLength(); ++i) {
            n = list.item(i);
            if (n.hasAttributes())
                moduloTags.add(n);
        }
    }
}

From source file:org.openmicroscopy.shoola.util.file.modulo.ModuloParser.java

/** 
 * Creates a concrete <code>ModuloInfo</code> object to handle the
 * conversion of the content of the passed tag into an object. 
 *
 * @param tag DOM node representing either a <i>modulo</i> tag.
 * @return See above./*from  w w  w. j a  va2 s.  c o m*/
 * @throws Exception If the tag couldn't be handled.
 */
ModuloInfo createModuloFor(Node tag) throws Exception {
    if (!tag.hasAttributes())
        throw new Exception("Missing tag's attributes.");
    ModuloInfo info = new ModuloInfo(tag.getNodeName());
    NamedNodeMap attributes = tag.getAttributes();
    Node attribute;
    for (int i = 0; i < attributes.getLength(); ++i) {
        attribute = attributes.item(i);
        if (ModuloInfo.START.equals(attribute.getNodeName()))
            info.setStart(Double.parseDouble(attribute.getNodeValue()));
        else if (ModuloInfo.END.equals(attribute.getNodeName()))
            info.setEnd(Double.parseDouble(attribute.getNodeValue()));
        else if (ModuloInfo.STEP.equals(attribute.getNodeName()))
            info.setStep(Double.parseDouble(attribute.getNodeValue()));
        else if (ModuloInfo.TYPE.equals(attribute.getNodeName()))
            info.setType(attribute.getNodeValue());
        else if (ModuloInfo.TYPE_DESCRIPTION.equals(attribute.getNodeName()))
            info.setTypeDescription(attribute.getNodeValue());
        else if (ModuloInfo.UNIT.equals(attribute.getNodeName()))
            info.setUnit(attribute.getNodeValue());
    }
    NodeList nodes = tag.getChildNodes();
    Double min = Double.MAX_VALUE;
    Double max = Double.MIN_VALUE;
    Double v;
    List<Double> labels = new ArrayList<Double>();
    for (int i = 0; i < nodes.getLength(); i++) {
        attribute = nodes.item(i);
        if (attribute.getNodeType() == Node.ELEMENT_NODE) {
            if (ModuloInfo.LABEL.equals(attribute.getNodeName())) {
                v = Double.parseDouble(attribute.getFirstChild().getNodeValue());
                if (v < min)
                    min = v;
                if (v > max)
                    max = v;
                labels.add(v);
            }
        }
    }
    if (!CollectionUtils.isEmpty(labels)) {
        info.setStart(min);
        info.setEnd(max);
        info.setLabels(labels);
    }

    return info;
}

From source file:org.openmrs.module.muzima.handler.XmlEncounterQueueDataHandler.java

private void processObs(final Encounter encounter, final NodeList obsNodeList) throws QueueProcessorException {
    Node obsNode = obsNodeList.item(0);
    NodeList obsElementNodes = obsNode.getChildNodes();
    for (int i = 0; i < obsElementNodes.getLength(); i++) {
        Node obsElementNode = obsElementNodes.item(i);
        // skip all top level obs nodes without child element or without attribute
        // no attribute: temporary elements
        // no child: element with no answer
        if (obsElementNode.hasAttributes() && obsElementNode.hasChildNodes()) {
            processObsNode(encounter, null, obsElementNode);
        }/*from   ww  w. j a v  a  2  s . c  o m*/
    }
}

From source file:org.openmrs.module.muzima.handler.XmlEncounterQueueDataHandler.java

private void processObsNode(final Encounter encounter, final Obs parentObs, final Node obsElementNode) {
    Element obsElement = (Element) obsElementNode;
    String[] conceptElements = StringUtils.split(obsElement.getAttribute("concept"), "\\^");
    int conceptId = Integer.parseInt(conceptElements[0]);
    Concept concept = Context.getConceptService().getConcept(conceptId);

    if (concept == null) {
        log.info("Skipping obs creation, " + obsElement.getAttribute("concept")
                + " is not valid or not available.");
        return;/*from   www.  ja  v a 2  s .  co  m*/
    }

    if (concept.isSet()) {
        Obs obsGroup = new Obs();
        obsGroup.setConcept(concept);
        obsGroup.setCreator(encounter.getCreator());
        NodeList nodeList = obsElementNode.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node subNode = nodeList.item(i);
            // only process sub node with attribute and it is a tag
            if (subNode.hasAttributes() && subNode.getNodeType() == Node.ELEMENT_NODE) {
                // need to do recursive because we might have nested sets structure
                encounter.addObs(obsGroup);
                processObsNode(encounter, obsGroup, subNode);
            }
        }
    } else {
        Node valueNode = findSubNode("value", obsElementNode);
        if (valueNode != null) {
            String value = StringUtils.trim(valueNode.getTextContent());
            if (StringUtils.isNotEmpty(value)) {
                Obs obs = new Obs();
                obs.setConcept(concept);
                obs.setEncounter(encounter);
                obs.setPerson(encounter.getPatient());
                obs.setObsDatetime(encounter.getEncounterDatetime());
                obs.setLocation(encounter.getLocation());
                obs.setCreator(encounter.getCreator());
                // find the obs value :)
                if (concept.getDatatype().isNumeric()) {
                    obs.setValueNumeric(Double.parseDouble(value));
                } else if (concept.getDatatype().isDate() || concept.getDatatype().isTime()
                        || concept.getDatatype().isDateTime()) {
                    obs.setValueDatetime(parseDate(value));
                } else if (concept.getDatatype().isCoded()) {
                    String[] valueCodedElements = StringUtils.split(value, "\\^");
                    int valueCodedId = Integer.parseInt(valueCodedElements[0]);
                    Concept valueCoded = Context.getConceptService().getConcept(valueCodedId);
                    if (valueCoded == null) {
                        queueProcessorException.addException(new Exception(
                                "Unable to find concept for value coded with id: " + valueCodedId));
                    }
                    obs.setValueCoded(valueCoded);
                } else if (concept.getDatatype().isText()) {
                    obs.setValueText(value);
                }
                // only add if the value is not empty :)
                encounter.addObs(obs);
                if (parentObs != null) {
                    parentObs.addGroupMember(obs);
                }
            }
        } else {
            Node xformValuesNode = findSubNode("xforms_value", obsElementNode);
            if (xformValuesNode != null) {
                String[] xformValues = StringUtils.split(StringUtils.trim(xformValuesNode.getTextContent()));
                for (String xformValue : xformValues) {
                    Node xformValueNode = findSubNode(xformValue, obsElementNode);
                    if (xformValueNode != null && xformValueNode.hasAttributes()) {
                        Obs obs = new Obs();
                        obs.setConcept(concept);
                        obs.setEncounter(encounter);
                        obs.setPerson(encounter.getPatient());
                        obs.setObsDatetime(encounter.getEncounterDatetime());
                        obs.setLocation(encounter.getLocation());
                        obs.setCreator(encounter.getCreator());

                        Element xformValueElement = (Element) xformValueNode;
                        String[] valueCodedElements = StringUtils
                                .split(xformValueElement.getAttribute("concept"), "\\^");
                        int valueCodedId = Integer.parseInt(valueCodedElements[0]);
                        Concept valueCoded = Context.getConceptService().getConcept(valueCodedId);
                        if (valueCoded == null) {
                            queueProcessorException.addException(new Exception(
                                    "Unable to find concept for value coded with id: " + valueCodedId));
                        }
                        obs.setValueCoded(valueCoded);

                        encounter.addObs(obs);
                        if (parentObs != null) {
                            parentObs.addGroupMember(obs);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.sakaiproject.site.util.SiteSetupQuestionFileParser.java

/**
 * Populate cached values from a configuration XML resource.  We always try
 * to parse the resource, regardless of any prior success or failure.
 *
 * @param configurationXml Configuration resource name (this doubles as a
 *                         unique key into the configuration cache)
 *//*from w w  w  .  ja  va2s .co m*/
protected static SiteSetupQuestionMap populateConfig(String configurationXml, InputStream stream) {
    org.w3c.dom.Document document;
    String value;

    /*
     * Parse the XML - if that fails, give up now
     */
    if ((document = parseXmlFromStream(stream)) == null) {
        return null;
    }

    SiteSetupQuestionMap m = new SiteSetupQuestionMap();

    Element rootElement = document.getDocumentElement();
    NodeList childList = rootElement.getChildNodes();
    // root element should be "SiteSetupQuestions"
    if (childList == null || childList.getLength() == 0) {
        m_log.warn("Cannot find elements in SiteSetupQuestions");
    } else {
        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                if (currentNode.hasAttributes()) {
                    NamedNodeMap nNMap = currentNode.getAttributes();
                    String siteType = nNMap.getNamedItem("type") != null
                            ? nNMap.getNamedItem("type").getNodeValue()
                            : null;
                    if (siteType != null) {
                        // add the site type into the question list
                        SiteTypeQuestions siteTypeQuestions = questionService.newSiteTypeQuestions();
                        siteTypeQuestions.setSiteType(siteType);

                        NodeList qSetList = currentNode.getChildNodes();
                        for (int i2 = 0; i2 < qSetList.getLength(); i2++) {
                            Node qNode = qSetList.item(i2);
                            switch (qNode.getNodeType()) {
                            case Node.TEXT_NODE:
                                break;
                            case Node.ELEMENT_NODE:
                                if (qNode.getNodeName().equals("header")) {
                                    siteTypeQuestions.setInstruction(qNode.getTextContent());
                                } else if (qNode.getNodeName().equals("url")) {
                                    NodeList qList = qNode.getChildNodes();
                                    for (int i3 = 0; i3 < qList.getLength(); i3++) {
                                        Node qDetailNode = qList.item(i3);
                                        switch (qDetailNode.getNodeType()) {
                                        case Node.TEXT_NODE:
                                            break;
                                        case Node.ELEMENT_NODE:
                                            if (qDetailNode.getNodeName().equals("a")) {
                                                if (qDetailNode.hasAttributes()) {
                                                    // attributes
                                                    NamedNodeMap qDetailMap = qDetailNode.getAttributes();
                                                    if (qDetailMap.getNamedItem("href") != null) {
                                                        siteTypeQuestions.setUrl(
                                                                qDetailMap.getNamedItem("href").getNodeValue());
                                                    } else if (qDetailMap.getNamedItem("target") != null) {
                                                        siteTypeQuestions.setUrlTarget(qDetailMap
                                                                .getNamedItem("target").getNodeValue());
                                                    }
                                                }
                                                siteTypeQuestions.setUrlLabel(qDetailNode.getTextContent());
                                            }
                                        }
                                    }
                                } else if (qNode.getNodeName().equals("question")) {
                                    SiteSetupQuestion q = questionService.newSiteSetupQuestion();
                                    if (qNode.hasAttributes()) {
                                        // attributes
                                        NamedNodeMap qMap = qNode.getAttributes();
                                        if (qMap.getNamedItem("required") != null) {
                                            q.setRequired(Boolean
                                                    .valueOf(qMap.getNamedItem("required").getNodeValue()));
                                        } else {
                                            q.setRequired(false);
                                        }
                                        if (qMap.getNamedItem("multiple_answers") != null) {
                                            q.setIsMultipleAnswers(Boolean.valueOf(
                                                    qMap.getNamedItem("multiple_answers").getNodeValue()));
                                        } else {
                                            q.setIsMultipleAnswers(false);
                                        }

                                        NodeList qList = qNode.getChildNodes();
                                        for (int i3 = 0; i3 < qList.getLength(); i3++) {
                                            Node qDetailNode = qList.item(i3);
                                            switch (qDetailNode.getNodeType()) {
                                            case Node.TEXT_NODE:
                                                break;
                                            case Node.ELEMENT_NODE:
                                                if (qDetailNode.getNodeName().equals("q")) {
                                                    q.setQuestion(qDetailNode.getTextContent());
                                                } else if (qDetailNode.getNodeName().equals("answer")) {
                                                    SiteSetupQuestionAnswer answer = questionService
                                                            .newSiteSetupQuestionAnswer();
                                                    if (qDetailNode.hasAttributes()) {
                                                        // attributes
                                                        NamedNodeMap qDetailMap = qDetailNode.getAttributes();
                                                        if (qDetailMap.getNamedItem("fillin_blank") != null) {
                                                            answer.setIsFillInBlank(Boolean.valueOf(
                                                                    qDetailMap.getNamedItem("fillin_blank")
                                                                            .getNodeValue()));
                                                        } else {
                                                            answer.setIsFillInBlank(false);
                                                        }
                                                    }
                                                    answer.setAnswer(qDetailNode.getTextContent());
                                                    // save answer
                                                    questionService.saveSiteSetupQuestionAnswer(answer);
                                                    q.addAnswer(answer);
                                                }
                                                break;
                                            }
                                        }
                                    }

                                    // mark this question as currently used
                                    q.setCurrent("true");

                                    // save question
                                    questionService.saveSiteSetupQuestion(q);
                                    siteTypeQuestions.addQuestion(q);
                                }

                                break;
                            }
                        }
                        // save siteTypeQuestions
                        questionService.saveSiteTypeQuestions(siteTypeQuestions);

                    }
                }
                break;
            }
        }
    }

    // what to do?

    return m;
}

From source file:org.tizzit.util.XercesHelper.java

public static String node2string(Node nde) {
    StringBuffer sb = new StringBuffer();
    String attributes = "";
    if (nde.hasAttributes()) {
        NamedNodeMap attr = nde.getAttributes();
        for (int j = 0; j < attr.getLength(); j++) {
            attributes += " " + attr.item(j).getNodeName() + "=\"" + getHexEncoded(attr.item(j).getNodeValue())
                    + "\"";
        }/* w  ww.ja v a2s .  co  m*/
    }
    sb.append("<" + nde.getNodeName() + attributes);
    if (nde.hasChildNodes()) {
        sb.append(">" + nodeList2string(nde.getChildNodes()) + "</" + nde.getNodeName() + ">");
    } else {
        sb.append("/>");
    }
    return sb.toString();
}

From source file:org.tizzit.util.XercesHelper.java

public static String nodeList2string(NodeList nl) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < nl.getLength(); i++) {
        Node nde = nl.item(i);
        String attributes = "";
        if (nde.getNodeType() == Node.TEXT_NODE) {
            sb.append(getHexEncoded(nde.getNodeValue()));
            if (nde.hasChildNodes()) {
                sb.append(nodeList2string(nde.getChildNodes()));
            }/*from w  w w.j  a v  a2  s.c  om*/
        } else if (nde.getNodeType() == Node.CDATA_SECTION_NODE) {
            sb.append("<![CDATA[" + nde.getNodeValue() + "]]>");
        } else if (nde.getNodeType() == Node.COMMENT_NODE) {
            sb.append("<!-- -->");
        } else {
            if (nde.hasAttributes()) {
                NamedNodeMap attr = nde.getAttributes();
                for (int j = 0; j < attr.getLength(); j++) {
                    attributes += " " + attr.item(j).getNodeName() + "=\""
                            + getHexEncoded(attr.item(j).getNodeValue()) + "\"";
                }
            }
            sb.append("<" + nde.getNodeName() + attributes);
            if (nde.hasChildNodes()) {
                sb.append(">" + nodeList2string(nde.getChildNodes()) + "</" + nde.getNodeName() + ">");
            } else {
                sb.append("/>");
            }
        }
    }
    return sb.toString();
}