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:edu.cornell.mannlib.semservices.service.impl.LCSHService.java

protected List<String> getConceptURIFromXML(String rdf) {
    List<String> uris = new ArrayList<String>();
    String conceptUri = new String();
    try {//w  ww  .  j av a  2 s . c o m
        Document doc = XMLUtils.parse(rdf);
        NodeList nodes = doc.getElementsByTagName("search:result");
        int len = nodes.getLength();
        int i;
        for (i = 0; i < len; i++) {
            Node node = nodes.item(i);
            NamedNodeMap attrs = node.getAttributes();
            Attr idAttr = (Attr) attrs.getNamedItem("uri");
            conceptUri = idAttr.getTextContent();
            log.debug("concept uri is " + conceptUri);
            uris.add(conceptUri);
        }

    } catch (IOException e) {
        log.error("error occurred in parsing " + rdf, e);
    } catch (SAXException e) {
        log.error("error occurred in parsing " + rdf, e);
    } catch (ParserConfigurationException e) {
        log.error("error occurred in parsing " + rdf, e);

    }
    return uris;

}

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

public String getObjXml(String xml) {
    try {/*from  www .j a v  a 2 s.  co  m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
        NodeList timestampList = doc.getElementsByTagName("metric_timestamp");
        for (int i = 0; i < timestampList.getLength(); i++) {
            Element ts = (Element) timestampList.item(i);
            String tsLangType = ts.getTextContent();
            try {
                long millis = 0;
                millis = Long.parseLong(tsLangType);
                Date udate = new Date(millis * 1000);
                String timestamp = DateFormatUtils.ISO_DATETIME_FORMAT.format(udate);
                ts.setTextContent(timestamp);
            } catch (NumberFormatException e) {

            }
        }
        String rs = xmlToString(doc);
        return rs;

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

From source file:ac.ucy.cs.spdx.service.SpdxViolationAnalysis.java

@POST
@Path("/correct/")
@Consumes(MediaType.TEXT_PLAIN)/*from w  ww. ja  va 2s . co  m*/
@Produces(MediaType.TEXT_XML)
public Response correctSpdx(String jsonString) throws Exception {

    ObjectMapper mapper = new ObjectMapper();
    JsonNode fileNode = null;
    try {
        fileNode = mapper.readTree(jsonString);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String fileName = fileNode.get("filename").toString();
    fileName = fileName.substring(1, fileName.length() - 1);

    final String LICENSE_HTML = "http://spdx.org/licenses/";

    String contentXML = fileNode.get("content").toString();
    contentXML = StringEscapeUtils.unescapeXml(contentXML);
    contentXML = contentXML.substring(1, contentXML.length() - 1);

    String newDeclared = fileNode.get("declared").toString();
    newDeclared = newDeclared.substring(1, newDeclared.length() - 1);

    String fullpath = ParseRdf.parseToRdf(fileName, contentXML);
    setLastCorrected(fullpath);

    File xmlFile = new File(fullpath);

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(xmlFile);

    if (doc.getElementsByTagName("licenseDeclared").item(0).getAttributes()
            .getNamedItem("rdf:resource") == null) {
        Element e = (Element) doc.getElementsByTagName("licenseDeclared").item(0);
        e.setAttribute("rdf:resource", LICENSE_HTML + newDeclared);
    } else {
        doc.getElementsByTagName("licenseDeclared").item(0).getAttributes().getNamedItem("rdf:resource")
                .setNodeValue(LICENSE_HTML + newDeclared);
    }

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);

    PrintWriter writer = new PrintWriter(xmlFile);
    writer.print("");
    writer.close();

    StreamResult result = new StreamResult(xmlFile);

    transformer.transform(source, result);

    ResponseBuilder response = Response.ok((Object) xmlFile);
    response.header("Content-Disposition", "attachment; filename=" + fileName);
    return response.build();// {"filename":"anomos","declared":"Apache-2.0","content":""}

}

From source file:com.commonsware.android.service.WeatherPlusService.java

List<Forecast> buildForecasts(String raw) throws Exception {
    List<Forecast> forecasts = new ArrayList<Forecast>();
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(raw)));
    NodeList times = doc.getElementsByTagName("start-valid-time");

    for (int i = 0; i < times.getLength(); i++) {
        Element time = (Element) times.item(i);
        Forecast forecast = new Forecast();

        forecasts.add(forecast);//from  w ww . j a  v a  2 s  .  c o  m
        forecast.setTime(time.getFirstChild().getNodeValue());
    }

    NodeList temps = doc.getElementsByTagName("value");

    for (int i = 0; i < temps.getLength(); i++) {
        Element temp = (Element) temps.item(i);
        Forecast forecast = forecasts.get(i);

        forecast.setTemp(new Integer(temp.getFirstChild().getNodeValue()));
    }

    NodeList icons = doc.getElementsByTagName("icon-link");

    for (int i = 0; i < icons.getLength(); i++) {
        Element icon = (Element) icons.item(i);
        Forecast forecast = forecasts.get(i);

        forecast.setIcon(icon.getFirstChild().getNodeValue());
    }

    return (forecasts);
}

