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.compomics.colims.core.service.impl.UniProtServiceImpl.java

@Override
public Map<String, String> getUniProtByAccession(String accession) throws RestClientException, IOException {
    Map<String, String> uniProt = new HashMap<>();

    try {// w  ww  .  ja  v a2s.c  om
        // Set XML content type explicitly to force response in XML (If not spring gets response in JSON)
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
        HttpEntity<String> entity = new HttpEntity<>("parameters", headers);

        ResponseEntity<String> response = restTemplate.exchange(UNIPROT_BASE_URL + "/" + accession + ".xml",
                HttpMethod.GET, entity, String.class);
        String responseBody = response.getBody();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(responseBody));

        Document document = (Document) builder.parse(is);
        document.getDocumentElement().normalize();
        NodeList recommendedName = document.getElementsByTagName("recommendedName");

        Node node = recommendedName.item(0);
        Element element = (Element) node;
        if (element.getElementsByTagName("fullName").item(0).getTextContent() != null
                && !element.getElementsByTagName("fullName").item(0).getTextContent().equals("")) {
            uniProt.put("description", element.getElementsByTagName("fullName").item(0).getTextContent());
        }

        NodeList organism = document.getElementsByTagName("organism");
        node = organism.item(0);
        element = (Element) node;
        if (element.getElementsByTagName("name").item(0).getTextContent() != null
                && !element.getElementsByTagName("name").item(0).getTextContent().equals("")) {
            uniProt.put("species", element.getElementsByTagName("name").item(0).getTextContent());
        }

        NodeList dbReference = document.getElementsByTagName("dbReference");
        node = dbReference.item(0);
        element = (Element) node;
        if (element.getAttribute("id") != null && !element.getAttribute("id").equals("")) {
            uniProt.put("taxid", element.getAttribute("id"));
        }

    } catch (HttpClientErrorException ex) {
        LOGGER.error(ex.getMessage(), ex);
        //ignore the exception if the namespace doesn't correspond to an ontology
        if (!ex.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
            throw ex;
        }
    } catch (ParserConfigurationException | SAXException ex) {
        java.util.logging.Logger.getLogger(UniProtServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    return uniProt;
}

From source file:org.shareok.data.plosdata.PlosApiDataImpl.java

private String getJsonApiResponseByQuery(String query) {
    String jsonData = null;/*  w  w  w  .jav  a  2s  .  co m*/
    try {
        if (null != query) {
            System.out.println(query);
            //                query = "http://api.plos.org/search?q=author_affiliate%3A%22University%20of%20Oklahoma%22%20AND%20publication_date:[2016-01-01T00:00:00Z+TO+2016-12-31T23:59:59Z]&rows=500&fl=affiliate,doi,author,volume,issue,title,journal,publication_date&api_key=mC8TEAzqwfvDWs4eamFh";
            ApplicationContext context = new ClassPathXmlApplicationContext("htmlRequestContext.xml");
            HttpRequestHandler req = (HttpRequestHandler) context.getBean("httpRequestHandler");
            String response = req.sendGet(query);
            String[] responseInfoArr = response.split("\\n");
            if (null != responseInfoArr[0] && responseInfoArr[0].equals("200")) {
                List<Map<String, String>> articleData = new ArrayList<>();
                String responseDocs = responseInfoArr[1];
                if (!DocumentProcessorUtil.isEmptyString(responseDocs)) {
                    Document doc = DocumentProcessorUtil.loadXMLFromStringContent(responseDocs);
                    NodeList docList = doc.getElementsByTagName("doc");
                    for (int i = 0; i < docList.getLength(); i++) {
                        Element item = (Element) docList.item(i);
                        Map<String, String> tmpMapData = getArticleMapData(item);
                        if (tmpMapData.containsKey("doi")) {
                            articleData.add(tmpMapData);
                        } else {
                            throw new NoDoiDataException(
                                    "Parseing the api response did not get DOI information!");
                        }
                    }
                }
                ObjectMapper mapper = new ObjectMapper();
                jsonData = mapper.writeValueAsString(articleData);
            } else {
                throw new ErrorPlosApiResponseException("Got the response code " + responseInfoArr[0]);
            }
        } else {
            throw new InvalidPlosApiQueryException("The plos api query is null");
        }
    } catch (Exception ex) {
        logger.error(ex);
    }
    return jsonData;
}

From source file:com.sparkred.mdex.metrics.publish.EndecaMDEXAgent.java

/**
 * sample XML : <throughput units="req/sec" five_minute_avg="0.02"
 * one_minute_avg="0.06" ten_second_avg="0.07" />
 * //  w  ww .ja  v a 2 s.  c o  m
 * 
 * @param pDoc
 */
private void reportThroughputMetrics(Document pDoc) {
    NodeList thorughPut_stats = pDoc.getElementsByTagName("throughput");
    Node node = thorughPut_stats.item(0);
    NamedNodeMap attr = node.getAttributes();
    Double fiveMinuteAvg = Double.valueOf(attr.getNamedItem("five_minute_avg").getNodeValue());
    Double oneMinuteAvg = Double.valueOf(attr.getNamedItem("one_minute_avg").getNodeValue());
    Double tenSecondAvg = Double.valueOf(attr.getNamedItem("ten_second_avg").getNodeValue());

    reportMetric(METRIC_THRPT_5_MIN_AVG, UNIT_REQ_SEC, fiveMinuteAvg);
    reportMetric(METRIC_THRPT_1_MIN_AVG, UNIT_REQ_SEC, oneMinuteAvg);
    reportMetric(METRIC_THRPT_10_SEC_AVG, UNIT_REQ_SEC, tenSecondAvg);
}

From source file:lv.coref.io.MmaxReaderWriter.java

public void readWords(Text text, String fileName) {
    try {//from   w w  w  . j  a v  a  2  s  . c  om
        File file = new File(fileName);
        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = dBuilder.parse(file);
        NodeList markables = doc.getElementsByTagName("word");
        words = new ArrayList<String>();
        for (int i = 0; i < markables.getLength(); i++) {
            Node markable = markables.item(i);
            String word = markable.getFirstChild().getNodeValue();
            word = StringEscapeUtils.unescapeXml(word);
            // String idString = markable.getAttributes().getNamedItem("id").getNodeValue();
            words.add(word);
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Error reading " + fileName, e);
    }
}

From source file:com.amazonaws.mturk.cmd.GetResults.java

/**
 * Gets the HIT and assignment headers and adds additional rows
 * for each question identifier in a HIT in case the ARG_KVP
 * flag is not set/*from   w  w  w  . j a v a2 s.com*/
 */
private String[] getHeaderRow(HITResults r) {
    if (headerFields == null) {
        headerFields = new ArrayList<String>();

        for (HITProperties.HITField field : HITProperties.HIT_FIELDS) {
            headerFields.add(field.getFieldName());
        }

        for (HITProperties.AssignmentField field : HITProperties.ASSIGNMENT_FIELDS) {
            headerFields.add(field.getFieldName());
        }
    }

    if (!outputAsNameValuePair) {
        headerFields.remove(HITProperties.AssignmentField.Answers.getFieldName());
        // parse question for first hit to write out the header based on the question IDs
        try {
            DOMParser p = new DOMParser();
            p.parse(new InputSource(new StringReader(r.getHIT().getQuestion())));
            Document doc = p.getDocument();
            NodeList nodes = doc.getElementsByTagName("QuestionIdentifier");
            for (int i = 0; i < nodes.getLength(); i++) {
                headerFields
                        .add(resultProcessor.getAnswerPrefix() + nodes.item(i).getFirstChild().getNodeValue());
            }
        } catch (Exception e) {
            log.error("Failed to parse HIT question to produce proper header information: "
                    + e.getLocalizedMessage(), e);
        }
    }

    return headerFields.toArray(new String[] {});
}

From source file:com.sun.socialsite.web.rest.opensocial.ConsumerContextValidator.java

private void initRules(InputStream resourceStream) {

    try {/*from ww  w.  ja  v  a  2s.co m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(resourceStream);
        NodeList nl = doc.getElementsByTagName("rule");
        for (int i = 0; i < nl.getLength(); i++) {
            Rule rule = new Rule((Element) (nl.item(i)));
            rules.add(rule);
        }
    } catch (Exception e) {
        String msg = "Failed to load validator rules";
        log.error(msg, e);
        throw new RuntimeException(msg, e);
    }

}

From source file:com.runwaysdk.request.ClientRequestManager.java

/**
 * Parses an XML document to extract connection information, ultimately creating Connection objects.
 * /*  ww w .j  a va 2  s  . c  o  m*/
 * @param document
 */
private void parseDocument(Document document) {
    NodeList connectionsList = document.getElementsByTagName(CONNECTION_ELEMENT);

    // go through each connection
    for (int i = 0; i < connectionsList.getLength(); i++) {
        Node connection = connectionsList.item(i);
        NodeList connectionData = connection.getChildNodes();

        // get the data for each connection
        String label = null;
        ConnectionLabel.Type type = null;
        String address = null;

        // we have to loop through all child nodes since whitespace
        // counts as a text node
        for (int j = 0; j < connectionData.getLength(); j++) {
            Node data = connectionData.item(j);

            // ignore all \n\t text nodes
            if (data.getNodeType() == Node.TEXT_NODE) {
                continue;
            }

            if (data.getNodeName().equals(LABEL_ELEMENT)) {
                label = data.getTextContent();
            } else if (data.getNodeName().equals(TYPE_ELEMENT)) {
                String typeValue = data.getTextContent();
                type = ConnectionLabel.Type.dereference(typeValue);
            } else if (data.getNodeName().equals(ADDRESS_ELEMENT)) {
                address = data.getTextContent();
            }
        }

        connections.put(label, new ConnectionLabel(label, type, address));
    }
}

From source file:cz.incad.kramerius.k5indexer.IndexDocs.java

private void getDocs(int start) throws Exception {

    _init = true;/*  w ww . jav a  2  s  .  com*/
    docs.clear();

    String urlStr = host + "/select?wt=" + wt + "&q=" + URLEncoder.encode(query, "UTF-8") + "&rows=" + rows
            + "&start=" + (start + initStart);
    if (fl != null) {
        urlStr += "&fl=" + fl;
    }
    logger.log(Level.INFO, "urlStr: {0}", urlStr);

    java.net.URL url = new java.net.URL(urlStr);
    InputStream is;
    StringWriter resp = new StringWriter();
    try {
        is = url.openStream();
    } catch (Exception ex) {
        logger.log(Level.WARNING, "", ex);
        is = url.openStream();
    }

    if (wt.equals("json")) {
        org.apache.commons.io.IOUtils.copy(is, resp, "UTF-8");
        JSONObject json = new JSONObject(resp.toString());
        JSONObject response = json.getJSONObject("response");
        numFound = response.getInt("numFound");
        JSONArray jdocs = response.getJSONArray("docs");
        numDocs = jdocs.length();
        for (int i = 0; i < jdocs.length(); i++) {
            docs.add(jdocs.getJSONObject(i));
        }
    } else {

        Document respDoc = builder.parse(is);
        numFound = Integer.parseInt(respDoc.getElementsByTagName("result").item(0).getAttributes()
                .getNamedItem("numFound").getNodeValue());
        numDocs = respDoc.getElementsByTagName("doc").getLength();
        docs.add(respDoc);
    }

}

From source file:net.frontlinesms.plugins.forms.FormsPluginController.java

/**
 * Fabaris_a.zanchi Static utility method to extract tag contents from a xml
 *
 * @param xmlContent The xml conent//from   w  w  w.  java  2 s .  c om
 * @param tag the specified xml tag we want to fetch contents from
 * @return a List of Strings with the tags' content
 */
public static List<String> getTagContentFromXml(String xmlContent, String tag) throws Exception {
    List<String> ret = new ArrayList<String>();
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(xmlContent));
    org.w3c.dom.Document xmlDoc = docBuilder.parse(inStream);
    xmlDoc.getDocumentElement().normalize();
    if (!tag.equals("client_version")) {
        NodeList nodeList = xmlDoc.getElementsByTagName(tag);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node dataNode = nodeList.item(i);
            Element elem = (Element) dataNode;
            ret.add(elem.getFirstChild().getNodeValue());
        }
    } else {
        // Search for client version not knowing its index
        NodeList dataNode = xmlDoc.getElementsByTagName("data");
        Element dataElem = (Element) dataNode.item(0);
        NodeList allNodes = dataElem.getChildNodes();
        for (int i = 0; i < allNodes.getLength(); i++) {
            if (allNodes.item(i).getNodeName().contains("client_version")) {
                ret.add(allNodes.item(i).getTextContent());
            }
        }
    }
    return ret;
}

From source file:canreg.client.dataentry.Import.java

/**
 *
 * @param doc// w  w  w.  j a va 2 s  .  c  om
 * @param lineElements
 * @return
 */
public static List<Relation> constructRelations(Document doc, String[] lineElements) {
    LinkedList<Relation> list = new LinkedList();
    NodeList nl = doc.getElementsByTagName(namespace + "variable");
    String[] variableNames = canreg.common.Tools.getVariableNames(doc, namespace);
    for (int i = 0; i < lineElements.length; i++) {
        boolean found = false;
        int j = 0;
        while (!found && j < variableNames.length) {
            found = lineElements[i].equalsIgnoreCase(variableNames[j++]);
        }
        //build relation
        Relation rel = new Relation();
        rel.setFileVariableName(lineElements[i]);
        rel.setFileColumnNumber(i);
        if (found) {
            //backtrack
            j--;
            Element e = (Element) nl.item(j);
            rel.setDatabaseTableName(e.getElementsByTagName(namespace + "table").item(0).getTextContent());
            rel.setDatabaseTableVariableID(Integer
                    .parseInt(e.getElementsByTagName(namespace + "variable_id").item(0).getTextContent()));
            rel.setVariableType(e.getElementsByTagName(namespace + "variable_type").item(0).getTextContent());
            rel.setDatabaseVariableName(variableNames[j]);
        } else {
            rel.setDatabaseTableName("");
            rel.setDatabaseTableVariableID(-1);
            rel.setVariableType("");
            rel.setDatabaseVariableName("");
        }
        list.add(rel);
    }
    return list;
}