Example usage for org.w3c.dom Element normalize

List of usage examples for org.w3c.dom Element normalize

Introduction

In this page you can find the example usage for org.w3c.dom Element normalize.

Prototype

public void normalize();

Source Link

Document

Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

Usage

From source file:Main.java

License:asdf

public static void main(String[] args) throws Exception {
    String initial = "<root><param value=\"abc\"/><param value=\"bc\"/></root>";
    ByteArrayInputStream is = new ByteArrayInputStream(initial.getBytes());
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(is);//from w  w  w . j  a  v a2s  . com

    // Create the new xml fragment
    Text a = doc.createTextNode("asdf");
    Node p = doc.createElement("parameterDesc");
    p.appendChild(a);
    Node i = doc.createElement("insert");
    i.appendChild(p);
    Element r = doc.getDocumentElement();
    r.insertBefore(i, r.getFirstChild());
    r.normalize();

    // Format the xml for output
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    // initialize StreamResult with File object to save to file
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);

    System.out.println(result.getWriter().toString());

}

From source file:ValidateLicenseHeaders.java

/**
 * ValidateLicenseHeaders jboss-src-root
 * /*from w  w  w. j a  v  a  2s  . c om*/
 * @param args
 */
public static void main(String[] args) throws Exception {
    if (args.length == 0 || args[0].startsWith("-h")) {
        log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root");
        System.exit(1);
    }
    int rootArg = 0;
    if (args.length == 2) {
        if (args[0].startsWith("-add"))
            addDefaultHeader = true;
        else {
            log.severe("Uknown argument: " + args[0]);
            log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root");
            System.exit(1);

        }
        rootArg = 1;
    }

    File jbossSrcRoot = new File(args[rootArg]);
    if (jbossSrcRoot.exists() == false) {
        log.info("Src root does not exist, check " + jbossSrcRoot.getAbsolutePath());
        System.exit(1);
    }

    URL u = Thread.currentThread().getContextClassLoader()
            .getResource("META-INF/services/javax.xml.parsers.DocumentBuilderFactory");
    System.err.println(u);

    // Load the valid copyright statements for the licenses
    File licenseInfo = new File(jbossSrcRoot, "varia/src/etc/license-info.xml");
    if (licenseInfo.exists() == false) {
        log.severe("Failed to find the varia/src/etc/license-info.xml under the src root");
        System.exit(1);
    }
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = factory.newDocumentBuilder();
    Document doc = db.parse(licenseInfo);
    NodeList licenses = doc.getElementsByTagName("license");
    for (int i = 0; i < licenses.getLength(); i++) {
        Element license = (Element) licenses.item(i);
        String key = license.getAttribute("id");
        ArrayList headers = new ArrayList();
        licenseHeaders.put(key, headers);
        NodeList copyrights = license.getElementsByTagName("terms-header");
        for (int j = 0; j < copyrights.getLength(); j++) {
            Element copyright = (Element) copyrights.item(j);
            copyright.normalize();
            String id = copyright.getAttribute("id");
            // The id will be blank if there is no id attribute
            if (id.length() == 0)
                continue;
            String text = getElementContent(copyright);
            if (text == null)
                continue;
            // Replace all duplicate whitespace and '*' with a single space
            text = text.replaceAll("[\\s*]+", " ");
            if (text.length() == 1)
                continue;

            text = text.toLowerCase().trim();
            // Replace any copyright date0-date1,date2 with copyright ...
            text = text.replaceAll(COPYRIGHT_REGEX, "...");
            LicenseHeader lh = new LicenseHeader(id, text);
            headers.add(lh);
        }
    }
    log.fine(licenseHeaders.toString());

    File[] files = jbossSrcRoot.listFiles(dotJavaFilter);
    log.info("Root files count: " + files.length);
    processSourceFiles(files, 0);

    log.info("Processed " + totalCount);
    log.info("Updated jboss headers: " + jbossCount);
    // Files with no headers details
    log.info("Files with no headers: " + noheaders.size());
    FileWriter fw = new FileWriter("NoHeaders.txt");
    for (Iterator iter = noheaders.iterator(); iter.hasNext();) {
        File f = (File) iter.next();
        fw.write(f.getAbsolutePath());
        fw.write('\n');
    }
    fw.close();

    // Files with unknown headers details
    log.info("Files with invalid headers: " + invalidheaders.size());
    fw = new FileWriter("InvalidHeaders.txt");
    for (Iterator iter = invalidheaders.iterator(); iter.hasNext();) {
        File f = (File) iter.next();
        fw.write(f.getAbsolutePath());
        fw.write('\n');
    }
    fw.close();

    // License usage summary
    log.info("Creating HeadersSummary.txt");
    fw = new FileWriter("HeadersSummary.txt");
    for (Iterator iter = licenseHeaders.entrySet().iterator(); iter.hasNext();) {
        Map.Entry entry = (Map.Entry) iter.next();
        String key = (String) entry.getKey();
        fw.write("+++ License type=" + key);
        fw.write('\n');
        List list = (List) entry.getValue();
        Iterator jiter = list.iterator();
        while (jiter.hasNext()) {
            LicenseHeader lh = (LicenseHeader) jiter.next();
            fw.write('\t');
            fw.write(lh.id);
            fw.write(", count=");
            fw.write("" + lh.count);
            fw.write('\n');
        }
    }
    fw.close();
}