From source file:at.ait.dme.yuma.server.map.KMLConverterServlet.java

private Document convert(Document kml, AffineTransformation interpolator) {
    // Get all 'coordinates' nodes
    NodeList coordNodes = kml.getElementsByTagName("coordinates");

    StringBuffer sb;//from w  w w.j  a v a2 s.  c  o m
    String[] coords;
    String[] lonlat;
    TransformationResult ir;
    for (int i = 0; i < coordNodes.getLength(); i++) {
        // Construct result coordinate string
        sb = new StringBuffer();

        // Original WGS84 coordinate set: 'lon,lat,alt lon,lat,alt lon,lat,alt ...'
        Node n = coordNodes.item(i);

        // Split into individual WGS84 coordinates: 'lon,lat,alt'
        coords = n.getTextContent().trim().split(" ");

        int lastX = 0;
        int lastY = 0;
        double dist = 0;
        for (int j = 0; j < coords.length; j++) {
            // Split into coordinate values
            lonlat = coords[j].split(",");
            if (lonlat.length > 1) {
                try {
                    // Interpolate
                    ir = interpolator.getXYFromKnownLatLon(
                            new WGS84Coordinate(Double.parseDouble(lonlat[1]), Double.parseDouble(lonlat[0])));

                    // Threshold check: does the distance between this point and 
                    // the last one exceed the threshold? --> Outlier! Don't add
                    dist = Math.sqrt(Math.pow((ir.xy.x - lastX), 2) + Math.pow((ir.xy.y - lastY), 2));
                    if ((j == 0) || (dist < outlierThreshold)) {
                        sb.append(ir.xy.x + "," + ir.xy.y + "\n");
                        lastX = ir.xy.x;
                        lastY = ir.xy.y;
                    }
                } catch (TransformationException e) {
                    // Cannot happen unless interpolator is invalid
                    throw new RuntimeException(e);
                }
            }
        }

        // Replace node
        n.setTextContent(sb.toString());
    }
    return kml;
}

From source file:di.uniba.it.tee2.extraction.TemporalExtractor.java

public TaggedText process(String text) throws Exception {
    Date currentTime = Calendar.getInstance(TimeZone.getDefault()).getTime();
    TaggedText taggedText = new TaggedText();
    text = StringEscapeUtils.escapeXml11(text);
    taggedText.setText(text);//  w w  w .j ava 2  s  . c  o m
    String timemlOutput = heidelTagger.process(text, currentTime);
    taggedText.setTaggedText(timemlOutput);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    org.w3c.dom.Document doc = builder.parse(new InputSource(new StringReader(timemlOutput)));

    StringBuilder sb = new StringBuilder();
    NodeList timemlNodes = doc.getElementsByTagName("TimeML");
    for (int i = 0; i < timemlNodes.getLength(); i++) {
        NodeList childs = timemlNodes.item(i).getChildNodes();
        for (int j = 0; j < childs.getLength(); j++) {
            Node child = childs.item(j);
            if (child.getNodeType() == Node.TEXT_NODE) {
                sb.append(child.getTextContent());
            } else if (child.getNodeName().equals("TIMEX3")) {
                String timeText = child.getTextContent();
                String timeValueString = child.getAttributes().getNamedItem("value").getNodeValue();
                String normalizedTime = null;
                try {
                    normalizedTime = TEEUtils.normalizeTime(timeValueString);
                } catch (Exception ex) {
                    //logger.log(Level.WARNING, "Error to normalize time: ", ex);
                }
                if (normalizedTime != null) {
                    TimeEvent event = new TimeEvent(sb.length(), sb.length() + timeText.length(),
                            normalizedTime);
                    event.setEventString(timeText);
                    taggedText.getEvents().add(event);
                }
                sb.append(timeText);
            }
            //VERBOSE
            //System.out.println(child.getNodeType() + "\t" + child.getNodeName() + "\t" + child.getTextContent());
            //System.out.println();
        }
    }
    taggedText.setText(sb.toString());
    return taggedText;
}

