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:com.twinsoft.convertigo.beans.core.Sequence.java

private static Node cloneNodeWithUserData(Node node, boolean recurse) {
    if (node != null) {
        Object node_output = node.getUserData(Step.NODE_USERDATA_OUTPUT);

        Node clonedNode = node.cloneNode(false);
        clonedNode.setUserData(Step.NODE_USERDATA_OUTPUT, node_output, null);

        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // attributes
            NamedNodeMap attributeMap = clonedNode.getAttributes();
            for (int i = 0; i < attributeMap.getLength(); i++) {
                Node clonedAttribute = attributeMap.item(i);
                String attr_name = clonedAttribute.getNodeName();
                Object attr_output = ((Element) node).getAttributeNode(attr_name)
                        .getUserData(Step.NODE_USERDATA_OUTPUT);
                clonedAttribute.setUserData(Step.NODE_USERDATA_OUTPUT, attr_output, null);
            }//from w ww .  ja  va  2  s . com

            // recurse on element child nodes only
            if (recurse && node.hasChildNodes()) {
                NodeList list = node.getChildNodes();
                for (int i = 0; i < list.getLength(); i++) {
                    Node clonedChild = cloneNodeWithUserData(list.item(i), recurse);
                    if (clonedChild != null) {
                        clonedNode.appendChild(clonedChild);
                    }
                }
            }
        }

        return clonedNode;
    }
    return null;
}

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

public void createModuleDef(ArrayList list, String classname) {
    String result = "";
    try {/* w w w.  j  av  a  2  s. c om*/

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();

        Document doc = docBuilder.parse((new ClassPathResource("logic/moduleEx.xml").getFile()));
        //Document doc = docBuilder.newDocument();
        NodeList modules = doc.getElementsByTagName("modules");
        Node modulesNode = modules.item(0);
        Element module_ex = doc.getElementById(classname);
        if (module_ex != null) {
            modulesNode.removeChild(module_ex);
        }
        Element module = doc.createElement("module");
        Element property_list = doc.createElement("property-list");
        module.setAttribute("class", "com.krawler.esp.hibernate.impl." + classname);
        module.setAttribute("type", "pojo");
        module.setAttribute("id", classname);
        for (int cnt = 0; cnt < list.size(); cnt++) {
            Element propertyNode = doc.createElement("property");
            Hashtable mapObj = (Hashtable) list.get(cnt);

            propertyNode.setAttribute("name", mapObj.get("name").toString());
            propertyNode.setAttribute("type", mapObj.get("type").toString().toLowerCase());
            property_list.appendChild(propertyNode);

        }

        module.appendChild(property_list);
        modulesNode.appendChild(module);
        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/module.dtd");
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        // create string from xml tree
        File outputFile = (new ClassPathResource("logic/moduleEx.xml").getFile());
        outputFile.setWritable(true);
        // StringWriter sw = new StringWriter();
        StreamResult sresult = new StreamResult(outputFile);

        DOMSource source = new DOMSource(doc);
        trans.transform(source, sresult);
        //       result  = sw.toString();

    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
    } finally {
        // System.out.println(result);
        // return result;
    }
}

From source file:com.cloud.hypervisor.kvm.resource.wrapper.LibvirtMigrateCommandWrapper.java

