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:com.vmware.identity.samlservice.Shared.java

/**
 * Method to convert Element to String/*from  w ww  .  j ava  2  s .  co m*/
 *
 * @param e
 * @return
 */
public static String getStringFromElement(Element e) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        e.normalize();
        prettyPrint(e, baos);
        return baos.toString("UTF-8");
    } catch (Exception ex) {
        return null;
    }
}

From source file:Main.java

private static void removeEmptyChildElements(Element parentElement) {
    List<Element> toRemove = new LinkedList<Element>();

    NodeList children = parentElement.getChildNodes();
    int childrenCount = children.getLength();
    for (int i = 0; i < childrenCount; ++i) {
        Node child = children.item(i);
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            Element childElement = (Element) child;
            removeEmptyChildElements(childElement);
            if (elementIsRedundant(childElement)) {
                toRemove.add(childElement);
            }/* ww  w.  ja v a2  s  .  c o  m*/
        }
    }

    for (Element childElement : toRemove) {
        parentElement.removeChild(childElement);
    }
    parentElement.normalize();
}

From source file:org.kde.necessitas.ministro.MinistroActivity.java

public static double downloadVersionXmlFile(Context c, boolean checkOnly) {
    if (!isOnline(c))
        return -1;
    try {//from www .  j ava  2  s.  co  m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document dom = null;
        Element root = null;
        URLConnection connection = getVersionUrl(c).openConnection();
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        dom = builder.parse(connection.getInputStream());
        root = dom.getDocumentElement();
        root.normalize();
        double version = Double.valueOf(root.getAttribute("latest"));
        if (MinistroService.instance().getVersion() >= version)
            return MinistroService.instance().getVersion();

        if (checkOnly)
            return version;
        String supportedFeatures = null;
        if (root.hasAttribute("features"))
            supportedFeatures = root.getAttribute("features");
        connection = getLibsXmlUrl(c, version + deviceSupportedFeatures(supportedFeatures)).openConnection();
        File file = new File(MinistroService.instance().getVersionXmlFile());
        file.delete();
        FileOutputStream outstream = new FileOutputStream(MinistroService.instance().getVersionXmlFile());
        InputStream instream = connection.getInputStream();
        byte[] tmp = new byte[2048];
        int downloaded;
        while ((downloaded = instream.read(tmp)) != -1)
            outstream.write(tmp, 0, downloaded);

        outstream.close();
        MinistroService.instance().refreshLibraries(false);
        return version;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return -1;
}

From source file:it.polimi.diceH2020.plugin.control.JSonReader.java

private void writeUml(String filePath, String id) {
    File inputFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;/*from  w w w  .  j av a2 s.c  o  m*/
    Document doc = null;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(inputFile);
    } catch (SAXException | ParserConfigurationException | IOException e) {
        e.printStackTrace();
    }

    Element root = doc.getDocumentElement();
    root.normalize();
    NodeList packegedElement = root.getElementsByTagName("packagedElement");

    Node firstPackEl = packegedElement.item(0);
    String deviceId;
    if (firstPackEl.getNodeType() == Node.ELEMENT_NODE) {
        Element pElement = (Element) firstPackEl;
        deviceId = pElement.getAttribute("xmi:id");
    } else {
        System.err.println("NO DEVICE ID IN THE DDSM UML FILE. THE DDSM FILE WILL NOT BE OVERWRITTEN");
        return;
    }

    NodeList nodes = root.getElementsByTagName("DDSM:DdsmVMsCluster");
    Node n = searchElement(nodes, deviceId);

    if (n == null) {
        System.err.println("NO DEVICE ID MATCHING IN THE DDSM UML FILE. THE DDSM FILE WILL NOT BE OVERWRITTEN");
    } else {
        setAttribute(n, INSTANCES, classNumVM.get(id).toString());
        setAttribute(n, GENERIC_SIZE, classTypeVM.get(id));
        setAttribute(n, PROVIDER, provider);

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filePath));
            transformer.transform(source, result);
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.opengamma.web.bundle.BundleParser.java

