Example usage for org.w3c.dom Document normalizeDocument

List of usage examples for org.w3c.dom Document normalizeDocument

Introduction

In this page you can find the example usage for org.w3c.dom Document normalizeDocument.

Prototype

public void normalizeDocument();

Source Link

Document

This method acts as if the document was going through a save and load cycle, putting the document in a "normal" form.

Usage

From source file:org.parelon.pskc.XmlManager.java

public void convertXml(String fileIn, String fileOut)
        throws FileNotFoundException, SAXException, IOException, InvalidKeyException, Base64DecodingException,
        NoSuchAlgorithmException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
        BadPaddingException, NoSuchPaddingException, UnsupportedEncodingException, ParserConfigurationException,
        DecoderException, Exception {
    ArrayList<OtpSeed> seeds = new ArrayList<OtpSeed>();

    /**/*from  w w w  .j  av  a2 s .  c  om*/
     * Parserizzazione XML
     */
    FileInputStream fileToConvert = new FileInputStream(fileIn);
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document parsedXml = builder.parse(fileToConvert);
    fileToConvert.close();
    if (parsedXml.hasChildNodes()) {
        int validSerials = 0;
        NodeList keyPackages = parsedXml.getElementsByTagName("KeyPackage");
        for (int i = 0; i < keyPackages.getLength(); i++) {
            Node keyPackageNode = keyPackages.item(i);
            /**
             * Parse PSKC node structure
             */
            String serialNo = ((Element) keyPackageNode).getElementsByTagName("SerialNo").item(0)
                    .getTextContent();

            if (validateSerial(serialNo)) {
                validSerials++;

                OtpSeed validSeed = new OtpSeed();
                validSeed.setSerialNo(serialNo);
                validSeed.setCryptoId(String.format("KR-%06d", validSerials));
                validSeed.setIssuer(issuer);
                validSeed.setKeyId(String.format("%08d", validSerials));
                validSeed.setManufacturer(manufactuer);

                NodeList tempNode = ((Element) keyPackageNode).getElementsByTagName("xenc:CipherValue");
                if (tempNode != null && tempNode.getLength() != 0) {
                    validSeed.setCipherValue(((Element) tempNode.item(0)).getTextContent());
                }
                seeds.add(validSeed);
            }
        }
    }

    /**
     * Creazione del nuovo XML
     */
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    // root elements
    Document doc = docBuilder.newDocument();
    doc.setXmlVersion("1.0");

    Element keyContainer = doc.createElement("KeyContainer");
    doc.appendChild(keyContainer);
    keyContainer.setAttribute("xmlns", "urn:ietf:params:xml:ns:keyprov:pskc");
    keyContainer.setAttribute("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
    keyContainer.setAttribute("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#");
    keyContainer.setAttribute("Version", "1.0");
    keyContainer.setAttribute("ID", "KC0001");

    /**
     * Key Name
     */
    Element encryptionKey = doc.createElement("EncryptionKey");
    keyContainer.appendChild(encryptionKey);
    Element ds_keyName = doc.createElement("ds:KeyName");
    encryptionKey.appendChild(ds_keyName);
    ds_keyName.setTextContent(this.preSharedKeyName);

    /**
     * MAC Method
     */
    Element macMethod = doc.createElement("MACMethod");
    keyContainer.appendChild(macMethod);
    macMethod.setAttribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#hmac-sha1");
    /**
     * Mac Key
     */
    Element macKey = doc.createElement("MACKey");
    macMethod.appendChild(macKey);
    /**
     * EncryptionMethod
     */
    Element encryptionMethod = doc.createElement("xenc:EncryptionMethod");
    macKey.appendChild(encryptionMethod);
    encryptionMethod.setAttribute("Algorithm", "http://www.w3.org/2001/04/xmlenc#aes128-cbc");
    /**
     * xenc:CipherData
     */
    Element xenc_CipherData = doc.createElement("xenc:CipherData");
    macKey.appendChild(xenc_CipherData);
    /**
     * xenc:CipherValue
     */
    Element xenc_CipherValue = doc.createElement("xenc:CipherValue");
    xenc_CipherData.appendChild(xenc_CipherValue);

    /**
     * Passo 1: Criptare la MAC Key
     */
    String macSignature = Base64.encode(crypto.getAesCipheredMacKey());
    xenc_CipherValue.setTextContent(macSignature);

    for (OtpSeed seed : seeds) {
        /**
         * Passo 2: Convertire il dato criptato
         */
        byte[] reCipheredSecretBytes = crypto.convertRsaToAes(seed.getCipherValue());
        seed.setCipherValue(Base64.encode(reCipheredSecretBytes));
        /**
         * Passo 3: Firmare il dato criptato
         */
        byte[] secretSignatureBytes = crypto.signCipheredSecret(reCipheredSecretBytes);
        seed.setValueMac(Base64.encode(secretSignatureBytes));

        /**
         * KeyPackage
         */
        Element keyPackageElement = doc.createElement("KeyPackage");
        keyContainer.appendChild(keyPackageElement);
        /**
         * DeviceInfo
         */
        Element deviceInfoElement = doc.createElement("DeviceInfo");
        keyPackageElement.appendChild(deviceInfoElement);
        /**
         * Manufactuer
         */
        Element manufactuerElement = doc.createElement("Manufactuer");
        manufactuerElement.setTextContent(seed.getManufacturer());
        deviceInfoElement.appendChild(manufactuerElement);
        /**
         * SerialNo
         */
        Element serialNoElement = doc.createElement("SerialNo");
        serialNoElement.setTextContent(seed.getSerialNo());
        deviceInfoElement.appendChild(serialNoElement);
        /**
         * CryptoModuleInfo
         */
        Element cryptoModuleInfoElement = doc.createElement("CryptoModuleInfo");
        keyPackageElement.appendChild(cryptoModuleInfoElement);
        /**
         * ID
         */
        Element idElement = doc.createElement("ID");
        idElement.setTextContent(seed.getCryptoId());
        cryptoModuleInfoElement.appendChild(idElement);
        /**
         * Key
         */
        Element keyElement = doc.createElement("Key");
        keyPackageElement.appendChild(keyElement);
        keyElement.setAttribute("Id", seed.getKeyId());
        if (seed.getType().equals("TOTP")) {
            keyElement.setAttribute("Algorithm", "urn:ietf:params:xml:ns:keyprov:pskc:totp");
        } else if (seed.getType().equals("HOTP")) {
            keyElement.setAttribute("Algorithm", "urn:ietf:params:xml:ns:keyprov:pskc:hotp");
        } else {
            throw new Exception("OTP type not supported");
        }

        /**
         * Issuer
         */
        Element issuerElement = doc.createElement("Issuer");
        issuerElement.setTextContent(seed.getIssuer());
        keyElement.appendChild(issuerElement);
        /**
         * AlgorithmParameters
         */
        Element algorithmParametersElement = doc.createElement("AlgorithmParameters");
        keyElement.appendChild(algorithmParametersElement);
        /**
         * ResponseFormat
         */
        Element responseFormatElement = doc.createElement("ResponseFormat");
        algorithmParametersElement.appendChild(responseFormatElement);
        responseFormatElement.setAttribute("Length", seed.getLength());
        responseFormatElement.setAttribute("Encoding", seed.getEncoding());
        /**
         * Data
         */
        Element dataElement = doc.createElement("Data");
        keyElement.appendChild(dataElement);
        /**
         * Secret
         */
        Element secretElement = doc.createElement("Secret");
        dataElement.appendChild(secretElement);
        /**
         * EncryptedValue
         */
        Element encryptedValueElement = doc.createElement("EncryptedValue");
        secretElement.appendChild(encryptedValueElement);
        /**
         * xenc:EncryptionMethod
         */
        Element encryptionMethodElement = doc.createElement("xenc:EncryptionMethod");
        encryptedValueElement.appendChild(encryptionMethodElement);
        encryptionMethodElement.setAttribute("Algorithm", "http://www.w3.org/2001/04/xmlenc#aes128-cbc");
        /**
         * xenc:CipherData
         */
        Element cipherDataElement = doc.createElement("xenc:CipherData");
        encryptedValueElement.appendChild(cipherDataElement);
        /**
         * xenc:CipherValue
         */
        Element cipherValueElement = doc.createElement("xenc:CipherValue");
        cipherValueElement.setTextContent(seed.getCipherValue());
        cipherDataElement.appendChild(cipherValueElement);
        /**
         * ValueMAC
         */
        Element valueMACElement = doc.createElement("ValueMAC");
        valueMACElement.setTextContent(seed.getValueMac());
        secretElement.appendChild(valueMACElement);
        /**
         * Counter
         */
        Element counterElement = doc.createElement("Counter");
        dataElement.appendChild(counterElement);
        /**
         * PlainValue
         */
        Element counterPlainValueElement = doc.createElement("PlainValue");
        counterPlainValueElement.setTextContent(seed.getCounter());
        counterElement.appendChild(counterPlainValueElement);
        /**
         * TimeInterval
         */
        Element timeIntervalElement = doc.createElement("TimeInterval");
        dataElement.appendChild(timeIntervalElement);
        /**
         * PlainValue
         */
        Element timeIntervalPlainValueElement = doc.createElement("PlainValue");
        timeIntervalPlainValueElement.setTextContent(seed.getTimeInterval());
        timeIntervalElement.appendChild(timeIntervalPlainValueElement);
        /**
         * Time
         */
        Element timeElement = doc.createElement("Time");
        dataElement.appendChild(timeElement);
        /**
         * PlainValue
         */
        Element timePlainValueElement = doc.createElement("PlainValue");
        timePlainValueElement.setTextContent(seed.getTime());
        timeElement.appendChild(timePlainValueElement);
    }

    doc.normalizeDocument();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    DOMSource source = new DOMSource(doc);

    StreamResult result = new StreamResult(new File(fileOut));
    transformer.transform(source, result);
}

From source file:org.wso2.carbon.automation.engine.configurations.AutomationConfigurationReader.java

private static Document readConfigurationXmlDocument() throws Exception {
    File fXmlFile = new File(
            FrameworkPathUtil.getSystemResourceLocation() + FrameworkConstants.CONFIGURATION_FILE_NAME);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

    //remove all comments from the content of the automation.xml
    dbFactory.setIgnoringComments(true);
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document xmlDocument = dBuilder.parse(fXmlFile);

    //remove all text(empty) elements
    removeText(xmlDocument);/*w w w.j av  a2 s . c o  m*/
    xmlDocument.normalizeDocument();
    return xmlDocument;
}

From source file:org.xwoot.wikiContentManager.XWikiSwizzleClient.XwikiSwizzleClient.java

public static Document toXmlStatic(String pageId, String href, Map<String, String> pageMap)
        throws WikiContentManagerException {
    if (pageMap == null) {
        return null;
    }//from w  w  w.j av a2s  .  com
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new WikiContentManagerException(e);
    }

    Document document = builder.newDocument();

    // Proprits du DOM
    document.setXmlVersion("1.0");
    document.setXmlStandalone(true);

    // Cration de l'arborescence du DOM
    Element racine = document.createElement(XML_NODE_NAME_XWIKIPAGE);
    racine.setAttribute(XML_ATTRIBUTE_NAME_XWIKIPAGEID, pageId);
    racine.setAttribute(XML_ATTRIBUTE_NAME_HREF, href);
    Element entries = document.createElement(XML_NODE_NAME_ENTRIES);

    Iterator i = pageMap.entrySet().iterator();
    Element entry = null;
    Element key = null;
    Element value = null;

    while (i.hasNext()) {
        Entry k = (Entry) i.next();

        entry = document.createElement(XML_NODE_NAME_ENTRY);

        key = document.createElement(XML_NODE_NAME_ENTRY_KEY);
        key.appendChild(document.createTextNode((String) k.getKey()));
        entry.appendChild(key);

        value = document.createElement(XML_NODE_NAME_ENTRY_VALUE);
        value.appendChild(document.createTextNode((String) k.getValue()));
        entry.appendChild(value);

        entries.appendChild(entry);
    }
    racine.appendChild(entries);
    document.appendChild(racine);
    document.normalizeDocument();
    return document;

}