private String replaceStorage(String xmlDesc, Map<String, MigrateCommand.MigrateDiskInfo> migrateStorage)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {
    InputStream in = IOUtils.toInputStream(xmlDesc);

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(in);

    // Get the root element
    Node domainNode = doc.getFirstChild();

    NodeList domainChildNodes = domainNode.getChildNodes();

    for (int i = 0; i < domainChildNodes.getLength(); i++) {
        Node domainChildNode = domainChildNodes.item(i);

        if ("devices".equals(domainChildNode.getNodeName())) {
            NodeList devicesChildNodes = domainChildNode.getChildNodes();

            for (int x = 0; x < devicesChildNodes.getLength(); x++) {
                Node deviceChildNode = devicesChildNodes.item(x);

                if ("disk".equals(deviceChildNode.getNodeName())) {
                    Node diskNode = deviceChildNode;

                    String sourceFileDevText = getSourceFileDevText(diskNode);

                    String path = getPathFromSourceFileDevText(migrateStorage.keySet(), sourceFileDevText);

                    if (path != null) {
                        MigrateCommand.MigrateDiskInfo migrateDiskInfo = migrateStorage.remove(path);

                        NamedNodeMap diskNodeAttributes = diskNode.getAttributes();
                        Node diskNodeAttribute = diskNodeAttributes.getNamedItem("type");

                        diskNodeAttribute.setTextContent(migrateDiskInfo.getDiskType().toString());

                        NodeList diskChildNodes = diskNode.getChildNodes();

                        for (int z = 0; z < diskChildNodes.getLength(); z++) {
                            Node diskChildNode = diskChildNodes.item(z);

                            if ("driver".equals(diskChildNode.getNodeName())) {
                                Node driverNode = diskChildNode;

                                NamedNodeMap driverNodeAttributes = driverNode.getAttributes();
                                Node driverNodeAttribute = driverNodeAttributes.getNamedItem("type");

                                driverNodeAttribute.setTextContent(migrateDiskInfo.getDriverType().toString());
                            } else if ("source".equals(diskChildNode.getNodeName())) {
                                diskNode.removeChild(diskChildNode);

                                Element newChildSourceNode = doc.createElement("source");

                                newChildSourceNode.setAttribute(migrateDiskInfo.getSource().toString(),
                                        migrateDiskInfo.getSourceText());

                                diskNode.appendChild(newChildSourceNode);
                            } else if ("auth".equals(diskChildNode.getNodeName())) {
                                diskNode.removeChild(diskChildNode);
                            } else if ("iotune".equals(diskChildNode.getNodeName())) {
                                diskNode.removeChild(diskChildNode);
                            }//  ww w .  ja va 2s.c o  m
                        }
                    }
                }
            }
        }
    }

    if (!migrateStorage.isEmpty()) {
        throw new CloudRuntimeException(
                "Disk info was passed into LibvirtMigrateCommandWrapper.replaceStorage that was not used.");
    }

    return getXml(doc);
}

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