From source file:client.QueryLastFm.java

License:asdf

public static void main(String[] args) throws Exception {

    // isAlreadyInserted("asdfs","jas,jnjkah");

    // FileWriter fw = new FileWriter(".\\tracks.csv");
    OutputStream track_os = new FileOutputStream(".\\tracks.csv");
    PrintWriter out = new PrintWriter(new OutputStreamWriter(track_os, "UTF-8"));

    OutputStream track_id_os = new FileOutputStream(".\\track_id_sim_track_id.csv");
    PrintWriter track_id_out = new PrintWriter(new OutputStreamWriter(track_id_os, "UTF-8"));

    track_id_out.print("");

    ByteArrayInputStream input;/*from ww  w.ja  v a 2 s . c o  m*/
    Document doc = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();

    String trackName = "";
    String artistName = "";
    String sourceMbid = "";
    out.print("ID");// first row first column
    out.print(",");
    out.print("TrackName");// first row second column
    out.print(",");
    out.println("Artist");// first row third column

    track_id_out.print("source");// first row second column
    track_id_out.print(",");
    track_id_out.println("target");// first row third column
    // track_id_out.print(",");
    // track_id_out.println("type");// first row third column

    // out.flush();

    // out.close();

    // fw.close();

    // os.close();

    try {
        URI uri = new URIBuilder().setScheme("http").setHost("ws.audioscrobbler.com").setPath("/2.0/")
                .setParameter("method", "track.getsimilar").setParameter("artist", "cher")
                .setParameter("track", "believe").setParameter("limit", "100")
                .setParameter("api_key", "88858618961414f8bec919bddd057044").build();

        // new URIBuilder().
        HttpGet request = new HttpGet(uri);

        // request.
        // This is useful for last.fm logging and preventing them from blocking this client
        request.setHeader(HttpHeaders.USER_AGENT,
                "nileshmore@gatech.edu - ClassAssignment at GeorgiaTech Non-commercial use");

        HttpGet httpGet = new HttpGet(
                "http://ws.audioscrobbler.com/2.0/?method=track.getsimilar&artist=cher&track=believe&limit=4&api_key=88858618961414f8bec919bddd057044");
        CloseableHttpResponse response = httpclient.execute(request);

        int statusCode = response.getStatusLine().getStatusCode();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            if (statusCode == 200) {
                HttpEntity entity1 = response.getEntity();
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));
                Document document = builder.parse((response.getEntity().getContent()));
                Element root = document.getDocumentElement();
                root.normalize();
                // Need to focus and resolve this part
                NodeList nodes;
                nodes = root.getChildNodes();

                nodes = root.getElementsByTagName("track");
                if (nodes.getLength() == 0) {
                    // System.out.println("empty");
                    return;
                }
                Node trackNode;
                for (int k = 0; k < nodes.getLength(); k++) // can access all tracks now
                {
                    trackNode = nodes.item(k);
                    NodeList trackAttributes = trackNode.getChildNodes();

                    // check if mbid is present in track attributes
                    // System.out.println("Length  " + (trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0));

                    if ((trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0)) {
                        if (((Element) trackAttributes.item(5)).hasChildNodes())
                            ;// System.out.println("Go aHead");
                        else
                            continue;
                    } else
                        continue;

                    for (int n = 0; n < trackAttributes.getLength(); n++) {
                        Node attribute = trackAttributes.item(n);
                        if ((attribute.getNodeName().compareToIgnoreCase("name")) == 0) {
                            // System.out.println(((Element)attribute).getFirstChild().getNodeValue());
                            trackName = ((Element) attribute).getFirstChild().getNodeValue(); // make string encoding as UTF-8 ************ 

                        }

                        if ((attribute.getNodeName().compareToIgnoreCase("mbid")) == 0) {
                            // System.out.println(n +  "   " +  ((Element)attribute).getFirstChild().getNodeValue());
                            sourceMbid = attribute.getFirstChild().getNodeValue();

                        }

                        if ((attribute.getNodeName().compareToIgnoreCase("artist")) == 0) {
                            NodeList ArtistNodeList = attribute.getChildNodes();
                            for (int j = 0; j < ArtistNodeList.getLength(); j++) {
                                Node Artistnode = ArtistNodeList.item(j);
                                if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) {
                                    // System.out.println(((Element)Artistnode).getFirstChild().getNodeValue());
                                    artistName = ((Element) Artistnode).getFirstChild().getNodeValue();
                                }
                            }
                        }
                    }
                    out.print(sourceMbid);
                    out.print(",");
                    out.print(trackName);
                    out.print(",");
                    out.println(artistName);
                    // out.print(",");
                    findSimilarTracks(track_id_out, sourceMbid, trackName, artistName);

                }
                track_id_out.flush();

                out.flush();
                out.close();
                track_id_out.close();
                track_os.close();

                // fw.close();
                Element trac = (Element) nodes.item(0);
                // trac.normalize();
                nodes = trac.getChildNodes();
                // System.out.println(nodes.getLength());

                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    // System.out.println(node.getNodeName());
                    if ((node.getNodeName().compareToIgnoreCase("name")) == 0) {
                        // System.out.println(((Element)node).getFirstChild().getNodeValue());
                    }

                    if ((node.getNodeName().compareToIgnoreCase("mbid")) == 0) {
                        // System.out.println(((Element)node).getFirstChild().getNodeValue());
                    }

                    if ((node.getNodeName().compareToIgnoreCase("artist")) == 0) {

                        // System.out.println("Well");
                        NodeList ArtistNodeList = node.getChildNodes();
                        for (int j = 0; j < ArtistNodeList.getLength(); j++) {
                            Node Artistnode = ArtistNodeList.item(j);
                            if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) {
                                /* System.out.println(((Element)Artistnode).getFirstChild().getNodeValue());*/
                            }
                            /*System.out.println(Artistnode.getNodeName());*/
                        }
                    }

                }
                /*if(node instanceof Element){
                  //a child element to process
                  Element child = (Element) node;
                  String attribute = child.getAttribute("width");
                }*/

                // System.out.println(root.getAttribute("status"));
                NodeList tracks = root.getElementsByTagName("track");
                Element track = (Element) tracks.item(0);
                // System.out.println(track.getTagName());
                track.getChildNodes();

            } else {
                System.out.println("failed with status" + response.getStatusLine());
            }
            // input = (ByteArrayInputStream)entity1.getContent();
            // do something useful with the response body
            // and ensure it is fully consumed
        } finally {
            response.close();
        }
    }

    finally {
        System.out.println("Exited succesfully.");
        httpclient.close();

    }
}

