Example usage for org.w3c.dom Node appendChild

List of usage examples for org.w3c.dom Node appendChild

Introduction

In this page you can find the example usage for org.w3c.dom Node appendChild.

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:jef.tools.XMLUtils.java

/**
 * ?/*from www.  j  av a2s  .  co  m*/
 * 
 * @param node
 *            
 * @param data
 *            
 * @return DOM
 */
public static Text setText(Node node, String data) {
    Document doc = null;
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        doc = (Document) node;
    } else {
        doc = node.getOwnerDocument();
    }
    clearChildren(node, Node.TEXT_NODE);
    Text t = doc.createTextNode(data);
    node.appendChild(t);
    return t;
}

From source file:com.ironiacorp.persistence.datasource.HibernateConfigurationUtil.java

public void save() {
    NodeList propertiesNodes = config.getElementsByTagName("property");
    Node parentNode = config.getElementsByTagName("session-factory").item(0);

    for (int i = 0; i < propertiesNodes.getLength(); i++) {
        Node propertyNode = propertiesNodes.item(i);

        // Get the property name
        NamedNodeMap attributesNodes = propertyNode.getAttributes();
        Node attributeNode = attributesNodes.getNamedItem("name");
        String property = attributeNode.getNodeValue();

        if (property.equals("connection.driver_class") || property.equals("connection.url")
                || property.equals("connection.username") || property.equals("connection.password")
                || property.equals("dialect") || property.equals("hibernate.connection.datasource")
                || property.equals("hibernate.connection.username")
                || property.equals("hibernate.connection.password")) {
            parentNode.removeChild(propertyNode);
        }//  ww w  .  j av a2s.  c  om
    }

    for (Map.Entry<String, String> property : preferences.entrySet()) {
        if (property.getValue() != null) {
            Element propertyNode = config.createElement("property");
            propertyNode.setAttribute("name", (String) property.getKey());
            // TODO: propertyNode.setTextContent((String) property.getValue());
            parentNode.appendChild(propertyNode);
        }
    }

    try {
        File configFile = new File(contextPath + configFileSufix);
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.transform(new DOMSource(config), new StreamResult(configFile));
    } catch (TransformerConfigurationException tce) {
    } catch (TransformerException te) {
    }

}

From source file:org.guanxi.idp.service.SSOBase.java

/**
 * Adds encrypted assertions to a SAML2 Response
 *
 * @param encryptionCert the X509 certificate to use for encrypting the assertions
 * @param assertionDoc the assertions to encrypt
 * @param responseDoc the SAML2 Response to add the encrypted assertions to
 * @throws GuanxiException if an error occurs
 *///from  w ww . ja va 2  s. c o  m
