Example usage for org.w3c.dom Document getElementsByTagName

List of usage examples for org.w3c.dom Document getElementsByTagName

Introduction

In this page you can find the example usage for org.w3c.dom Document getElementsByTagName.

Prototype

public NodeList getElementsByTagName(String tagname);

Source Link

Document

Returns a NodeList of all the Elements in document order with a given tag name and are contained in the document.

Usage

From source file:com.collabnet.ccf.core.recovery.HospitalArtifactReplayer.java

private Element getRouterElement(Document document) {
    NodeList beanNodesList = document.getElementsByTagName("bean");
    Node routerNode = null;//from  w  w w. j  a  va 2  s .c o  m
    for (int i = 0; i < beanNodesList.getLength(); i++) {
        Node node = beanNodesList.item(i);
        NamedNodeMap nodeMap = node.getAttributes();
        Node idNode = nodeMap.getNamedItem("id");
        String id = idNode.getNodeValue();
        // FIXME What happens if the router is not called router?
        if (id.equals("Router")) {
            routerNode = node;
        }
    }
    return (Element) routerNode;
}

From source file:com.zacwolf.commons.wbxcon.WBXCONorg.java

/**
 * This is a helper method that returns the text content from the first node with
 * the specified tag name/*from  w  w w .j  av a 2 s .co m*/
 * @param {@link org.w3c.dom.Document} to parse
 * @param tagname
 * @return text content for the specified tag or null if no text content
 */
final static String documentGetTextContentByTagName(final Document dom, final String tagname) {
    try {
        return dom.getElementsByTagName(tagname).item(0).getTextContent();
    } catch (final NullPointerException npe) {
        return null;
    }
}

From source file:com.lyncode.xoai.serviceprovider.iterators.RecordIterator.java

private void harvest() throws NoRecordsMatchException, BadResumptionTokenException,
        CannotDisseminateFormatException, NoSetHierarchyException, InternalHarvestException {
    HttpClient httpclient = new DefaultHttpClient();
    String url = makeUrl();//from   ww w.j  av  a 2 s . co  m
    log.info("Harvesting: " + url);
    HttpGet httpget = new HttpGet(url);
    httpget.addHeader("User-Agent", HarvesterManager.USERAGENT);
    httpget.addHeader("From", HarvesterManager.FROM);

    HttpResponse response = null;

    if (this.proxyIp != null && this.proxyPort > -1) {
        HttpHost proxy = new HttpHost(this.proxyIp, this.proxyPort);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    try {
        response = httpclient.execute(httpget);
        StatusLine status = response.getStatusLine();

        log.debug(response.getStatusLine());

        if (status.getStatusCode() == 503) // 503 Status (must wait)
        {
            org.apache.http.Header[] headers = response.getAllHeaders();
            for (org.apache.http.Header h : headers) {
                if (h.getName().equals("Retry-After")) {
                    String retry_time = h.getValue();
                    try {
                        Thread.sleep(Integer.parseInt(retry_time) * 1000);
                    } catch (NumberFormatException e) {
                        log.warn("Cannot parse " + retry_time + " to Integer", e);
                    } catch (InterruptedException e) {
                        log.debug(e.getMessage(), e);
                    }
                    httpclient.getConnectionManager().shutdown();
                    httpclient = new DefaultHttpClient();
                    response = httpclient.execute(httpget);
                }
            }
        }

        HttpEntity entity = response.getEntity();
        InputStream instream = entity.getContent();

        Document doc = XMLUtils.parseDocument(instream);

        XMLUtils.checkListRecords(doc);

        NodeList listRecords = doc.getElementsByTagName("record");
        for (int i = 0; i < listRecords.getLength(); i++)
            _queue.add(XMLUtils.getRecord(listRecords.item(i)));

        resumption = XMLUtils.getText(doc.getElementsByTagName("resumptionToken"));
        log.debug("RESUMPTION: " + resumption);
    } catch (IOException e) {
        throw new InternalHarvestException(e);
    } catch (ParserConfigurationException e) {
        throw new InternalHarvestException(e);
    } catch (SAXException e) {
        throw new InternalHarvestException(e);
    }

}

From source file:eu.guardiansystems.livesapp.android.ui.GMapDirections.java

public int getDistanceValue(Document doc) {
    try {/*from www.java  2 s  .  c  om*/
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = null;
        node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));

        return Integer.parseInt(node2.getTextContent());
    } catch (Exception e) {
        return -1;
    }
    /*
     * NodeList nl1 = doc.getElementsByTagName("distance"); Node node1 =
     * null; if (nl1.getLength() > 0) node1 = nl1.item(nl1.getLength() - 1);
     * if (node1 != null) { NodeList nl2 = node1.getChildNodes(); Node node2
     * = nl2.item(getNodeIndex(nl2, "value")); Log.i("DistanceValue",
     * node2.getTextContent()); return
     * Integer.parseInt(node2.getTextContent()); } else return 0;
     */
}

From source file:com.lyncode.xoai.serviceprovider.iterators.IdentifierIterator.java

