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:bemap.OsmAPI.java

public ArrayList<OsmNode> getOSMSegments(double lat, double lon) throws Exception {

    ArrayList<OsmNode> OsmNodeList = new ArrayList<>();

    double left = lon - NODE_SEARCH_RADIUS;
    double bottom = lat - NODE_SEARCH_RADIUS;
    double right = lon + NODE_SEARCH_RADIUS;
    double top = lat + NODE_SEARCH_RADIUS;

    String url = DOMAIN + "/api/0.6/map?bbox=" + String.format("%.10f", left) + ","
            + String.format("%.10f", bottom) + "," + String.format("%.10f", right) + ","
            + String.format("%.10f", top);

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("User-Agent", USER_AGENT);

    int responseCode = con.getResponseCode();
    if (SERVER_DEBUG)
        BeMapEditor.mainWindow.append("Sending 'GET' request to URL : " + url + "\n");

    if (SERVER_DEBUG)
        BeMapEditor.mainWindow.append("Response Code : " + responseCode + "\n");

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;/* w  w  w  .ja v  a  2 s  .co m*/
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    String xml = response.toString();

    //if(SERVER_DEBUG) BeMapEditor.mainWindow.append(xml);

    Document doc = loadXMLFromString(xml);
    NodeList nList = doc.getElementsByTagName("node");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);

        //System.out.println("\nCurrent Element :" + nNode.getNodeName());

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            Element eElement = (Element) nNode;

            //System.out.println(eElement.getAttribute("id"));
            //System.out.println(eElement.getAttribute("lat"));
            //System.out.println(eElement.getAttribute("lon"));

            NodeList childList = eElement.getChildNodes();

            for (int i = 0; i < childList.getLength(); i++) {
                Node childNode = childList.item(i);

                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element child = (Element) childNode;

                    if ("highway".equals(child.getAttribute("k"))) {
                        double lat1 = Double.parseDouble(eElement.getAttribute("lat"));
                        double lon1 = Double.parseDouble(eElement.getAttribute("lon"));
                        long id = Long.parseLong(eElement.getAttribute("id"));

                        OsmNode s = new OsmNode(id, lat1, lon1);
                        OsmNodeList.add(s);

                        //for debug
                        /*
                        MapMarkerDot m = new MapMarkerDot(lat1,lon1);
                        BeMapEditor.mainWindow.getMap().addMapMarker(m);
                        m.setVisible(true);
                        */
                    }
                }
            }
        }
    }

    return OsmNodeList;
}

From source file:com.axelor.csv.script.PrepareCsv.java

/**
 * Method to generate csv files//  w ww.  ja  va2  s. c o m
 * @param xmlDir 
 * @param csvDir
 */