protected void addEncryptedAssertionsToResponse(X509Certificate encryptionCert, AssertionDocument assertionDoc,
        ResponseDocument responseDoc) throws GuanxiException {
    try {
        PublicKey keyEncryptKey = encryptionCert.getPublicKey();

        // Generate a secret key
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();

        XMLCipher keyCipher = XMLCipher.getInstance(XMLCipher.RSA_OAEP);
        keyCipher.init(XMLCipher.WRAP_MODE, keyEncryptKey);

        Document domAssertionDoc = (Document) assertionDoc.newDomNode(xmlOptions);
        EncryptedKey encryptedKey = keyCipher.encryptKey(domAssertionDoc, secretKey);

        Element elementToEncrypt = domAssertionDoc.getDocumentElement();

        XMLCipher xmlCipher = XMLCipher.getInstance(XMLCipher.AES_128);
        xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);

        // Add KeyInfo to the EncryptedData element
        EncryptedData encryptedDataElement = xmlCipher.getEncryptedData();
        KeyInfo keyInfo = new KeyInfo(domAssertionDoc);
        keyInfo.add(encryptedKey);
        encryptedDataElement.setKeyInfo(keyInfo);

        // Encrypt the assertion
        xmlCipher.doFinal(domAssertionDoc, elementToEncrypt, false);

        // Go back into XMLBeans land...
        EncryptedDataDocument encryptedDataDoc = EncryptedDataDocument.Factory.parse(domAssertionDoc);
        // ...and add the encrypted assertion to the response
        responseDoc.getResponse().addNewEncryptedAssertion()
                .setEncryptedData(encryptedDataDoc.getEncryptedData());

        // Look for the Response/EncryptedAssertion/EncryptedData/KeyInfo/EncryptedKey node...
        EncryptedDataType encryptedData = responseDoc.getResponse().getEncryptedAssertionArray(0)
                .getEncryptedData();
        NodeList nodes = encryptedData.getKeyInfo().getDomNode().getChildNodes();
        Node encryptedKeyNode = null;
        for (int c = 0; c < nodes.getLength(); c++) {
            encryptedKeyNode = nodes.item(c);
            if (encryptedKeyNode.getLocalName() != null) {
                if (encryptedKeyNode.getLocalName().equals("EncryptedKey"))
                    break;
            }
        }

        // ...get a new KeyInfo ready...
        KeyInfoDocument keyInfoDoc = KeyInfoDocument.Factory.newInstance();
        X509DataType x509Data = keyInfoDoc.addNewKeyInfo().addNewX509Data();

        // ...and a useable version of the SP's encryption certificate...
        StringWriter sw = new StringWriter();
        PEMWriter pemWriter = new PEMWriter(sw);
        pemWriter.writeObject(encryptionCert);
        pemWriter.close();
        String x509 = sw.toString();
        x509 = x509.replaceAll("-----BEGIN CERTIFICATE-----", "");
        x509 = x509.replaceAll("-----END CERTIFICATE-----", "");

        // ...add the encryption cert to the new KeyInfo...
        x509Data.addNewX509Certificate().setStringValue(x509);

        // ...and insert it into Response/EncryptedAssertion/EncryptedData/KeyInfo/EncryptedKey
        encryptedKeyNode.appendChild(
                encryptedKeyNode.getOwnerDocument().importNode(keyInfoDoc.getKeyInfo().getDomNode(), true));
    } catch (NoSuchAlgorithmException nsae) {
        logger.error("AES encryption not available");
        throw new GuanxiException(nsae);
    } catch (XMLEncryptionException xea) {
        logger.error("RSA_OAEP error with WRAP_MODE");
        throw new GuanxiException(xea);
    } catch (Exception e) {
        logger.error("Error encyrpting the assertion");
        throw new GuanxiException(e);
    }
}

From source file:jef.tools.XMLUtils.java

/**
 * ?? //  w  w w.  j  ava  2  s  . co  m
 * 
 * <pre>
 *    &lt;parent&gt;
 *       &lt;a&gt;text-a&lt;/a&gt;
 *       &lt;c&gt;text-c&lt;/c&gt;
 *    &lt;/parent&gt;
 * </pre>
 * 
 * {@code addElementBefore(c,"b","text-b")}c?c 
 * 
 * <pre>
 *     &lt;parent&gt;
 *       &lt;a&gt;text-a&lt;/a&gt;
 *       &lt;b&gt;text-b&lt;/b&gt;
 *       &lt;c&gt;text-c&lt;/c&gt;
 *    &lt;/parent&gt;
 * </pre>
 * 
 * @param node
 *            DOM
 * @param tagName
 *            ??
 * @param nodeText
 *            
 * @return Element
 */
public static Element addElementBefore(Node node, String tagName, String... nodeText) {
    Node pNode = node.getParentNode();
    List<Node> movingNodes = new ArrayList<Node>();
    for (Node n : toArray(pNode.getChildNodes())) {
        if (n == node) {
            movingNodes.add(n);
        } else if (movingNodes.size() > 0) {
            movingNodes.add(n);
        }
    }
    Element e = addElement(pNode, tagName, nodeText);
    for (Node n : movingNodes) {
        pNode.appendChild(n);
    }
    return e;
}

From source file:jef.tools.XMLUtils.java

/**
 * ??/* w ww .  java  2s.  co m*/
 * 
 * @param node
 *            DOM
 * @param tagName
 *            ??
 * @param nodeText
 *            
 * @return Element
 */
public static Element addElementAfter(Node node, String tagName, String... nodeText) {
    Node pNode = node.getParentNode();
    List<Node> movingNodes = new ArrayList<Node>();
    boolean flag = false;
    for (Node n : toArray(pNode.getChildNodes())) {
        if (flag) {
            movingNodes.add(n);
        } else if (n == node) {
            flag = true;
        }
    }
    Element e = addElement(pNode, tagName, nodeText);
    for (Node n : movingNodes) {
        pNode.appendChild(n);
    }
    return e;
}