From source file:net.neurowork.cenatic.centraldir.workers.xml.AsociacionXmlImporter.java

private Asociacion importAsociacion(String xmlString, Integer associationCode)
        throws ParserConfigurationException, SAXException, IOException {
    Document doc = XmlParserUtil.createDocumentFromString(xmlString);
    Asociacion ret = null;//  w w w .  ja  va 2  s . co  m
    NodeList nodeLst = doc.getElementsByTagName("association");

    for (int s = 0; s < nodeLst.getLength(); s++) {
        Node fstNode = nodeLst.item(s);
        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
            Element elPDU = (Element) fstNode;
            String code = XmlParserUtil.getAttribute(elPDU, "code");
            String url = XmlParserUtil.getAttribute(elPDU, "url");
            String icon = XmlParserUtil.getAttribute(elPDU, "icon");
            NodeList fstNm = elPDU.getChildNodes();
            String associationName = null;

            if (fstNm.getLength() > 0) {
                associationName = ((Node) fstNm.item(0)).getNodeValue();

                Integer capId = AbstractXmlImporter.getId(code);
                Asociacion association = null;
                try {
                    Collection<Asociacion> associations = asociacionService.findByName(associationName);

                    if (associations != null && associations.size() > 0) {
                        association = associations.iterator().next();
                    } else {
                        association = new Asociacion();
                        association.setName(associationName);
                        association.setUrl(url);
                        association.setIcon(icon);
                        logger.info("Saving Asociacion: " + associationName + " url: " + url + " icon " + icon);
                        asociacionService.save(association);
                    }

                    if (capId != null && capId.equals(associationCode)) {
                        ret = association;
                    }
                } catch (ServiceException e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }
    return ret;
}

From source file:com.google.publicalerts.cap.CapJsonBuilder.java

private JSONObject documentToJsonObject(Document document) throws JSONException {
    JSONObject object = new JSONObject();
    Map<String, Set<String>> repeatedFields = CapUtil.getRepeatedFieldNames();
    toJsonObjectInner((Element) document.getElementsByTagName("alert").item(0), object, repeatedFields);
    return object;
}

From source file:broadwick.Broadwick.java

/**
 * Get a collection of XML elements one for each <model> section.
 * <p>//www. j a  v  a  2 s  .  co m
 * @return a collection of XML elements of each <model>.
 * @throws ParserConfigurationException if the nodes for the configured models cannot be found.
 * @throws SAXException                 if the nodes for the configured models cannot be found.
 * @throws IOException                  if the nodes for the configured models cannot be found.
 */
private NodeList getAllModelConfigurations() throws ParserConfigurationException, SAXException, IOException {
    final DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder docBuilder = xmlFactory.newDocumentBuilder();
    final Document xmlDoc = docBuilder.parse(new InputSource(new StringReader(configXml)));
    return xmlDoc.getElementsByTagName("model");
}

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

public String getObjXml(String xml) {
    try {/*w ww .j a  v  a 2  s. c om*/
        // Create a builder factory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
        NodeList timestampList = doc.getElementsByTagName("metric_timestamp");
        for (int i = 0; i < timestampList.getLength(); i++) {
            Element ts = (Element) timestampList.item(i);
            String tsLangType = ts.getTextContent();
            try {
                long millis = 0;
                millis = Long.parseLong(tsLangType);
                Date udate = new Date(millis * 1000);
                String timestamp = DateFormatUtils.ISO_DATETIME_FORMAT.format(udate);
                ts.setTextContent(timestamp);
            } catch (NumberFormatException e) {

            }
        }
        String rs = xmlToString(doc);
        return rs;

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