public void prepareCsv(String xmlDir, String csvDir) {
    List<String> ignoreType = Arrays.asList("one-to-one", "many-to-many", "one-to-many");
    try {
        if (xmlDir != null && csvDir != null) {
            File xDir = new File(xmlDir);
            File cDir = new File(csvDir);
            List<String[]> blankData = new ArrayList<String[]>();
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            if (xDir.isDirectory() && cDir.isDirectory()) {
                for (File xf : xDir.listFiles()) {
                    LOG.info("Processing XML: " + xf.getName());
                    List<String> fieldList = new ArrayList<String>();
                    Document doc = dBuilder.parse(xf);
                    NodeList nList = doc.getElementsByTagName("module");
                    String module = nList.item(0).getAttributes().getNamedItem("name").getNodeValue();
                    nList = doc.getElementsByTagName("entity");
                    if (nList != null) {
                        NodeList fields = nList.item(0).getChildNodes();
                        Integer count = 0;
                        String csvFileName = module + "_" + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL,
                                xf.getName().replace(".xml", ".csv"));
                        while (count < fields.getLength()) {
                            Node field = fields.item(count);
                            NamedNodeMap attrs = field.getAttributes();
                            String type = field.getNodeName();
                            if (attrs != null && attrs.getNamedItem("name") != null
                                    && !ignoreType.contains(type)) {
                                String fieldName = attrs.getNamedItem("name").getNodeValue();
                                if (type.equals("many-to-one")) {
                                    String[] objName = attrs.getNamedItem("ref").getNodeValue().split("\\.");
                                    String refName = objName[objName.length - 1];
                                    String nameColumn = getNameColumn(xmlDir + "/" + refName + ".xml");
                                    if (nameColumn != null)
                                        fieldList.add(fieldName + "." + nameColumn);
                                    else {
                                        fieldList.add(fieldName);
                                        LOG.error("No name column found for " + refName + ", field '"
                                                + attrs.getNamedItem("name").getNodeValue() + "'");
                                    }
                                } else
                                    fieldList.add(fieldName);
                            }

                            count++;
                        }
                        CsvTool.csvWriter(csvDir, csvFileName, ';', StringUtils.join(fieldList, ",").split(","),
                                blankData);
                        LOG.info("CSV file prepared: " + csvFileName);
                    }
                }

            } else
                LOG.error("XML and CSV paths must be directory");
        } else
            LOG.error("Please input XML and CSV directory path");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.kiva.KivaKatch.LenderLoans.java

/**
 * /*w w  w.  java  2s  . c  o m*/
 * @param name
 * @throws LenderLoansCreationException
 */
public LenderLoans(String name) throws LenderLoansCreationException {
    Log.i("KivaKatch", "Construting a new Lender");
    this.loans = new ArrayList<LenderLoansItem>();

    // Process the parameters
    String url = KivaAPI.getLenderLoansURL(name);

    // Create an instance of HttpClient
    HttpClient client = new DefaultHttpClient();

    // What we are actually requesting
    HttpGet getRequest = new HttpGet(url);

    try {
        // Perform the request
        Log.i("KivaKatch", "Requesting: " + url);
        HttpResponse response = client.execute(getRequest);

        // Get the input stream from the response
        InputStream input = response.getEntity().getContent();

        // Build the XML document
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(input);

        // We are concerned with the list of lenders.
        NodeList listOfLoans = doc.getElementsByTagName("loan");

        Log.i("KivaKatch", "Total Loans: " + listOfLoans.getLength());

        // Loop through the list of lenders
        for (int s = 0; s < listOfLoans.getLength(); s++) {
            Node loan = listOfLoans.item(s);
            if (loan.getNodeType() == Node.ELEMENT_NODE) {
                LenderLoansItem l = new LenderLoansItem();
                l.setId(this.getXMLDataFrom(loan, "id"));
                l.setName(this.getXMLDataFrom(loan, "name"));
                l.setStatus(this.getXMLDataFrom(loan, "status"));
                this.loans.add(l);
            }
        }
    } catch (Exception e) {
        // For now we just log the exception.
        Log.e("KivaKatch", e.getMessage());
        throw new LenderLoansCreationException("LenderLoans could not be retreived", e);
    }
}

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

/**
 * Fabaris_a.zanchi Method to remove empty groups for outgoing messages so
 * that mobile tool doesn't crash/*  ww  w  .j  a  v a  2 s  .com*/
 *
 * @param content an xml document (just xml without any additional content)
 * @return xml document without empty groups with attribute
 * appearance="field-list"
 * @throws Exception
 */
public static String removeEmptyGroups(String content) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(content));
    org.w3c.dom.Document xmlDoc = docBuilder.parse(inStream);
    xmlDoc.getDocumentElement().normalize();
    NodeList groupList = xmlDoc.getElementsByTagName("group");
    int i = 0;
    while (i < groupList.getLength()) {
        Element group = (Element) groupList.item(i);
        if (group.getAttribute("appearance").equals("field-list")) {
            if (group.getChildNodes().getLength() == 0) {
                groupList.item(i).getParentNode().removeChild(groupList.item(i));
                i--;
            }
            if (group.getTextContent().equals(", ")) {
                groupList.item(i).getParentNode().removeChild(groupList.item(i));
                i--;
            }
        }
        i++;
    }
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer trans = tFactory.newTransformer();
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    StringWriter sWriter = new StringWriter();
    Result result = new StreamResult(sWriter);
    trans.transform(new DOMSource(xmlDoc), result);
    String result2 = sWriter.getBuffer().toString();
    System.out.println("---------- remove empty groups ---------");
    System.out.println(result2);
    return result2;
}

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