From source file:org.xwoot.wikiContentManager.XWikiSwizzleClient.XwikiSwizzleClient.java

public static Document PageListToXmlStatic(String pagesHRef, List<String> list)
        throws WikiContentManagerException {
    if (list != null) {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;/* w w  w .j av a 2  s .  c  o  m*/
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new WikiContentManagerException(e);
        }

        Document document = builder.newDocument();

        // Proprits du DOM
        document.setXmlVersion("1.0");
        document.setXmlStandalone(true);

        // Cration de l'arborescence du DOM
        Element racine = document.createElement(WikiContentManager.XML_NODE_NAME_XWIKIPAGELIST);
        racine.setAttribute(WikiContentManager.XML_ATTRIBUTE_NAME_LISTSIZE, String.valueOf(list.size()));

        Iterator i = list.iterator();
        Element page = null;

        while (i.hasNext()) {
            String k = (String) i.next();

            page = document.createElement(WikiContentManager.XML_NODE_NAME_XWIKIPAGE);
            page.setAttribute(WikiContentManager.XML_ATTRIBUTE_NAME_XWIKIPAGEID, k);
            page.setAttribute(WikiContentManager.XML_ATTRIBUTE_NAME_HREF, pagesHRef + "/" + k);
            racine.appendChild(page);
        }
        document.appendChild(racine);
        document.normalizeDocument();
        return document;
    }
    return null;
}