private void harvest() throws InternalHarvestException, NoRecordsMatchException, BadResumptionTokenException,
        CannotDisseminateFormatException, NoSetHierarchyException {
    HttpClient httpclient = new DefaultHttpClient();
    String url = makeUrl();// w ww.java2 s  .  co m
    log.info("Harvesting: " + url);
    HttpGet httpget = new HttpGet(url);
    httpget.addHeader("User-Agent", HarvesterManager.USERAGENT);
    httpget.addHeader("From", HarvesterManager.FROM);

    HttpResponse response = null;

    if (this.proxyIp != null && this.proxyPort > -1) {
        HttpHost proxy = new HttpHost(this.proxyIp, this.proxyPort);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    try {
        response = httpclient.execute(httpget);
        StatusLine status = response.getStatusLine();

        log.debug(response.getStatusLine());

        if (status.getStatusCode() == 503) // 503 Status (must wait)
        {
            org.apache.http.Header[] headers = response.getAllHeaders();
            for (org.apache.http.Header h : headers) {
                if (h.getName().equals("Retry-After")) {
                    String retry_time = h.getValue();
                    try {
                        Thread.sleep(Integer.parseInt(retry_time) * 1000);
                    } catch (NumberFormatException e) {
                        log.warn("Cannot parse " + retry_time + " to Integer", e);
                    } catch (InterruptedException e) {
                        log.debug(e.getMessage(), e);
                    }
                    httpclient.getConnectionManager().shutdown();
                    httpclient = new DefaultHttpClient();
                    response = httpclient.execute(httpget);
                }
            }
        }

        HttpEntity entity = response.getEntity();
        InputStream instream = entity.getContent();

        Document doc = XMLUtils.parseDocument(instream);

        XMLUtils.checkListIdentifiers(doc);

        NodeList listRecords = doc.getElementsByTagName("header");
        for (int i = 0; i < listRecords.getLength(); i++)
            _queue.add(XMLUtils.getIdentifier(listRecords.item(i)));

        resumption = XMLUtils.getText(doc.getElementsByTagName("resumptionToken"));
        log.debug("RESUMPTION: " + resumption);
    } catch (IOException e) {
        throw new InternalHarvestException(e);
    } catch (ParserConfigurationException e) {
        throw new InternalHarvestException(e);
    } catch (SAXException e) {
        throw new InternalHarvestException(e);
    }

}

From source file:eu.optimis.sm.gui.server.XmlUtil.java

public List<Resource> getMonitoringRsModel(String xml) {
    try {//ww w  .  j  a  v a2  s .c  o m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));

        NodeList msList = doc.getElementsByTagName("monitoring_resource");

        ArrayList<Resource> rsList = new ArrayList<Resource>();
        for (int i = 0; i < msList.getLength(); i++) {
            Resource mdata = new Resource();
            Element ts = (Element) msList.item(i);
            Element eMetricname = (Element) ts.getElementsByTagName("metric_name").item(0);
            String sMetricname = eMetricname.getTextContent();
            mdata.setMetricName(sMetricname);

            Element eMetricvalue = (Element) ts.getElementsByTagName("metric_value").item(0);
            String sMetricvalue = eMetricvalue.getTextContent();
            mdata.setMetricValue(sMetricvalue);

            Element eMetricunit = (Element) ts.getElementsByTagName("metric_unit").item(0);
            String sMetricunit = eMetricunit.getTextContent();
            mdata.setMetricUnit(sMetricunit);

            Element eMetrictp = (Element) ts.getElementsByTagName("metric_timestamp").item(0);
            String tsLangType = eMetrictp.getTextContent();
            mdata.setMetricTimestamp(tsLangType);

            Element eMinfoColType = (Element) ts.getElementsByTagName("monitoring_information_collector_id")
                    .item(0);
            if (eMinfoColType != null) {
                String sMinfoColType = eMinfoColType.getTextContent();
                mdata.setCollectorId(sMinfoColType);
            }

            Element eResType = (Element) ts.getElementsByTagName("resource_type").item(0);
            if (eResType != null) {
                String sResType = eResType.getTextContent();
                mdata.setResourceType(sResType);
            }

            Element ePResId = (Element) ts.getElementsByTagName("physical_resource_id").item(0);
            if (ePResId != null) {
                String sPResId = ePResId.getTextContent();
                mdata.setPhysicalResourceId(sPResId);
            }

            Element eSResId = (Element) ts.getElementsByTagName("service_resource_id").item(0);
            if (eSResId != null) {
                String sSResId = eSResId.getTextContent();
                mdata.setServiceResourceId(sSResId);
            }

            Element eVResId = (Element) ts.getElementsByTagName("virtual_resource_id").item(0);
            if (eVResId != null) {
                String sVResId = eVResId.getTextContent();
                mdata.setVirtualResourceId(sVResId);
            }
            rsList.add(mdata);
            mdata = null;
        }

        return rsList;

    } catch (SAXException e) {
        return null;
    } catch (ParserConfigurationException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
}

From source file:in.raster.oviyam.util.ReadXMLFile.java

public JSONArray getElementValues(String tagName) {
    Document doc = this.getXMLDocument();
    JSONArray jsonArr = null;/*from  ww w .  jav  a  2s . c  o  m*/
    try {
        jsonArr = new JSONArray();
        JSONObject jsonObj = null;

        NodeList nodeList = doc.getElementsByTagName(tagName);

        for (int i = 0; i < nodeList.getLength(); i++) {
            jsonObj = new JSONObject();
            Element element = (Element) nodeList.item(i);

            NodeList nList = element.getChildNodes();
            for (int j = 0; j < nList.getLength(); j++) {
                Node node = nList.item(j);
                switch (node.getNodeType()) {
                case Node.ELEMENT_NODE:
                    jsonObj.put(node.getNodeName(), getTagValue(node.getNodeName(), element));
                    break;
                }
            }
            jsonArr.put(jsonObj);
        }
    } catch (Exception e) {
        log.info("Unable to get element values ", e);
    }

    return jsonArr;
}

From source file:org.dasein.cloud.ibm.sce.identity.keys.SSHKeys.java

@Override
public @Nonnull SSHKeypair createKeypair(@Nonnull String name) throws InternalException, CloudException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new SCEConfigException("No context was configured for this request");
    }/*from w ww.j  a v  a 2s .  com*/
    ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();

    parameters.add(new BasicNameValuePair("name", name));

    SCEMethod method = new SCEMethod(provider);
    String response = method.post("/keys", parameters);

    if (response == null) {
        throw new CloudException("Cloud accepted the post, but no body was in the response");
    }

    Document doc = method.parseResponse(response, true);

    NodeList nodes = doc.getElementsByTagName("PrivateKey");

    for (int i = 0; i < nodes.getLength(); i++) {
        Node item = nodes.item(i);
        SSHKeypair kp = toKeyPair(ctx, item, true);

        if (kp != null) {
            SSHKeypair withPublic = getKeypair(name);
            String publicKey = (withPublic == null ? null : withPublic.getPublicKey());

            if (publicKey != null) {
                kp.setPublicKey(publicKey);
            }
            return kp;
        }
    }
    throw new CloudException("No key pair was in the XML response");
}