private void buildAllElements(Document document) {
    Element rootElement = document.getDocumentElement();
    if (isValidRootElement(rootElement)) {
        rootElement.normalize();
        NodeList childNodes = rootElement.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node node = childNodes.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                if (isValidBundleElement(element)) {
                    String idAttr = element.getAttribute(ID_ATTR);
                    if (_elementsByIdMap.get(idAttr) == null) {
                        _elementsByIdMap.put(idAttr, element);
                    } else {
                        throw new OpenGammaRuntimeException(
                                "parsing bundle XML : duplicate id attribute in " + node.getNodeName());
                    }// w  w  w . ja v  a  2 s . c  o  m
                }
            }
        }
    }
}

From source file:com.wandrell.example.swss.test.util.factory.SecureSoapMessages.java

/**
 * Creates a SOAP message with a signature.
 * <p>/*from w ww  .  j  a va2s. com*/
 * A valid SOAP message is required, this will be the message to be signed.
 * 
 * @param pathBase
 *            path to the SOAP message to sign
 * @param privateKeyAlias
 *            alias for the private key
 * @param privateKeyPass
 *            password for the private key
 * @param certificateAlias
 *            alias for the certificate
 * @param keystore
 *            key store for the signing
 * @return a singed SOAP message
 * @throws Exception
 *             if any error occurs during the message creation
 */
public static final SOAPMessage getSignedMessage(final String pathBase, final String privateKeyAlias,
        final String privateKeyPass, final String certificateAlias, final KeyStore keystore) throws Exception {
    Element root = null;
    String BaseURI = new ClassPathResource(pathBase).getURI().toString();
    SOAPMessage soapMessage;
    Base64Converter base64 = new Base64Converter();
    String token;
    Node binaryToken;
    X509Certificate cert;
    PrivateKey privateKey;
    XMLSignature sig;

    soapMessage = getMessageToSign(pathBase);

    // get the private key used to sign, from the keystore
    privateKey = (PrivateKey) keystore.getKey(privateKeyAlias, privateKeyPass.toCharArray());
    cert = (X509Certificate) keystore.getCertificate(certificateAlias);

    // create basic structure of signature
    Document doc = toDocument(soapMessage);

    org.apache.xml.security.Init.init();

    sig = getSignature(doc, BaseURI, cert, privateKey);

    // optional, but better
    root = doc.getDocumentElement();
    root.normalize();
    root.getElementsByTagName("wsse:Security").item(0).appendChild(sig.getElement());

    token = base64.encode(cert.getEncoded());

    binaryToken = root.getElementsByTagName("wsse:BinarySecurityToken").item(0);
    binaryToken.setTextContent(token);

    // write signature to file
    XMLUtils.outputDOMc14nWithComments(doc, System.out);

    return toMessage(doc);
}

From source file:com.k42b3.neodym.Http.java

public Document requestXml(int method, String url, Map<String, String> header, String body, boolean signed)
        throws Exception {
    // request//from   w  w w .  j  a  va  2 s.c o m
    if (header == null) {
        header = new HashMap<String, String>();
    }

    if (!header.containsKey("Accept")) {
        header.put("Accept", "application/xml");
    }

    String responseContent = this.request(method, url, header, body, signed);

    try {
        // parse response
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(responseContent));

        Document doc = db.parse(is);

        Element rootElement = (Element) doc.getDocumentElement();
        rootElement.normalize();

        return doc;
    } catch (SAXException e) {
        String text = responseContent.length() > 32 ? responseContent.substring(0, 32) + "..."
                : responseContent;

        throw new Exception(text);
    }
}

From source file:com.bernardomg.example.swss.test.util.factory.SecureSoapMessages.java

/**
 * Creates a SOAP message with a signature.
 * <p>/*from w  w w .ja  v a  2s . c  o  m*/
 * A valid SOAP message is required, this will be the message to be signed.
 * 
 * @param pathBase
 *            path to the SOAP message to sign
 * @param privateKeyAlias
 *            alias for the private key
 * @param privateKeyPass
 *            password for the private key
 * @param certificateAlias
 *            alias for the certificate
 * @param keystore
 *            key store for the signing
 * @return a singed SOAP message
 * @throws Exception
 *             if any error occurs during the message creation
 */