private void processKeyConstraints(IDataSourceProxy dataSource, Node node, Document document) {
    int i = 0;//from w  ww  .  j a  v  a  2 s.  c  o  m
    String name;
    for (KeyConstraint keyConstraint : dataSource.getKeyConstraints()) {
        Element keyOrUniqueTag;
        i++;
        if (keyConstraint.isPrimaryKey()) {
            name = "key" + i;
            keyOrUniqueTag = document.createElement(PREFIX + "key");
        } else {
            name = "unique" + i;
            keyOrUniqueTag = document.createElement(PREFIX + "unique");
        }
        mapOfKeyConstraints.put(keyConstraint, name);
        keyOrUniqueTag.setAttribute("name", name);

        Element selectorTag = document.createElement(PREFIX + "selector");
        String rootName = dataSource.getIntermediateSchema().getLabel();
        if (logger.isDebugEnabled())
            logger.debug("----->  rootName = " + rootName);
        if (keyConstraint.getKeyPaths().get(0).getLastNode(dataSource.getIntermediateSchema()).getFather()
                .getLabel().equalsIgnoreCase(rootName)) {
            selectorTag.setAttribute("xpath", "./.");
        } else {
            selectorTag.setAttribute("xpath", ".//" + keyConstraint.getKeyPaths().get(0)
                    .getLastNode(dataSource.getIntermediateSchema()).getFather().getLabel());
        }
        keyOrUniqueTag.appendChild(selectorTag);

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

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

public void createModuleDef(com.krawler.utils.json.base.JSONArray jsonData, String classname) {
    String result = "";
    try {//from  w w w  . ja v  a  2  s .co m

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();

        Document doc = docBuilder.parse((new ClassPathResource("logic/moduleEx.xml").getFile()));
        //Document doc = docBuilder.newDocument();
        NodeList modules = doc.getElementsByTagName("modules");
        Node modulesNode = modules.item(0);
        Element module_ex = doc.getElementById(classname);
        if (module_ex != null) {
            modulesNode.removeChild(module_ex);
        }
        Element module = doc.createElement("module");
        Element property_list = doc.createElement("property-list");
        module.setAttribute("class", "com.krawler.esp.hibernate.impl." + classname);
        module.setAttribute("type", "pojo");
        module.setAttribute("id", classname);
        for (int cnt = 0; cnt < jsonData.length(); cnt++) {
            Element propertyNode = doc.createElement("property");
            JSONObject jsonObj = jsonData.optJSONObject(cnt);

            propertyNode.setAttribute("name", jsonObj.optString("varname"));
            propertyNode.setAttribute("type", jsonObj.optString("modulename").toLowerCase());
            property_list.appendChild(propertyNode);

        }

        module.appendChild(property_list);
        modulesNode.appendChild(module);
        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://localhost/dtds/module.dtd");
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        // create string from xml tree
        File outputFile = (new ClassPathResource("logic/moduleEx.xml").getFile());
        outputFile.setWritable(true);
        // StringWriter sw = new StringWriter();
        StreamResult sresult = new StreamResult(outputFile);

        DOMSource source = new DOMSource(doc);
        trans.transform(source, sresult);
        //       result  = sw.toString();

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

From source file:eu.impact_project.iif.tw.gen.DeploymentCreator.java

/**
 * Insert data types/*w ww  .java 2  s  . c  o  m*/
 * @throws GeneratorException 
 */
public void createPom() throws GeneratorException {
    File wsdlTemplate = new File(this.pomAbsPath);
    if (!wsdlTemplate.canRead()) {
        throw new GeneratorException("Unable to read pom.xml template file: " + this.pomAbsPath);
    }
    try {

        DocumentBuilderFactory docBuildFact = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuildFact.newDocumentBuilder();
        doc = docBuilder.parse(this.pomAbsPath);
        NodeList profilesNodes = doc.getElementsByTagName("profiles");
        Node firstProfilesNode = profilesNodes.item(0);
        List<Deployref> dks = service.getDeployto().getDeployref();

        NodeList executionsNode = doc.getElementsByTagName("executions");
        Node thirdExecutionsNode = executionsNode.item(2);

        for (Deployref dk : dks) {
            boolean isDefaultDeployment = dk.isDefault();
            Deployment d = (Deployment) dk.getRef();

            String host = d.getHost();
            String id = d.getId();

            //<profile>
            //    <id>deployment1</id>
            //    <properties>
            //        <tomcat.manager.url>http://localhost:8080/manager</tomcat.manager.url>
            //        <tomcat.user>tomcat</tomcat.user>
            //        <tomcat.password>TxF781!P</tomcat.password>
            //        <war.suffix>deployment1</war.suffix>
            //    </properties>
            //</profile>
            //<profile>
            //    <id>deployment2</id>
            //    <properties>
            //        <tomcat.manager.url>http://localhost:8080/manager</tomcat.manager.url>
            //        <tomcat.user>tomcat</tomcat.user>
            //        <tomcat.password>TxF781!P</tomcat.password>
            //        <war.suffix>deployment2</war.suffix>
            //    </properties>
            //</profile>
            Element profileElm = doc.createElement("profile");

            if (isDefaultDeployment) {
                Element activationElm = doc.createElement("activation");
                Element activeByDefaultElm = doc.createElement("activeByDefault");
                activeByDefaultElm.setTextContent("true");
                activationElm.appendChild(activeByDefaultElm);
                profileElm.appendChild(activationElm);
            }

            firstProfilesNode.appendChild(profileElm);
            Element idElm = doc.createElement("id");
            idElm.setTextContent(d.getId());
            profileElm.appendChild(idElm);
            Element propertiesElm = doc.createElement("properties");
            profileElm.appendChild(propertiesElm);

            List<Port> ports = d.getPorts().getPort();
            String port = "8080";
            String type = "http";
            for (Port p : ports) {
                if (p.getType().equals("http")) {
                    port = String.valueOf(p.getValue());
                    type = p.getType();
                }
            }

            Element tomcatManagerUrlElm = doc.createElement("tomcat.manager.url");
            String managerPath = d.getManager().getPath();
            managerPath = (managerPath != null && !managerPath.isEmpty()) ? managerPath : "manager";
            tomcatManagerUrlElm.setTextContent(type + "://" + d.getHost() + ":" + port + "/" + managerPath);

            propertiesElm.appendChild(tomcatManagerUrlElm);
            Element tomcatUserPropElm = doc.createElement("tomcat.user");
            Manager manager = d.getManager();
            tomcatUserPropElm.setTextContent(manager.getUser());
            propertiesElm.appendChild(tomcatUserPropElm);
            Element tomcatPasswordPropElm = doc.createElement("tomcat.password");
            tomcatPasswordPropElm.setTextContent(manager.getPassword());
            propertiesElm.appendChild(tomcatPasswordPropElm);
            Element warSuffixElm = doc.createElement("war.suffix");
            warSuffixElm.setTextContent(d.getId());
            propertiesElm.appendChild(warSuffixElm);

            //<execution>
            //    <id>package-deployment1</id>
            //    <phase>package</phase>
            //    <configuration>
            //        <classifier>deployment1</classifier>
            //        <webappDirectory>${project.build.directory}/${project.build.finalName}_deployment1</webappDirectory>
            //        <webResources>
            //            <resource>
            //                <directory>src/env/deployment1</directory>
            //            </resource>
            //        </webResources>
            //    </configuration>
            //    <goals>
            //        <goal>war</goal>
            //    </goals>
            //</execution>

            Element executionElm = doc.createElement("execution");
            Element id2Elm = doc.createElement("id");
            id2Elm.setTextContent("package-" + d.getId());
            executionElm.appendChild(id2Elm);
            Element phaseElm = doc.createElement("phase");
            phaseElm.setTextContent("package");
            executionElm.appendChild(phaseElm);
            Element configurationElm = doc.createElement("configuration");
            executionElm.appendChild(configurationElm);
            Element classifierElm = doc.createElement("classifier");
            classifierElm.setTextContent(d.getId());
            configurationElm.appendChild(classifierElm);
            Element webappDirectoryElm = doc.createElement("webappDirectory");
            webappDirectoryElm
                    .setTextContent("${project.build.directory}/${project.build.finalName}_" + d.getId());
            configurationElm.appendChild(webappDirectoryElm);
            Element webResourcesElm = doc.createElement("webResources");
            Element resourceElm = doc.createElement("resource");
            Element directoryElm = doc.createElement("directory");
            directoryElm.setTextContent("src/env/" + d.getId());
            resourceElm.appendChild(directoryElm);
            webResourcesElm.appendChild(resourceElm);
            configurationElm.appendChild(webResourcesElm);
            Element goalsElm = doc.createElement("goals");
            executionElm.appendChild(goalsElm);
            Element goalElm = doc.createElement("goal");
            goalElm.setTextContent("war");
            goalsElm.appendChild(goalElm);
            thirdExecutionsNode.appendChild(executionElm);

            if (isDefaultDeployment) {
                NodeList directories = doc.getElementsByTagName("directory");
                Node directoryNode = directories.item(0);
                directoryNode.setTextContent("src/env/" + d.getId());
            }

            // Create different environment dependent configuration files.
            // Deployment environment dependent files will be stored in
            // src/env and will then be activated by choosing the corresponding
            // profile during the corresponding maven phase.
            // E.g. mvn tomcat:redeploy -P deployment1
            // will replace the deployment dependent files by the ones
            // available under src/env/deployment1.
            String generatedDir = st.getGenerateDir();
            String projMidfix = st.getProjectMidfix();
            String projDir = st.getProjectDirectory();
            String servDir = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId(), "WEB-INF/services",
                    projMidfix, "META-INF");
            FileUtils.forceMkdir(new File(servDir));

            String sxmlFile = FileUtil.makePath(generatedDir, projDir, "src/main/webapp/WEB-INF/services",
                    st.getProjectMidfix(), "META-INF") + "services.xml";

            GenericCode deplDepServXmlCode = new GenericCode(sxmlFile);

            //<parameter name="cliCommand1">${clicmd}</parameter>
            //<parameter name="processingUnit">${tomcat_public_procunitid}</parameter>
            //<parameter name="publicHttpAccessDir">${tomcat_public_http_access_dir}</parameter>
            //<parameter name="publicHttpAccessUrl">${tomcat_public_http_access_url}</parameter>
            //<parameter name="serviceUrlFilter">${service_url_filter}</parameter>
            List<Operation> operations = service.getOperations().getOperation();
            for (Operation operation : operations) {
                String command = operation.getCommand();
                String toolsbasedir = d.getToolsbasedir();
                if (toolsbasedir != null && !toolsbasedir.equals("")) {
                    command = toolsbasedir + command;
                }
                deplDepServXmlCode.put("cli_cmd_" + String.valueOf(operation.getOid()), command);
            }

            deplDepServXmlCode.put("tomcat_public_procunitid", d.getIdentifier());
            Dataexchange de = d.getDataexchange();

            String accessDir = FileUtil.makePath(de.getAccessdir());
            String accessUrl = de.getAccessurl();

            deplDepServXmlCode.put("tomcat_public_http_access_dir", accessDir);
            deplDepServXmlCode.put("tomcat_public_http_access_url", accessUrl);
            // TODO: filter
            //deplDepServXmlCode.put("service_url_filter", );
            deplDepServXmlCode.evaluate();

            deplDepServXmlCode.create(servDir + "services.xml");
            logger.debug("Writing: " + servDir + "services.xml");
            if (isDefaultDeployment) {
                defaultDeplServicesFile = servDir + "services.xml";
                defaultServicesFile = sxmlFile;
            }

            // source
            String htmlIndexSourcePath = FileUtil.makePath(generatedDir, projDir, "src/main", "webapp")
                    + "index.html";
            // substitution
            GenericCode htmlSourceIndexCode = new GenericCode(htmlIndexSourcePath);
            htmlSourceIndexCode.put("service_description", service.getDescription());
            htmlSourceIndexCode.put("tomcat_public_host", d.getHost());
            htmlSourceIndexCode.put("tomcat_public_http_port", port);
            // target
            String htmlIndexDir = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId());
            FileUtils.forceMkdir(new File(htmlIndexDir));
            String htmlIndexTargetPath = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId())
                    + "index.html";
            htmlSourceIndexCode.create(htmlIndexTargetPath);
            if (isDefaultDeployment) {
                this.defaultDeplHtmlFile = htmlIndexTargetPath;
                this.defaultHtmlFile = htmlIndexSourcePath;
            }

            // source
            String wsdlSourcePath = FileUtil.makePath(generatedDir, projDir, "src/main", "webapp")
                    + st.getProjectMidfix() + ".wsdl";
            // substitution
            GenericCode wsdlSourceCode = new GenericCode(wsdlSourcePath);
            wsdlSourceCode.put("tomcat_public_host", d.getHost());
            wsdlSourceCode.put("tomcat_public_http_port", port);
            // target
            String wsdlDir = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId());
            FileUtils.forceMkdir(new File(wsdlDir));
            String wsdlTargetPath = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId())
                    + st.getProjectMidfix() + ".wsdl";
            wsdlSourceCode.create(wsdlTargetPath);
            if (isDefaultDeployment) {
                this.defaultDeplWsdlFile = wsdlTargetPath;
                this.defaultWsdlFile = wsdlSourcePath;
            }
        }
        if (defaultDeplServicesFile != null && !defaultDeplServicesFile.isEmpty()) {
            FileUtils.copyFile(new File(defaultDeplServicesFile), new File(defaultServicesFile));
            FileUtils.copyFile(new File(this.defaultDeplHtmlFile), new File(this.defaultHtmlFile));
            FileUtils.copyFile(new File(this.defaultDeplWsdlFile), new File(this.defaultWsdlFile));
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        DOMSource source = new DOMSource(doc);
        FileOutputStream fos = new FileOutputStream(this.pomAbsPath);
        StreamResult result = new StreamResult(fos);
        transformer.transform(source, result);
        fos.close();
    } catch (Exception ex) {
        logger.error("An exception occurred: " + ex.getMessage());
    }
}