/**
 * Fabaris_a.zanchi This method inserts the designer software version number
 * in the outgoing xform It also creates an empty tag for the client version
 *
 * @param xmlContent the string representation of the xform
 *///from ww w  .ja  v a  2 s  .  c o m
public static String insertSoftwareVersionNumber(String xmlContent, Form form) throws Exception {
    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();
    Node versionNode = xmlDoc.getElementsByTagName(DefaultComponentDescriptor.DESINGER_VERSION_TAGNAME + "_"
            + DefaultComponentDescriptor.DESIGNER_VERSION_INDEX).item(0);
    if (versionNode != null) {
        versionNode.setTextContent(form.getDesignerVersion());
    }
    /*
     * NodeList nodeList = xmlDoc.getElementsByTagName("h:head"); Node
     * headNode = nodeList.item(0); Node modelNode =
     * xmlDoc.getElementsByTagName("model").item(0); Element newElemDesigner
     * = xmlDoc.createElement("designer_version"); Element newElemClient =
     * xmlDoc.createElement("client_version"); Node newNodeDesigner = (Node)
     * newElemDesigner; Node newNodeClient = (Node) newElemClient; String
     * designerVersion = form.getDesignerVersion(); if (designerVersion ==
     * null) designerVersion = "";
     * newNodeDesigner.appendChild(xmlDoc.createTextNode(designerVersion));
     * newNodeClient.appendChild(xmlDoc.createTextNode(""));
     * headNode.insertBefore(newNodeDesigner, modelNode);
     * headNode.insertBefore(newNodeClient, modelNode);
     */
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer trans = tFactory.newTransformer();
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    StringWriter sWriter = new StringWriter();
    Result result = new StreamResult(sWriter);
    trans.transform(new DOMSource(xmlDoc), result);
    String result2 = sWriter.getBuffer().toString();
    System.out.println("-------- inserting version ------------");
    System.out.println(result2);
    return result2;
}

From source file:com.titankingdoms.dev.titanchat.util.update.Update.java

public String check() {
    try {/*from  w ww .j  a v  a2  s.  c  o m*/
        URL url = new URL(rss);

        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openStream());
        doc.getDocumentElement().normalize();

        Node node = doc.getElementsByTagName("item").item(0);

        if (node.getNodeType() == 1) {
            Node name = ((Element) node).getElementsByTagName("title").item(0);
            Node version = name.getChildNodes().item(0);
            newVersion = version.getNodeValue().replaceAll("[^\\d\\.]", "");

        } else {
            newVersion = currentVersion;
        }

    } catch (Exception e) {
        newVersion = currentVersion;
    }

    return newVersion;
}

From source file:fr.aliasource.webmail.server.proxy.client.http.AttachmentsMetadataMethod.java

public AttachmentMetadata[] getMetadata(String[] attachementId) {
    StringBuilder ids = new StringBuilder(attachementId.length * 20);
    for (int i = 0; i < attachementId.length; i++) {
        if (i > 0) {
            ids.append(',');
        }/*  ww  w.java  2  s.  c  o  m*/
        ids.append(attachementId[i]);
    }
    Map<String, String> params = new HashMap<String, String>();
    params.put("token", token);
    params.put("ids", ids.toString());

    logger.info("loading ids: " + ids.toString());

    Document doc = execute(params);

    AttachmentMetadata[] ret = new AttachmentMetadata[attachementId.length];
    NodeList n = doc.getElementsByTagName("att");

    for (int i = 0; i < attachementId.length; i++) {
        Element e = (Element) n.item(i);
        ret[i] = new AttachmentMetadata(attachementId[i]);
        ret[i].setFileName(e.getAttribute("filename"));
        ret[i].setSize(Long.parseLong(e.getAttribute("size")));
        ret[i].setMime(e.getAttribute("mime"));
        ret[i].setWithPreview("true".equals(e.getAttribute("preview")));
        ret[i].setPreviewMime("preview-mime");
    }
    return ret;
}

From source file:mk.finki.ranggo.aggregator.ContentsAggregatorImpl.java

