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

public static Element loadDocument(String location) {
    Document doc = null;/*  ww  w . ja  v a2s .  co  m*/
    try {
        URL url = new URL(location);
        InputSource xmlInp = new InputSource(url.openStream());

        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;
}

From source file:Main.java

public static Element loadDocument(File location) {
    Document doc = null;/*from www.  j a va  2 s . co  m*/
    try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser = docBuilderFactory.newDocumentBuilder();
        doc = parser.parse(location);
        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 (MalformedURLException mfx) {
        System.err.println("URLMappingsXmlDAO error: " + mfx);
    } catch (IOException e) {
        System.err.println("URLMappingsXmlDAO error: " + e);
    } catch (Exception pce) {
        System.err.println("URLMappingsXmlDAO error: " + pce);
    }
    return null;
}

From source file:Main.java

public static Element loadDocument(Reader target) {
    Document doc = null;//from   w w  w . jav a  2  s.co  m
    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 (MalformedURLException mfx) {
        System.err.println("URLMappingsXmlDAO error: " + mfx);
    } catch (IOException e) {
        System.err.println("URLMappingsXmlDAO error: " + e);
    } catch (Exception pce) {
        System.err.println("URLMappingsXmlDAO error: " + pce);
    }
    return null;
}

From source file:Main.java

public static Element loadDocument(File location) {
    Document doc = null;/*from w w  w . ja  va 2  s .c o m*/
    try {

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser = docBuilderFactory.newDocumentBuilder();
        doc = parser.parse(location);
        Element root = doc.getDocumentElement();
        root.normalize();
        /*
         * //Output to standard output ; use Sun's reference imple for now
         * XmlDocument xdoc = (XmlDocument) doc; xdoc.write(new
         * OutputStreamWriter(System.out));
         */
        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;
}

From source file:Main.java

/**
 * Return the text (node value) of the first node under this, works best if normalized.
 *//* ww  w  .jav  a2 s  . c  o m*/
public static String elementValue(Element element) {
    if (element == null)
        return null;
    // make sure we get all the text there...
    element.normalize();
    Node textNode = element.getFirstChild();

    if (textNode == null)
        return null;

    StringBuffer valueBuffer = new StringBuffer();
    do {
        if (textNode.getNodeType() == Node.CDATA_SECTION_NODE || textNode.getNodeType() == Node.TEXT_NODE) {
            valueBuffer.append(textNode.getNodeValue());
        }
    } while ((textNode = textNode.getNextSibling()) != null);
    return valueBuffer.toString();
}

From source file:Main.java

public static Element loadDocument(String value, String type) {
    Document doc = null;/*from ww  w  .  ja v  a2  s.  com*/
    InputSource xmlInp = null;
    try {
        if (type.equals("location")) {
            URL url = new URL(value);
            xmlInp = new InputSource(url.openStream());
        } else {
            xmlInp = new InputSource(new StringReader(value));
        }
        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 (MalformedURLException mfx) {
        System.err.println("URLMappingsXmlDAO error: " + mfx);
    } catch (IOException e) {
        System.err.println("URLMappingsXmlDAO error: " + e);
    } catch (Exception pce) {
        System.err.println("URLMappingsXmlDAO error: " + pce);
    }
    return null;
}

From source file:Main.java

/**
 * Return the text (node value) of the first node under this, works best if
 * normalized.// w  w  w  . j  a  v a2  s . co m
 */
public static String elementValue(Element element) {
    if (element == null)
        return null;
    // make sure we get all the text there...
    element.normalize();
    Node textNode = element.getFirstChild();

    if (textNode == null)
        return null;
    // should be of type text
    return textNode.getNodeValue();
}

From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java

/**
* Method used to create an enveloped digital signature for an element of a TAXII document.
*
* @param element the element to be signed
* @param keyEntry the PrivateKeyEntry//  w w w .j a va 2  s.  com
* @param cbIndex the index of the Content_Block if we're signing a Content_Block, otherwise set to -1 if we're signing the root element
* @return the status of the operation
*
* Usage Example:
*   String pks = config.getProperty("pathToPublisherKeyStore");
*    String pksPw = FLAREclientUtil.decrypt(config.getProperty("publisherKeyStorePassword"));
*    String keyName = config.getProperty("publisherKeyName");
*    String keyPW = FLAREclientUtil.decrypt(config.getProperty("publisherKeyPassword"));
*   PrivateKeyEntry keyEntry =  FLAREclientUtil.getKeyEntry(pks, pksPw, keyName, keyPW);
*   List<Integer> statusList = Xmldsig.sign(rootElement, keyEntry, -1);
*/
private static boolean sign(Element element, PrivateKeyEntry keyEntry, int cbIndex) {
    element.normalize();
    boolean status = false;

    //Create XML Signature Factory
    XMLSignatureFactory xmlSigFactory = XMLSignatureFactory.getInstance("DOM");
    PublicKey publicKey = ClientUtil.getPublicKey(keyEntry);
    PrivateKey privateKey = keyEntry.getPrivateKey();
    DOMSignContext dsc = new DOMSignContext(privateKey, element);
    dsc.setDefaultNamespacePrefix("ds");
    dsc.setURIDereferencer(new MyURIDereferencer(element));
    SignedInfo si = null;
    DigestMethod dm = null;
    SignatureMethod sm = null;
    KeyInfo ki = null;
    X509Data xd;
    List<Serializable> x509Content = new ArrayList<>();
    try {
        String algorithm = publicKey.getAlgorithm();
        X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
        x509Content.add(cert.getSubjectX500Principal().getName());
        x509Content.add(cert);
        String algorithmName = cert.getSigAlgName();
        if (algorithm.toUpperCase().contains("RSA")) {
            if (algorithmName.toUpperCase().contains("SHA1")) {
                dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA1, null);
                sm = xmlSigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
            } else if (algorithmName.toUpperCase().contains("SHA2")) {
                dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA256, null);
                sm = xmlSigFactory.newSignatureMethod(RSA_SHA256_URI, null);
            } else {
                logger.error("Error in digital signature application. " + algorithmName + " is not supported.");
            }
            CanonicalizationMethod cm;
            if (cbIndex != -1) {
                cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null);
                String refUri = "#xpointer(//*[local-name()='Content_Block'][" + cbIndex
                        + "]/*[local-name()='Content'][1]/*)";
                List<Reference> references = Collections.singletonList(xmlSigFactory.newReference(refUri, dm));
                si = xmlSigFactory.newSignedInfo(cm, sm, references);
            } else {
                List<Transform> transforms = new ArrayList<>(2);
                transforms.add(xmlSigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
                transforms.add(xmlSigFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
                        (TransformParameterSpec) null));
                cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                        (C14NMethodParameterSpec) null);
                String refUri = "#xpointer(/*)";
                List<Reference> references = Collections
                        .singletonList(xmlSigFactory.newReference(refUri, dm, transforms, null, null));
                si = xmlSigFactory.newSignedInfo(cm, sm, references);
            }
            KeyInfoFactory kif = xmlSigFactory.getKeyInfoFactory();
            xd = kif.newX509Data(x509Content);
            ki = kif.newKeyInfo(Collections.singletonList(xd));
        } else {
            logger.error("Error in digital signature application. " + algorithmName + " is not supported.");
        }
    } catch (NoSuchAlgorithmException ex) {
        logger.error("NoSuchAlgorithm Exception when attempting to digitally sign a document.");
    } catch (InvalidAlgorithmParameterException ex) {
        logger.error("InvalidAlgorithmParameter Exception when attempting to digitally sign a document.");
    }

    // Create a new XML Signature
    XMLSignature signature = xmlSigFactory.newXMLSignature(si, ki);
    try {
        // Sign the document
        signature.sign(dsc);
        status = true;
    } catch (MarshalException ex) {
        logger.error("MarshalException when attempting to digitally sign a document.");
    } catch (XMLSignatureException ex) {
        logger.error("XMLSignature Exception when attempting to digitally sign a document.");
    } catch (Exception e) {
        logger.error("General exception when attempting to digitally sign a document.");
    }
    return status;
}