From source file:lcmc.data.VMSXML.java

/** Creates XML for new domain. */
public Node createDomainXML(final String uuid, final String domainName, final Map<String, String> parametersMap,
        final boolean needConsole) {
    //<domain type='kvm'>
    //  <memory>524288</memory>
    //  <name>fff</name>
    //  <os>
    //    <type arch='i686' machine='pc-0.12'>hvm</type>
    //  </os>
    //</domain>

    /* domain type: kvm/xen */
    final String type = parametersMap.get(VM_PARAM_DOMAIN_TYPE);
    final String configName = getConfigName(type, domainName);
    namesConfigsMap.put(domainName, configName);
    /* build xml */
    final String encoding = "UTF-8";
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;/*from   w w w .j a  va  2s  .  co m*/

    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException pce) {
        assert false;
    }
    final Document doc = db.newDocument();
    final Element root = (Element) doc.appendChild(doc.createElement("domain"));
    /* type */
    root.setAttribute("type", type); /* kvm/xen */
    /* uuid */
    final Node uuidNode = (Element) root.appendChild(doc.createElement("uuid"));
    uuidNode.appendChild(doc.createTextNode(uuid));
    /* name */
    final Node nameNode = (Element) root.appendChild(doc.createElement("name"));
    nameNode.appendChild(doc.createTextNode(domainName));
    /* memory */
    final Node memoryNode = (Element) root.appendChild(doc.createElement("memory"));
    final long mem = Tools.convertToKilobytes(parametersMap.get(VM_PARAM_MEMORY));
    memoryNode.appendChild(doc.createTextNode(Long.toString(mem)));
    /* current memory */
    final Node curMemoryNode = (Element) root.appendChild(doc.createElement("currentMemory"));
    final long curMem = Tools.convertToKilobytes(parametersMap.get(VM_PARAM_CURRENTMEMORY));
    curMemoryNode.appendChild(doc.createTextNode(Long.toString(curMem)));
    /* vcpu */
    final String vcpu = parametersMap.get(VM_PARAM_VCPU);
    if (vcpu != null) {
        final Node vcpuNode = (Element) root.appendChild(doc.createElement("vcpu"));
        vcpuNode.appendChild(doc.createTextNode(vcpu));
    }

    /* bootloader */
    final String bootloader = parametersMap.get(VM_PARAM_BOOTLOADER);
    if (bootloader != null) {
        final Node bootloaderNode = (Element) root.appendChild(doc.createElement("bootloader"));
        bootloaderNode.appendChild(doc.createTextNode(bootloader));
    }

    /* os */
    final Element osNode = (Element) root.appendChild(doc.createElement("os"));
    final Element typeNode = (Element) osNode.appendChild(doc.createElement("type"));
    typeNode.appendChild(doc.createTextNode(parametersMap.get(VM_PARAM_TYPE)));
    typeNode.setAttribute("arch", parametersMap.get(VM_PARAM_TYPE_ARCH));
    typeNode.setAttribute("machine", parametersMap.get(VM_PARAM_TYPE_MACHINE));
    final String init = parametersMap.get(VM_PARAM_INIT);
    if (init != null && !"".equals(init)) {
        final Element initNode = (Element) osNode.appendChild(doc.createElement("init"));
        initNode.appendChild(doc.createTextNode(init));
    }
    final Element bootNode = (Element) osNode.appendChild(doc.createElement(OS_BOOT_NODE));
    bootNode.setAttribute(OS_BOOT_NODE_DEV, parametersMap.get(VM_PARAM_BOOT));
    final String bootDev2 = parametersMap.get(VM_PARAM_BOOT_2);
    if (bootDev2 != null && !"".equals(bootDev2)) {
        final Element bootNode2 = (Element) osNode.appendChild(doc.createElement(OS_BOOT_NODE));
        bootNode2.setAttribute(OS_BOOT_NODE_DEV, parametersMap.get(VM_PARAM_BOOT_2));
    }

    final Node loaderNode = (Element) osNode.appendChild(doc.createElement("loader"));
    loaderNode.appendChild(doc.createTextNode(parametersMap.get(VM_PARAM_LOADER)));

    /* features */
    addFeatures(doc, root, parametersMap);

    /* cpu match */
    addCPUMatchNode(doc, root, parametersMap);

    /* on_ */
    final String onPoweroff = parametersMap.get(VM_PARAM_ON_POWEROFF);
    if (onPoweroff != null) {
        final Element onPoweroffNode = (Element) root.appendChild(doc.createElement("on_poweroff"));
        onPoweroffNode.appendChild(doc.createTextNode(onPoweroff));

    }
    final String onReboot = parametersMap.get(VM_PARAM_ON_REBOOT);
    if (onReboot != null) {
        final Element onRebootNode = (Element) root.appendChild(doc.createElement("on_reboot"));
        onRebootNode.appendChild(doc.createTextNode(onReboot));

    }
    final String onCrash = parametersMap.get(VM_PARAM_ON_CRASH);
    if (onCrash != null) {
        final Element onCrashNode = (Element) root.appendChild(doc.createElement("on_crash"));
        onCrashNode.appendChild(doc.createTextNode(onCrash));

    }
    /* devices / emulator */
    final String emulator = parametersMap.get(VM_PARAM_EMULATOR);
    if (emulator != null || needConsole) {
        final Element devicesNode = (Element) root.appendChild(doc.createElement("devices"));
        if (needConsole) {
            final Element consoleNode = (Element) devicesNode.appendChild(doc.createElement("console"));
            consoleNode.setAttribute("type", "pty");
        }
        final Element emulatorNode = (Element) devicesNode.appendChild(doc.createElement("emulator"));
        emulatorNode.appendChild(doc.createTextNode(emulator));
    }
    return root;
}