private static void fetchPersonDetailsFromDbpedia(Person person) {
    String url = person.getDbpediaUrl();
    url = url.replace("http://dbpedia.org/resource/", "http://dbpedia.org/data/")
            .replace("http://dbpedia.org/page/", "http://dbpedia.org/data/");
    url += ".xml";

    try {/*from   w  ww  .  j a  v a 2  s. com*/
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(url);
        //System.out.println(getStringFromDocument(document));

        //extract abstract (short biography)
        NodeList abstracts = document.getElementsByTagName("dbo:abstract");
        for (int i = 0; i < abstracts.getLength(); i++) {
            Element entity = (Element) abstracts.item(i);
            if (entity.hasAttribute("xml:lang") && entity.getAttribute("xml:lang").equals("en")) {
                String dbAbstract = entity.getTextContent().replaceAll("&#39;", "'").replaceAll("&lt;", "<")
                        .replaceAll("&gt;", ">").replaceAll("&amp;", "&").replaceAll("", "-");
                person.setShortBio(dbAbstract);
            }
        }

        //extract thumbnail (picture url)
        NodeList thumbnails = document.getElementsByTagName("dbo:thumbnail");
        for (int i = 0; i < thumbnails.getLength(); i++) {
            Element entity = (Element) thumbnails.item(i);
            if (entity.hasAttribute("rdf:resource")) {
                String dbThumbnail = entity.getAttribute("rdf:resource");
                person.setPictureUrl(dbThumbnail);
            }
        }
    } catch (ParserConfigurationException exception) {
    } catch (SAXException exception) {
    } catch (IOException exception) {
    }
}

From source file:org.urbanstew.SoundCloudBase.SoundCloudMainActivity.java

public void requestCompleted(HttpResponse response) {
    String userName = null;/*from  www  . jav a2s.  co m*/

    if (response.getStatusLine().getStatusCode() == 200)
        try {

            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();

            Document dom = db.parse(response.getEntity().getContent());

            userName = dom.getElementsByTagName("username").item(0).getFirstChild().getNodeValue();
        } catch (Exception e) {
            e.printStackTrace();
        }

    final String finalUserName = userName;
    runOnUiThread(new Runnable() {
        public void run() {
            setUserName(finalUserName);
        }
    });
}

From source file:Servlet.Cancel.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w  w w  .  j  av  a 2s . co m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {

        String eventUrl = request.getParameter("eventUrl");
        System.out.print(eventUrl);

        String valid = "valid";

        OAuthConsumer consumer = new DefaultOAuthConsumer("test6-40942", "oQ4q4oBiv9y4jPr7");
        URL url = new URL(eventUrl);
        HttpURLConnection requestUrl = (HttpURLConnection) url.openConnection();
        consumer.sign(requestUrl);
        requestUrl.connect();

        GetResponse gr = new GetResponse();
        gr.validateUrl(valid);

        String result = null;
        StringBuilder sb = new StringBuilder();
        requestUrl.setRequestMethod("GET");
        BufferedReader br = new BufferedReader(new InputStreamReader(requestUrl.getInputStream()));
        String inputLine = "";
        while ((inputLine = br.readLine()) != null) {
            sb.append(inputLine);
        }

        result = sb.toString();

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(result));

        //parsing elements by name tags from event url
        Document doc = builder.parse(src);
        String creatorName = doc.getElementsByTagName("fullName").item(0).getTextContent();
        String companyName = doc.getElementsByTagName("name").item(0).getTextContent();
        String edition = doc.getElementsByTagName("editionCode").item(0).getTextContent();
        String returnUrl = doc.getElementsByTagName("returnUrl").item(0).getTextContent();

        System.out.print(creatorName);
        System.out.print(companyName);
        System.out.print(edition);
        System.out.print(returnUrl);

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost xmlResponse = new HttpPost(returnUrl);
        StringEntity input = new StringEntity(
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><result><success>true</success><message>Account change successful</message>");
        input.setContentType("text/xml");
        xmlResponse.setEntity(input);
        httpClient.execute(xmlResponse);

    } catch (OAuthMessageSignerException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthExpectationFailedException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthCommunicationException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    }
}