From source file:com.nanocrawler.contentparser.HtmlContentParser.java

@Override
// Runs the whole parsing, extracts links from the page 
public Content parseContent(Page page, String contextUrl) {
    HtmlContent c = new HtmlContent();
    try {//  ww w  .java 2s.c o m
        Document doc = parseHtml(page, c);

        c.setText(doc.getElementsByTagName(BODY_ELEMENT).item(0).getTextContent().trim());
        if (doc.getElementsByTagName(TITLE_ELEMENT).getLength() > 0) {
            c.setTitle(doc.getElementsByTagName(TITLE_ELEMENT).item(0).getTextContent().trim());
        }

        String baseUrl = getBaseUrl(doc);
        if (baseUrl != null) {
            contextUrl = baseUrl;
        }

        List<ExtractedUrlAnchorPair> extractedUrls = getOutgoingUrls(doc);
        List<WebURL> outgoingUrls = new ArrayList<>();
        int urlCount = 0;
        for (ExtractedUrlAnchorPair urlAnchorPair : extractedUrls) {
            String href = urlAnchorPair.getHref();
            href = href.trim();
            if (href.length() == 0) {
                continue;
            }

            String hrefWithoutProtocol = href.toLowerCase();
            if (href.startsWith("http://")) {
                hrefWithoutProtocol = href.substring(7);
            }

            if (!hrefWithoutProtocol.contains("javascript:") && !hrefWithoutProtocol.contains("mailto:")
                    && !hrefWithoutProtocol.contains("@")) {
                String url = URLCanonicalizer.getCanonicalURL(href, contextUrl);
                if (url != null) {
                    WebURL webURL = new WebURL();
                    webURL.setURL(url);
                    webURL.setAnchor(urlAnchorPair.getAnchor());
                    outgoingUrls.add(webURL);
                    urlCount++;
                    if (urlCount > config.getMaxOutgoingLinksToFollow()) {
                        break;
                    }
                }
            }
        }

        c.setOutgoingUrls(outgoingUrls);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return c;
}

From source file:com.castlemock.web.mock.rest.converter.wadl.WADLRestDefinitionConverter.java

/**
 * The method extracts all the application elements from the provided document
 * @param document The document which contains all the application that will be extracted
 * @return A list of application elements
 *//*from  w w w  . j a va 2s  . c  om*/
private List<Element> getApplications(Document document) {
    List<Element> applicationElements = new LinkedList<Element>();
    final NodeList applicationNodeList = document.getElementsByTagName("application");

    for (int applicationIndex = 0; applicationIndex < applicationNodeList.getLength(); applicationIndex++) {
        Node applicationNode = applicationNodeList.item(applicationIndex);
        if (applicationNode.getNodeType() == Node.ELEMENT_NODE) {
            Element applicationElement = (Element) applicationNode;
            applicationElements.add(applicationElement);
        }
    }
    return applicationElements;
}