From source file:lcmc.data.VMSXML.java

/** Add CPU match node. */
private void addCPUMatchNode(final Document doc, final Node root, final Map<String, String> parametersMap) {
    final String cpuMatch = parametersMap.get(VM_PARAM_CPU_MATCH);
    final Element cpuMatchNode = (Element) root.appendChild(doc.createElement("cpu"));
    if (!"".equals(cpuMatch)) {
        cpuMatchNode.setAttribute("match", cpuMatch);
    }//from w ww .j  av a  2  s .c  om
    final String model = parametersMap.get(VM_PARAM_CPUMATCH_MODEL);
    if (!"".equals(model)) {
        final Node modelNode = (Element) cpuMatchNode.appendChild(doc.createElement("model"));
        modelNode.appendChild(doc.createTextNode(model));
    }
    final String vendor = parametersMap.get(VM_PARAM_CPUMATCH_VENDOR);
    if (!"".equals(vendor)) {
        final Node vendorNode = (Element) cpuMatchNode.appendChild(doc.createElement("vendor"));
        vendorNode.appendChild(doc.createTextNode(vendor));
    }
    final String sockets = parametersMap.get(VM_PARAM_CPUMATCH_TOPOLOGY_SOCKETS);
    final String cores = parametersMap.get(VM_PARAM_CPUMATCH_TOPOLOGY_CORES);
    final String threads = parametersMap.get(VM_PARAM_CPUMATCH_TOPOLOGY_THREADS);
    final boolean isSockets = !"".equals(sockets);
    final boolean isCores = !"".equals(cores);
    final boolean isThreads = !"".equals(threads);
    if (isSockets || isCores || isThreads) {
        final Element topologyNode = (Element) cpuMatchNode.appendChild(doc.createElement("topology"));
        if (isSockets) {
            topologyNode.setAttribute("sockets", sockets);
        }
        if (isCores) {
            topologyNode.setAttribute("cores", cores);
        }
        if (isThreads) {
            topologyNode.setAttribute("threads", threads);
        }
    }
    final String policy = parametersMap.get(VM_PARAM_CPUMATCH_FEATURE_POLICY);
    final String features = parametersMap.get(VM_PARAM_CPUMATCH_FEATURES);
    if (!"".equals(policy) && !"".equals(features)) {
        for (final String feature : features.split("\\s+")) {
            final Element featureNode = (Element) cpuMatchNode.appendChild(doc.createElement("feature"));
            featureNode.setAttribute("policy", policy);
            featureNode.setAttribute("name", feature);
        }
    }
    if (!cpuMatchNode.hasChildNodes()) {
        root.removeChild(cpuMatchNode);

    }
}