From source file:Main.java

/**
 * Get the text content of an element. If the element contains
 * mixed content (both elements and text), only the first text section
 * is returned./*from  ww  w. j av a2 s.com*/
 *
 * @param element target element to retrieve text on, cannot be null.
 * @return text content of the element.
 */
public static String getElementText(Element element) {
    element.normalize();
    NodeList list = element.getChildNodes();
    int len = list.getLength();

    for (int i = 0; i < len; i++) {
        Node n = list.item(i);

        if (n.getNodeType() == Node.TEXT_NODE) {
            String s = n.getNodeValue();

            if (s != null) {
                return s.trim();
            }
        }
    }
    return null;
}

From source file:Main.java

public static String textInElement(Element elem) {
    StringBuilder buf = new StringBuilder(100);
    elem.normalize();
    NodeList nlst = elem.getChildNodes();
    for (int i = 0, nlen = nlst.getLength(); i < nlen; i++) {
        Node n = nlst.item(i);/* w  w w.j a v a 2 s . c  o  m*/
        if (n instanceof Text) {
            final String data = ((Text) n).getData();
            buf.append(data);
        }
    }
    return buf.toString();
}

From source file:Main.java

public static String getTextContent(Element element) {
    StringBuilder buffer = new StringBuilder();

    element.normalize();
    NodeList children = element.getChildNodes();
    for (int i = 0, n = children.getLength(); i < n; i++) {
        Node child = children.item(i);
        if (child.getNodeType() == Node.TEXT_NODE) {
            buffer.append(child.getNodeValue());
        }/*ww w .j  a v  a2 s.  c om*/
    }

    return buffer.toString().trim();
}