From source file:org.dataone.proto.trove.mn.http.client.HttpExceptionHandler.java

private static ErrorElements deserializeXml(HttpResponse response) throws IllegalStateException, IOException //    throws NotFound, InvalidToken, ServiceFailure, NotAuthorized,
//    NotFound, IdentifierNotUnique, UnsupportedType,
//    InsufficientResources, InvalidSystemMetadata, NotImplemented,
//    InvalidCredentials, InvalidRequest, IOException {
{
    ErrorElements ee = new ErrorElements();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document doc;//  w ww  .j a va 2  s. c o m

    int httpCode = response.getStatusLine().getStatusCode();
    if (response.getEntity() != null) {
        BufferedInputStream bErrorStream = new BufferedInputStream(response.getEntity().getContent());
        bErrorStream.mark(5000); // good for resetting up to 5000 bytes

        String detailCode = null;
        String description = null;
        String name = null;
        int errorCode = -1;
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(bErrorStream);
            Element root = doc.getDocumentElement();
            root.normalize();
            if (root.getNodeName().equalsIgnoreCase("error")) {
                if (root.hasAttribute("errorCode")) {
                    try {
                        errorCode = Integer.getInteger(root.getAttribute("errorCode"));
                    } catch (NumberFormatException nfe) {
                        System.out.println("errorCode unexpectedly not able to parse to int,"
                                + " using http status for creating exception");
                        errorCode = httpCode;
                    }
                }
                if (errorCode != httpCode) //            throw new ServiceFailure("1000","errorCode in message body doesn't match httpStatus");
                {
                    System.out.println("errorCode in message body doesn't match httpStatus,"
                            + " using errorCode for creating exception");
                }
                if (root.hasAttribute("detailCode")) {
                    detailCode = root.getAttribute("detailCode");
                } else {
                    detailCode = "detail code is Not Set!";
                }
                if (root.hasAttribute("name")) {
                    name = root.getAttribute("name");
                } else {
                    name = "Exception";
                }
                Node child = root.getFirstChild();
                do {
                    if (child.getNodeType() == Node.ELEMENT_NODE) {
                        if (child.getNodeName().equalsIgnoreCase("description")) {
                            Element element = (Element) child;
                            description = element.getTextContent();
                            break;
                        }
                    }
                } while ((child = child.getNextSibling()) != null);
            } else {
                description = domToString(doc);
                detailCode = "detail code was never Set!";
            }
        } catch (TransformerException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        } catch (SAXException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        } catch (IOException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        } catch (ParserConfigurationException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        }

        ee.setCode(errorCode);
        ee.setName(name);
        ee.setDetailCode(detailCode);
        ee.setDescription(description);
    }
    return ee;
}