From source file:ai.aitia.meme.paramsweep.intellisweepPlugin.JgapGAPlugin.java

public void save(final Node node) {
    final Document document = node.getOwnerDocument();
    final Element pluginElement = (Element) node;
    pluginElement.setAttribute(WizardSettingsManager.CLASS, this.getClass().getName());

    final Element gaSettingsElement = document.createElement(GA_SETTINGS);
    node.appendChild(gaSettingsElement);

    saveGeneralParameters(gaSettingsElement);
    saveSelectors(gaSettingsElement);/*from  ww  w . ja v  a  2 s.  c  o  m*/
    saveOperators(gaSettingsElement);
    saveChromosome(gaSettingsElement);
}

From source file:it.unibas.spicy.persistence.xml.operators.ExportXSD.java

private void processForeignKeyConstraints(IDataSourceProxy dataSource, Node node, Document document) {
    int i = 0;//from   w w  w .  ja v a  2 s.c o m
    String name;
    for (ForeignKeyConstraint fkConstraint : dataSource.getForeignKeyConstraints()) {
        Element keyRefTag;
        i++;
        name = "keyRef" + i;
        keyRefTag = document.createElement(PREFIX + "keyref");
        keyRefTag.setAttribute("name", name);
        if (fkConstraint.getKeyConstraint() == null
                || mapOfKeyConstraints.get(fkConstraint.getKeyConstraint()) == null) {
            throw new IllegalArgumentException(" --- Unable to locate referred key in a foreignKey constraint");
        }

        keyRefTag.setAttribute("refer", mapOfKeyConstraints.get(fkConstraint.getKeyConstraint()));
        Element selectorTag = document.createElement(PREFIX + "selector");
        selectorTag.setAttribute("xpath", ".//" + fkConstraint.getForeignKeyPaths().get(0)
                .getLastNode(dataSource.getIntermediateSchema()).getFather().getLabel());
        keyRefTag.appendChild(selectorTag);

        for (PathExpression pathExpression : fkConstraint.getForeignKeyPaths()) {
            Element fieldTag = document.createElement(PREFIX + "field");
            keyRefTag.appendChild(fieldTag);
            String xpath = "";
            if (pathExpression.getLastNode(dataSource.getIntermediateSchema()) instanceof MetadataNode) {
                xpath = "@";
            }
            xpath += pathExpression.getLastNode(dataSource.getIntermediateSchema()).getLabel();
            fieldTag.setAttribute("xpath", xpath);
        }
        node.appendChild(keyRefTag);
    }
}

From source file:com.krawler.portal.tools.ServiceBuilder.java

public void createBusinessProcessforCRUD(String classname, String companyid) {
    try {//from  w  ww  .  j av a2s .c  o  m
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.parse(new ClassPathResource("logic/businesslogicEx.xml").getFile());
        //Document doc = docBuilder.newDocument();
        NodeList businessrules = doc.getElementsByTagName("businessrules");
        Node businessruleNode = businessrules.item(0);
        Element processEx = doc.getElementById(classname + "_addNew");

        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }

        processEx = doc.getElementById(classname + "_delete");

        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }
        processEx = doc.getElementById(classname + "_edit");
        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }

        Element process = createBasicProcessNode(doc, classname, "createNewRecord", "_addNew", "createNew");
        businessruleNode.appendChild(process);
        process = createBasicProcessNode(doc, classname, "deleteRecord", "_delete", "deleteRec");
        businessruleNode.appendChild(process);
        process = createBasicProcessNode(doc, classname, "editRecord", "_edit", "editRec");
        businessruleNode.appendChild(process);

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://192.168.0.4/dtds/businesslogicEx.dtd");
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        // create string from xml tree
        File outputFile = (new ClassPathResource("logic/businesslogicEx.xml").getFile());
        outputFile.setWritable(true);
        // StringWriter sw = new StringWriter();
        StreamResult sresult = new StreamResult(outputFile);

        DOMSource source = new DOMSource(doc);
        trans.transform(source, sresult);

    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
    }

}

From source file:com.fiorano.openesb.application.aps.Route.java