From source file:Main.java

/**
 * get the  text string in an element (eg interspersed between child elements), 
 * or "" if there is none or if the Element is null.
 * Tries to ignore white space text; but does not succeed.
 *//*from w  w  w . j  a v  a 2 s.co  m*/
public static String getText(Element el) {
    String res = "";
    if (el != null)
        try {
            el.normalize(); // does not help recognise white space
            NodeList nodes = el.getChildNodes();
            for (int i = 0; i < nodes.getLength(); i++)
                if (nodes.item(i) instanceof Text) {
                    Text text = (Text) nodes.item(i);
                    // this filter seems to make no difference
                    if (!text.isElementContentWhitespace()) {
                        String tData = text.getData();
                        // this seems to be an effective way to catch pure white space
                        StringTokenizer nonWhiteSpace = new StringTokenizer(tData, "\n \t");
                        if (nonWhiteSpace.countTokens() > 0)
                            res = res + tData;
                    }
                }
        } catch (Exception e) {
            System.out.println("Text failure: " + e.getMessage());
        }
    return res;
}

From source file:Main.java

private final static String getElement(String filePath, String key) throws Exception {

    String value = null;//from ww w  .j a v a 2s  . co  m

    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        File xmlFile = new File(filePath);

        Document document = documentBuilder.parse(xmlFile);

        Element resourcesElement = document.getDocumentElement();
        resourcesElement.normalize();

        NodeList strings = resourcesElement.getChildNodes();

        int stringsCount = strings.getLength();

        for (int i = 0; i < stringsCount; i++) {

            Node node = strings.item(i);

            short nodeType = node.getNodeType();

            if (nodeType == Node.ELEMENT_NODE) {

                Element element = (Element) node;

                String attribute = element.getAttribute("name");

                if (attribute.equals(key)) {

                    value = element.getTextContent();
                }
            }
        }

    } catch (Exception ex) {

        throw ex;
    }

    return value;
}

From source file:Main.java

public static void setElementTextValue(Element e, String text, boolean cdata) {
    Document root = e.getOwnerDocument();
    e.normalize();
    if (e.hasChildNodes()) {
        NodeList nl = e.getChildNodes();

        /* This suxx: NodeList Object is changed when removing children !!!
           I will store all nodes that should be deleted in a Vector and delete them afterwards */
        int length = nl.getLength();

        List<Node> v = new ArrayList<Node>(nl.getLength());
        for (int i = 0; i < length; i++)
            if (nl.item(i) instanceof CharacterData)
                v.add(nl.item(i));// w w w.ja  v a2  s .  c  o m
        for (Node n : v)
            e.removeChild(n);
    }

    if (cdata) {
        e.appendChild(root.createCDATASection(text));
    } else {
        e.appendChild(root.createTextNode(text));
    }
}

From source file:Main.java

public static Element loadDocument(Reader target) {
    Document doc = null;//ww  w . j  a v  a  2  s .c om
    try {
        InputSource xmlInp = new InputSource(target);

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser = docBuilderFactory.newDocumentBuilder();
        doc = parser.parse(xmlInp);
        Element root = doc.getDocumentElement();
        root.normalize();
        return root;
    } catch (SAXParseException err) {
        System.err.println("URLMappingsXmlDAO ** Parsing error" + ", line " + err.getLineNumber() + ", uri "
                + err.getSystemId());
        System.err.println("URLMappingsXmlDAO error: " + err.getMessage());
    } catch (SAXException e) {
        System.err.println("URLMappingsXmlDAO error: " + e);
    } catch (java.net.MalformedURLException mfx) {
        System.err.println("URLMappingsXmlDAO error: " + mfx);
    } catch (java.io.IOException e) {
        System.err.println("URLMappingsXmlDAO error: " + e);
    } catch (Exception pce) {
        System.err.println("URLMappingsXmlDAO error: " + pce);
    }
    return null;
}