From source file:client.QueryLastFm.java

License:asdf

public static void findSimilarTracks(PrintWriter track_id_out, String sourceMbid, String trackName,
        String artistName) throws Exception {
    String destMbid;//from  w w  w .j a v a 2  s  .  c o m
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {
        Thread.sleep(50); //1000 milliseconds is one second.
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
    try {
        URI uri = new URIBuilder().setScheme("http").setHost("ws.audioscrobbler.com").setPath("/2.0/")
                .setParameter("method", "track.getsimilar").setParameter("artist", artistName)
                .setParameter("track", trackName).setParameter("limit", "10")
                .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");

        CloseableHttpResponse response = httpclient.execute(request);

        int statusCode = response.getStatusLine().getStatusCode();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        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();

                NodeList mbidList = root.getElementsByTagName("mbid");
                // System.out.println("mbid" + mbidList.getLength());

                for (int n = 0; n < mbidList.getLength(); n++) {
                    Node attribute = mbidList.item(n);
                    if (mbidList.item(n).hasChildNodes()) {
                        if (mbidList.item(n).getParentNode().getNodeName().matches("track")) // to get correct mbid
                        {
                            destMbid = mbidList.item(n).getFirstChild().getNodeValue();
                            // track_id_out.print(sourceMbid);
                            // track_id_out.print(",");
                            // track_id_out.println(destMbid);
                            if (isAlreadyInserted(sourceMbid, destMbid)) //  if not inserted , insert into map
                            {
                                // System.out.println(sourceMbid + "---"  + destMbid);
                                // track_id_out.print(sourceMbid);
                                // track_id_out.print(",");
                                // track_id_out.println(destMbid);
                                // continue;
                            }
                            /*if(isAlreadyInserted(sourceMbid, destMbid))
                            {
                              System.out.println("Ok got the match !!");
                            }*/
                            else {
                                track_id_out.print(sourceMbid);
                                track_id_out.print(",");
                                track_id_out.println(destMbid); //
                                // track_id_out.print(",");
                                // track_id_out.println("Undirected");
                            }
                            // track_id_out.print()
                        }
                    }
                }

            }

        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

}