From source file:com.marklogic.client.functionaltest.TestBiTemporal.java

private DOMHandle getXMLDocumentHandle(String startValidTime, String endValidTime, String address, String uri)
        throws Exception {

    Document domDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element root = domDocument.createElement("root");

    // System start and End time
    Node systemNode = root.appendChild(domDocument.createElement("system"));
    systemNode.appendChild(domDocument.createElement(systemStartERIName));
    systemNode.appendChild(domDocument.createElement(systemEndERIName));

    // Valid start and End time
    Node validNode = root.appendChild(domDocument.createElement("valid"));

    Node validStartNode = validNode.appendChild(domDocument.createElement(validStartERIName));
    validStartNode.appendChild(domDocument.createTextNode(startValidTime));
    validNode.appendChild(validStartNode);

    Node validEndNode = validNode.appendChild(domDocument.createElement(validEndERIName));
    validEndNode.appendChild(domDocument.createTextNode(endValidTime));
    validNode.appendChild(validEndNode);

    // Address//from   w w  w. j  a v a2 s. c  o  m
    Node addressNode = root.appendChild(domDocument.createElement("Address"));
    addressNode.appendChild(domDocument.createTextNode(address));

    // uri
    Node uriNode = root.appendChild(domDocument.createElement("uri"));
    uriNode.appendChild(domDocument.createTextNode(uri));
    domDocument.appendChild(root);

    String domString = ((DOMImplementationLS) DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .getDOMImplementation()).createLSSerializer().writeToString(domDocument);

    System.out.println(domString);

    DOMHandle handle = new DOMHandle().with(domDocument);

    return handle;
}