public static final SOAPMessage getSignedMessage(final String pathBase, final String privateKeyAlias,
        final String privateKeyPass, final String certificateAlias, final KeyStore keystore) throws Exception {
    Element root = null;
    final String BaseURI = new ClassPathResource(pathBase).getURI().toString();
    SOAPMessage soapMessage;
    final Base64Converter base64 = new Base64Converter();
    String token;
    Node binaryToken;
    X509Certificate cert;
    PrivateKey privateKey;
    XMLSignature sig;

    soapMessage = getMessageToSign(pathBase);

    // get the private key used to sign, from the keystore
    privateKey = (PrivateKey) keystore.getKey(privateKeyAlias, privateKeyPass.toCharArray());
    cert = (X509Certificate) keystore.getCertificate(certificateAlias);

    // create basic structure of signature
    final Document doc = toDocument(soapMessage);

    org.apache.xml.security.Init.init();

    sig = getSignature(doc, BaseURI, cert, privateKey);

    // optional, but better
    root = doc.getDocumentElement();
    root.normalize();
    root.getElementsByTagName("wsse:Security").item(0).appendChild(sig.getElement());

    token = base64.encode(cert.getEncoded());

    binaryToken = root.getElementsByTagName("wsse:BinarySecurityToken").item(0);
    binaryToken.setTextContent(token);

    // write signature to file
    XMLUtils.outputDOMc14nWithComments(doc, System.out);

    return toMessage(doc);
}

From source file:com.servoy.extension.install.LibActivationHandler.java

protected void replaceReferencesInJNLP(File jnlp, File libFileToBeRemoved,
        FullLibDependencyDeclaration toActivate) {
    try {//from www  . ja v  a2 s .c  o  m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(new XMLErrorHandler(jnlp.getName()));

        Document doc = db.parse(jnlp);
        Element root = doc.getDocumentElement();
        root.normalize();

        NodeList list;
        if ("jnlp".equals(root.getNodeName())) //$NON-NLS-1$
        {
            list = root.getElementsByTagName("resources"); //$NON-NLS-1$
            if (list != null && list.getLength() == 1 && list.item(0).getNodeType() == Node.ELEMENT_NODE) {
                File appServerDir = new File(installDir, APP_SERVER_DIR);
                Element resourcesNode = (Element) list.item(0);
                boolean replaced1 = findAndReplaceReferences(resourcesNode, "jar", appServerDir, //$NON-NLS-1$
                        libFileToBeRemoved, toActivate);
                boolean replaced2 = findAndReplaceReferences(resourcesNode, "nativelib", appServerDir, //$NON-NLS-1$
                        libFileToBeRemoved, toActivate);

                if (replaced1 || replaced2) {
                    // save back the jnlp file
                    try {
                        writeBackXML(doc, jnlp, doc.getXmlEncoding());
                    } catch (Exception e) {
                        messages.addError("Cannot write back jnlp file (when deactivating lib): " + jnlp); //$NON-NLS-1$ 
                        Debug.error(e);
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.log(msg, e);
    } catch (SAXException e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.log(msg, e);
    } catch (IOException e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.log(msg, e);
    } catch (FactoryConfigurationError e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'. Please report this problem to Servoy."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.error(msg, e);
    }
}

From source file:com.urbancode.terraform.main.Main.java

private TerraformContext parseContext(File xmlFileToRead)
        throws ParserConfigurationException, XmlParsingException, SAXException, IOException {
    TerraformContext result = null;/*from   w  w  w.jav a2s  . c o m*/

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(xmlFileToRead);
    Element rootElement = doc.getDocumentElement();
    rootElement.normalize();

    XmlModelParser parser = new XmlModelParser();
    parser.setPropertyResolver(createResolver());
    result = (TerraformContext) parser.parse(rootElement);

    return result;
}