/**
 *  Returns the xml string equivalent of this object
 *
 * @param document the input Document object
 * @return element node//from   w  ww . j  a  v a 2  s  . c o m
 * @exception FioranoException if an error occurs while creating the element
 *      node.
 */
Node toJXMLString(Document document) throws FioranoException {
    Node root0 = document.createElement("Route");

    ((Element) root0).setAttribute("isP2PRoute", "" + m_isP2PRoute);
    ((Element) root0).setAttribute("isPersistant", "" + m_isPersitant);
    ((Element) root0).setAttribute("isDurable", "" + m_isDurable);
    ((Element) root0).setAttribute("applyTransformationAtSrc", "" + m_applyTransformationAtSrc);

    Node node = null;

    node = XMLDmiUtil.getNodeObject("Name", m_routeName, document);
    if (node != null)
        root0.appendChild(node);

    node = XMLDmiUtil.getNodeObject("RouteGUID", m_routeGUID, document);
    if (node != null)
        root0.appendChild(node);

    node = XMLDmiUtil.getNodeObject("TimeToLive", "" + m_iTimeToLive, document);
    if (node != null)
        root0.appendChild(node);

    node = XMLDmiUtil.getNodeObject("SrcServiceInstance", m_srcServInst, document);
    if (node != null)
        root0.appendChild(node);

    node = XMLDmiUtil.getNodeObject("SrcPort", m_srcPortName, document);
    if (node != null)
        root0.appendChild(node);

    Element child = null;

    if (m_transformationXSL != null) {
        child = document.createElement("TransformationXSL");

        Node pcData = document.createCDATASection(m_transformationXSL);

        child.appendChild(pcData);
        root0.appendChild(child);
    }
    if (m_selectors != null) {
        Iterator itr = m_selectors.keySet().iterator();

        while (itr.hasNext()) {
            child = document.createElement("Selector");

            String type = (String) itr.next();

            child.setAttribute("type", type);

            Object val = m_selectors.get(type);
            String value = null;

            if (val instanceof String) {
                value = (String) m_selectors.get(type);
            } else if (val instanceof XPathDmi) {
                value = ((XPathDmi) val).getXPath();
                HashMap map = ((XPathDmi) val).getNameSpace();

                if (map != null) {
                    Set keys = map.keySet();
                    Iterator iter = keys.iterator();

                    while (iter.hasNext()) {
                        String key = (String) iter.next();
                        String keyval = (String) map.get(key);

                        child.setAttribute("esb_" + key, keyval);
                    }
                }
            }

            Node pcData = document.createTextNode(value);

            child.appendChild(pcData);
            root0.appendChild(child);
        }
    }

    node = XMLDmiUtil.getNodeObject("TgtServiceInstance", m_trgtServInst, document);
    if (node != null)
        root0.appendChild(node);

    node = XMLDmiUtil.getNodeObject("TgtPort", m_trgtPortName, document);
    if (node != null)
        root0.appendChild(node);

    if (!StringUtils.isEmpty(m_longDescription)) {
        node = XMLDmiUtil.getNodeObject("LongDescription", m_longDescription, document);
        if (node != null)
            root0.appendChild(node);
    }
    if (!StringUtils.isEmpty(m_shortDescription)) {
        node = XMLDmiUtil.getNodeObject("ShortDescription", m_shortDescription, document);
        if (node != null)
            root0.appendChild(node);
    }
    if (m_altDestination != null) {
        root0.appendChild(m_altDestination.toJXMLString(document));
    }

    if (m_params != null && m_params.size() > 0) {
        Enumeration enums = m_params.elements();

        while (enums.hasMoreElements()) {
            Param param = (Param) enums.nextElement();
            if (!StringUtils.isEmpty(param.getParamName()) && !StringUtils.isEmpty(param.getParamValue()))
                root0.appendChild(param.toJXMLString(document));
        }
    }

    return root0;
}

From source file:com.bluexml.xforms.controller.mapping.MappingToolCommon.java

protected void addId(Document xformsDocument, Node element, String alfrescoId) {
    if (alfrescoId != null) {
        Element idElement = xformsDocument.createElement(MsgId.INT_INSTANCE_SIDEID.getText());
        idElement.setTextContent(alfrescoId);
        element.appendChild(idElement);
    }//from  w w  w  . j  av  a  2  s.  c om
}