From source file:com.rover12421.shaka.apktool.lib.AndrolibResourcesAj.java

private boolean horizontalScrollView_check(String errInfo) throws Exception {
    if (errInfo.indexOf("'@android:style/Widget.HorizontalScrollView'") > 0) {
        Pattern xmlPathPattern = Pattern.compile(
                "(.+?):\\d+:.+?(Error retrieving parent for item).+?'@android:style/Widget.HorizontalScrollView'");
        Matcher xmlPathMatcher = xmlPathPattern.matcher(errInfo);
        if (xmlPathMatcher.find()) {
            String xmlPathStr = xmlPathMatcher.group(1);
            File xmlPathFile = new File(xmlPathStr);
            if (xmlPathFile.exists()) {
                LogHelper.warning("Find HorizontalScrollView exception xml : " + xmlPathStr);
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document document = documentBuilder.parse(xmlPathStr);
                NodeList list = document.getChildNodes().item(0).getChildNodes();
                for (int i = 0; i < list.getLength(); i++) {
                    Node node = list.item(i);
                    if (node.getAttributes() != null) {
                        Node attr = node.getAttributes().getNamedItem("parent");
                        if (attr != null
                                && attr.getNodeValue().equals("@android:style/Widget.HorizontalScrollView")) {
                            /**
                             * HorizontalScrollView??aaptScrollView
                             *//*from  w w w.  j ava2 s .  c  o m*/
                            attr.setNodeValue("@android:style/Widget.ScrollView");
                            /**
                             * ? android:scrollbars  android:fadingEdge 
                             * ??,
                             * ?????
                             */
                            Element scrollbars = document.createElement("item");
                            scrollbars.setAttribute("name", "android:scrollbars");
                            scrollbars.setNodeValue("horizontal");

                            Element fadingEdge = document.createElement("item");
                            fadingEdge.setAttribute("name", "android:fadingEdge");
                            fadingEdge.setNodeValue("horizontal");
                            Element element = (Element) node;
                            NodeList items = element.getElementsByTagName("item");
                            for (int j = 0; j < items.getLength(); j++) {
                                Element item = (Element) items.item(j);
                                if (item.getAttribute("name").equals("android:scrollbars")) {
                                    scrollbars = null;
                                }
                                if (item.getAttribute("name").equals("android:fadingEdge")) {
                                    fadingEdge = null;
                                }
                            }

                            if (scrollbars != null) {
                                node.appendChild(scrollbars);
                            }

                            if (fadingEdge != null) {
                                node.appendChild(fadingEdge);
                            }
                        }
                    }
                }

                /**
                 * ?xml
                 */
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                transformer.transform(new DOMSource(document), new StreamResult(xmlPathStr));

                return true;
            }
        }
    }

    return false;
}