Example usage for org.w3c.dom Document appendChild

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

Introduction

In this page you can find the example usage for org.w3c.dom Document 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:conf.Configuration.java

/** 
 * Write out the non-default properties in this configuration to the given
 * {@link Writer}./*from  w w  w . j a  v a2s . c o m*/
 * 
 * @param out the writer to write to.
 */
public synchronized void writeXml(Writer out) throws IOException {
    Properties properties = getProps();
    try {
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element conf = doc.createElement("configuration");
        doc.appendChild(conf);
        conf.appendChild(doc.createTextNode("\n"));
        for (Enumeration e = properties.keys(); e.hasMoreElements();) {
            String name = (String) e.nextElement();
            Object object = properties.get(name);
            String value = null;
            if (object instanceof String) {
                value = (String) object;
            } else {
                continue;
            }
            Element propNode = doc.createElement("property");
            conf.appendChild(propNode);

            if (updatingResource != null) {
                Comment commentNode = doc.createComment("Loaded from " + updatingResource.get(name));
                propNode.appendChild(commentNode);
            }
            Element nameNode = doc.createElement("name");
            nameNode.appendChild(doc.createTextNode(name));
            propNode.appendChild(nameNode);

            Element valueNode = doc.createElement("value");
            valueNode.appendChild(doc.createTextNode(value));
            propNode.appendChild(valueNode);

            conf.appendChild(doc.createTextNode("\n"));
        }

        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(out);
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        transformer.transform(source, result);
    } catch (TransformerException te) {
        throw new IOException(te);
    } catch (ParserConfigurationException pe) {
        throw new IOException(pe);
    }
}

From source file:com.microfocus.application.automation.tools.results.RunResultRecorder.java

private void writeReportMetaData2XML(List<ReportMetaData> htmlReportsInfo, String xmlFile,
        TaskListener _logger) {//from  w w w . j  a v a  2s.c o  m

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        _logger.error("Failed creating xml doc report: " + e);
        return;
    }
    Document doc = builder.newDocument();
    Element root = doc.createElement("reports_data");
    doc.appendChild(root);

    for (ReportMetaData htmlReportInfo : htmlReportsInfo) {
        String disPlayName = htmlReportInfo.getDisPlayName();
        String urlName = htmlReportInfo.getUrlName();
        String resourceURL = htmlReportInfo.getResourceURL();
        String dateTime = htmlReportInfo.getDateTime();
        String status = htmlReportInfo.getStatus();
        String isHtmlReport = htmlReportInfo.getIsHtmlReport() ? "true" : "false";
        String isParallelRunnerReport = htmlReportInfo.getIsParallelRunnerReport() ? "true" : "false";
        Element elmReport = doc.createElement(REPORT_NAME_FIELD);
        elmReport.setAttribute("disPlayName", disPlayName);
        elmReport.setAttribute("urlName", urlName);
        elmReport.setAttribute("resourceURL", resourceURL);
        elmReport.setAttribute("dateTime", dateTime);
        elmReport.setAttribute("status", status);
        elmReport.setAttribute("isHtmlreport", isHtmlReport);
        elmReport.setAttribute("isParallelRunnerReport", isParallelRunnerReport);
        root.appendChild(elmReport);

    }

    try {
        write2XML(doc, xmlFile);
    } catch (TransformerException e) {
        _logger.error("Failed transforming xml file: " + e);
    } catch (FileNotFoundException e) {
        _logger.error("Failed to find " + xmlFile + ": " + e);
    }
}

From source file:com.enonic.vertical.engine.handlers.PageTemplateHandler.java

/**
 * Update the pagetemplate in the database.
 *
 * @param doc The pagetemplate XML document.
 * @throws VerticalUpdateException Indicates that the update was not successfull.
 */// w w  w .j ava 2s .  c o m
private void updatePageTemplate(Document doc) throws VerticalUpdateException {

    Element docElem = doc.getDocumentElement();
    Element[] pagetemplateElems;
    if ("pagetemplate".equals(docElem.getTagName())) {
        pagetemplateElems = new Element[] { docElem };
    } else {
        pagetemplateElems = XMLTool.getElements(doc.getDocumentElement());
    }

    Connection con = null;
    PreparedStatement preparedStmt = null;
    int pageTemplateKey;

    try {
        con = getConnection();
        preparedStmt = con.prepareStatement(PAT_UPDATE);

        for (Element root : pagetemplateElems) {
            Map<String, Element> subelems = XMLTool.filterElements(root.getChildNodes());

            // attribute: key
            String tmp = root.getAttribute("key");
            pageTemplateKey = Integer.parseInt(tmp);
            preparedStmt.setInt(9, pageTemplateKey);

            // attribute: type
            PageTemplateType pageTemplateType = PageTemplateType
                    .valueOf(root.getAttribute("type").toUpperCase());
            preparedStmt.setInt(7, pageTemplateType.getKey());

            RunAsType runAs = RunAsType.INHERIT;
            String runAsStr = root.getAttribute("runAs");
            if (StringUtils.isNotEmpty(runAsStr)) {
                runAs = RunAsType.valueOf(runAsStr);
            }
            preparedStmt.setInt(8, runAs.getKey());

            // attribute: menukey
            tmp = root.getAttribute("menukey");
            int menuKey = Integer.parseInt(tmp);
            preparedStmt.setInt(2, menuKey);

            // element: stylesheet
            Element stylesheet = subelems.get("stylesheet");
            String styleSheetKey = stylesheet.getAttribute("stylesheetkey");
            preparedStmt.setString(1, styleSheetKey);

            // element: name
            Element subelem = subelems.get("name");
            String name = XMLTool.getElementText(subelem);
            preparedStmt.setString(3, name);

            subelem = subelems.get("description");
            if (subelem != null) {
                String description = XMLTool.getElementText(subelem);
                if (description != null) {
                    preparedStmt.setString(4, description);
                } else {
                    preparedStmt.setNull(4, Types.VARCHAR);
                }
            } else {
                preparedStmt.setNull(4, Types.VARCHAR);
            }

            // element: timestamp (using the database timestamp at creation)
            /* no code */

            // element: contenttypes
            subelem = subelems.get("contenttypes");
            Element[] ctyElems = XMLTool.getElements(subelem);
            int[] ctys = new int[ctyElems.length];
            for (int j = 0; j < ctyElems.length; j++) {
                ctys[j] = Integer.parseInt(ctyElems[j].getAttribute("key"));
            }
            setPageTemplateContentTypes(pageTemplateKey, ctys);

            // element: datasources
            subelem = subelems.get("pagetemplatedata");
            Document ptdDoc = XMLTool.createDocument();
            ptdDoc.appendChild(ptdDoc.importNode(subelem, true));
            byte[] ptdBytes = XMLTool.documentToBytes(ptdDoc, "UTF-8");
            ByteArrayInputStream byteStream = new ByteArrayInputStream(ptdBytes);
            preparedStmt.setBinaryStream(5, byteStream, ptdBytes.length);

            // element: CSS
            subelem = subelems.get("css");
            if (subelem != null) {
                String foo = subelem.getAttribute("stylesheetkey");
                preparedStmt.setString(6, foo);
            } else {
                preparedStmt.setNull(6, Types.VARCHAR);
            }

            int result = preparedStmt.executeUpdate();
            if (result <= 0) {
                String message = "Failed to update page template. No page template updated.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }

            // If page template is of type "section", we need to create sections for menuitems
            // that does not have one
            if (pageTemplateType == PageTemplateType.SECTIONPAGE) {
                int[] menuItemKeys = getMenuItemKeysByPageTemplate(pageTemplateKey);
                for (int menuItemKey : menuItemKeys) {
                    MenuItemKey sectionKey = getSectionHandler()
                            .getSectionKeyByMenuItem(new MenuItemKey(menuItemKey));
                    if (sectionKey == null) {
                        getSectionHandler().createSection(menuItemKey, true, ctys);
                    }
                }
            }

            Element contentobjects = XMLTool.getElement(root, "contentobjects");
            Element ptp = XMLTool.getElement(root, "pagetemplateparameters");

            if (ptp != null) {
                int[] paramKeys = new int[0];

                // update all ptp entries for page
                try {
                    int[] oldPTPKey = getPageTemplParamKeys(pageTemplateKey);
                    Node[] ptpNode = XMLTool.filterNodes(ptp.getChildNodes(), Node.ELEMENT_NODE);
                    int[] updatedPTPKey = new int[ptpNode.length];
                    int updatedPTPs = 0, newPTPs = 0;
                    Document updatedPTPDoc = XMLTool.createDocument("pagetemplateparameters");
                    Element updatedPTP = updatedPTPDoc.getDocumentElement();
                    Document newPTPDoc = XMLTool.createDocument("pagetemplateparameters");
                    Element newPTP = newPTPDoc.getDocumentElement();

                    for (Node aPtpNode : ptpNode) {
                        ptp = (Element) aPtpNode;
                        String keyStr = ptp.getAttribute("key");
                        int key;
                        if (keyStr != null && keyStr.length() > 0) {
                            key = Integer.parseInt(keyStr);
                        } else {
                            key = -1;
                        }
                        if (key >= 0) {
                            updatedPTP.appendChild(updatedPTPDoc.importNode(ptp, true));
                            updatedPTPKey[updatedPTPs++] = key;
                        } else {
                            newPTP.appendChild(newPTPDoc.importNode(ptp, true));
                            newPTPs++;
                        }
                    }

                    // remove old
                    if (updatedPTPs == 0) {
                        PageHandler pageHandler = getPageHandler();
                        int[] pageKeys = pageHandler.getPageKeysByPageTemplateKey(pageTemplateKey);
                        for (int pageKey : pageKeys) {
                            pageHandler.removePageContentObjects(pageKey, null);
                        }
                        removePageTemplateCOs(pageTemplateKey, null);
                        removePageTemplParams(pageTemplateKey);
                    } else if (updatedPTPs < oldPTPKey.length) {
                        int temp1[] = new int[updatedPTPs];
                        System.arraycopy(updatedPTPKey, 0, temp1, 0, updatedPTPs);
                        updatedPTPKey = temp1;

                        Arrays.sort(oldPTPKey);
                        oldPTPKey = ArrayUtil.removeDuplicates(oldPTPKey);
                        Arrays.sort(updatedPTPKey);
                        updatedPTPKey = ArrayUtil.removeDuplicates(updatedPTPKey);
                        int temp2[][] = ArrayUtil.diff(oldPTPKey, updatedPTPKey);

                        PageHandler pageHandler = getPageHandler();
                        int[] contentObjectKeys = pageHandler.getContentObjectKeys(temp2[0]);
                        int[] pageKeys = pageHandler.getPageKeysByPageTemplateKey(pageTemplateKey);
                        if (contentObjectKeys != null && contentObjectKeys.length > 0) {
                            for (int pageKey : pageKeys) {
                                pageHandler.removePageContentObjects(pageKey, contentObjectKeys);
                            }
                        }
                        removePageTemplateCOs(pageTemplateKey, temp2[0]);
                        removePageTemplParams(temp2[0]);
                    }

                    updatePageTemplParam(updatedPTPDoc);
                    if (newPTPs > 0) {
                        paramKeys = createPageTemplParam(null, newPTPDoc);
                    }
                } catch (VerticalRemoveException vre) {
                    String message = "Failed to remove old page template parameters: %t";
                    VerticalEngineLogger.errorUpdate(this.getClass(), 3, message, vre);
                } catch (VerticalCreateException vce) {
                    String message = "Failed to create new page template parameters: %t";
                    VerticalEngineLogger.errorUpdate(this.getClass(), 4, message, vce);
                }

                if (contentobjects != null) {
                    // update all pageconobj entries for page
                    try {
                        Document cobsDoc = XMLTool.createDocument();
                        cobsDoc.appendChild(cobsDoc.importNode(contentobjects, true));
                        updatePageTemplateCOs(cobsDoc, pageTemplateKey, paramKeys);
                    } catch (VerticalCreateException vce) {
                        String message = "Failed to create new link from page template to content objects: %t";
                        VerticalEngineLogger.errorUpdate(this.getClass(), 2, message, vce);
                    }
                }
            }
        }
    } catch (SQLException sqle) {
        String message = "Failed to update page template because of database error: %t";
        VerticalEngineLogger.errorUpdate(this.getClass(), 5, message, sqle);
    } catch (NumberFormatException nfe) {
        String message = "Failed to parse a key field: %t";
        VerticalEngineLogger.errorUpdate(this.getClass(), 6, message, nfe);
    } catch (VerticalCreateException vce) {
        String message = "Failed to create sections for page template: %t";
        VerticalEngineLogger.errorUpdate(this.getClass(), 6, message, vce);
    } finally {
        close(preparedStmt);
        close(con);
    }
}

From source file:serverTools.java

public String createServerConfig(String node, String jsonString) {
    String result = node + "::";
    try {/*from w w w  .  j a va2 s. c om*/
        String ret;
        JSONObject jo = new JSONObject(jsonString);
        UUID uid = UUID.randomUUID();

        String varName = node;
        String varIP = jo.get("ip").toString();
        String varHyp = jo.get("hypervisor").toString();
        String varVmconfigs = jo.get("vmconfigs").toString();
        String varTransport = jo.get("transport").toString();
        String varDesc = jo.get("description").toString();
        // make sure that remote directory exist
        // Get the JSONArray value associated with the Result key
        JSONArray storageArray = jo.getJSONArray("storages");
        String configDir = this.makeRelativeDirs("/" + varName + "/config");
        this.makeRelativeDirs("/" + varName + "/screenshots");
        this.makeRelativeDirs("/" + varName + "/vm/configs");

        // Cration d'un nouveau DOM
        DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
        DocumentBuilder constructeur = fabrique.newDocumentBuilder();
        Document document = constructeur.newDocument();

        // Proprits du DOM
        document.setXmlStandalone(true);

        // Cration de l'arborescence du DOM
        Element server = document.createElement("server");
        document.appendChild(server);

        //racine.appendChild(document.createComment("Commentaire sous la racine"));
        Element name = document.createElement("name");
        server.appendChild(name);
        name.setTextContent(varName);

        Element ip = document.createElement("ip");
        server.appendChild(ip);
        ip.setTextContent(varIP);

        Element hypervisor = document.createElement("hypervisor");
        server.appendChild(hypervisor);
        hypervisor.setTextContent(varHyp);

        Element transport = document.createElement("transport");
        server.appendChild(transport);
        transport.setTextContent(varTransport);

        Element descEl = document.createElement("description");
        server.appendChild(descEl);
        descEl.setTextContent(varDesc);

        Element vmconfigs = document.createElement("vmconfigs");
        server.appendChild(vmconfigs);
        vmconfigs.setTextContent(varVmconfigs);

        JSONObject coordinatesObj = jo.getJSONObject("coordinates");
        Element coordinatesEl = document.createElement("coordinates");
        server.appendChild(coordinatesEl);
        coordinatesEl.setAttribute("building", coordinatesObj.get("building").toString());
        coordinatesEl.setAttribute("street", coordinatesObj.get("street").toString());
        coordinatesEl.setAttribute("city", coordinatesObj.get("city").toString());
        coordinatesEl.setAttribute("latitude", coordinatesObj.get("latitude").toString());
        coordinatesEl.setAttribute("longitude", coordinatesObj.get("longitude").toString());

        //<storages>
        Element storages = document.createElement("storages");
        server.appendChild(storages);

        int resultCount = storageArray.length();
        for (int i = 0; i < resultCount; i++) {
            Element repository = document.createElement("repository");
            storages.appendChild(repository);
            Element path = document.createElement("target");
            repository.appendChild(path);

            JSONObject newStorage = storageArray.getJSONObject(i);
            String storageName = newStorage.get("name").toString();
            String storagePath = newStorage.get("target").toString();
            storageName = storageName.replaceAll(" ", "_");
            storagePath = storagePath.replaceAll(" ", "_");

            repository.setAttribute("type", newStorage.get("type").toString());
            repository.setAttribute("name", storageName);
            path.setTextContent(storagePath);

            Element source = document.createElement("source");
            repository.appendChild(source);
            String storageSource = newStorage.get("source").toString();
            source.setTextContent(storageSource);

            String localStorageDir = this.makeRelativeDirs("/" + varName + "/vm/storages/" + storageName);
            if (localStorageDir == "Error") {
                return result + "Error: cannot create " + varName + "/vm/storages/" + storageName;
            }
        }
        //</storages>
        // Get network information (look for bridges)
        Element networks = document.createElement("networks");
        server.appendChild(networks);

        JSONObject joAction = new JSONObject();
        joAction.put("name", "add");
        joAction.put("driver", varHyp);
        joAction.put("transport", varTransport);
        joAction.put("description", varDesc);
        ArrayList<String> optList = new ArrayList<String>();
        optList.add("ip=" + varIP);
        String varPasswd = "";
        varPasswd = jo.opt("password").toString();
        if (varPasswd.length() > 0) {
            optList.add("exchange_keys=" + varPasswd);
        }
        joAction.put("options", optList);
        String msg = callOvnmanager(node, joAction.toString());

        JSONObject joMsg = new JSONObject(msg);
        JSONObject joActionRes = joMsg.getJSONObject("action");
        result += joActionRes.get("result").toString();
        //write the content into xml file

        String pathToXml = configDir + "/" + varName + ".xml";
        File xmlOutput = new File(pathToXml);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        DOMSource source = new DOMSource(document);
        StreamResult streamRes = new StreamResult(xmlOutput);
        transformer.transform(source, streamRes);

    } catch (Exception e) {
        log(ERROR, "create xml file has failed", e);
        return result + "Error: " + e.toString();
    }
    //ret = "done";
    return result;
}

From source file:com.enonic.vertical.engine.handlers.PageTemplateHandler.java

private int[] createPageTemplate(CopyContext copyContext, Document doc, boolean useOldKey)
        throws VerticalCreateException {

    Element docElem = doc.getDocumentElement();
    Element[] pagetemplateElems;/*from   w w w.j  ava2  s. c om*/
    if ("pagetemplate".equals(docElem.getTagName())) {
        pagetemplateElems = new Element[] { docElem };
    } else {
        pagetemplateElems = XMLTool.getElements(doc.getDocumentElement());
    }

    Connection con = null;
    PreparedStatement preparedStmt = null;
    TIntArrayList newKeys = new TIntArrayList();

    try {
        con = getConnection();
        preparedStmt = con.prepareStatement(PAT_CREATE);

        for (Element root : pagetemplateElems) {
            Map<String, Element> subelems = XMLTool.filterElements(root.getChildNodes());

            // key
            int key;
            String keyStr = root.getAttribute("key");
            if (!useOldKey || keyStr == null || keyStr.length() == 0) {
                key = getNextKey(PAT_TABLE);
            } else {
                key = Integer.parseInt(keyStr);
            }
            if (copyContext != null) {
                copyContext.putPageTemplateKey(Integer.parseInt(keyStr), key);
            }
            newKeys.add(key);
            preparedStmt.setInt(1, key);

            // attribute: menukey
            keyStr = root.getAttribute("menukey");
            int menuKey = Integer.parseInt(keyStr);
            preparedStmt.setInt(3, menuKey);

            // element: stylesheet
            Element stylesheet = subelems.get("stylesheet");
            String tmp = stylesheet.getAttribute("stylesheetkey");
            preparedStmt.setString(2, tmp);

            // element: name
            Element subelem = subelems.get("name");
            String name = XMLTool.getElementText(subelem);
            preparedStmt.setString(4, name);

            // element: name
            subelem = subelems.get("description");
            if (subelem != null) {
                String description = XMLTool.getElementText(subelem);
                if (description != null) {
                    preparedStmt.setString(5, description);
                } else {
                    preparedStmt.setNull(5, Types.VARCHAR);
                }
            } else {
                preparedStmt.setNull(5, Types.VARCHAR);
            }

            // element: timestamp (using the database timestamp at creation)
            /* no code */

            // element: datasources
            subelem = subelems.get("pagetemplatedata");
            Document ptdDoc;
            if (subelem != null) {
                ptdDoc = XMLTool.createDocument();
                ptdDoc.appendChild(ptdDoc.importNode(subelem, true));
            } else {
                ptdDoc = XMLTool.createDocument("pagetemplatedata");
            }
            byte[] ptdBytes = XMLTool.documentToBytes(ptdDoc, "UTF-8");
            ByteArrayInputStream byteStream = new ByteArrayInputStream(ptdBytes);
            preparedStmt.setBinaryStream(6, byteStream, ptdBytes.length);

            // element: CSS
            subelem = subelems.get("css");
            if (subelem != null) {
                preparedStmt.setString(7, subelem.getAttribute("stylesheetkey"));
            } else {
                preparedStmt.setNull(7, Types.VARCHAR);
            }

            // pagetemplate type:
            PageTemplateType type = PageTemplateType.valueOf(root.getAttribute("type").toUpperCase());
            preparedStmt.setInt(8, type.getKey());

            RunAsType runAs = RunAsType.INHERIT;
            String runAsStr = root.getAttribute("runAs");
            if (StringUtils.isNotEmpty(runAsStr)) {
                runAs = RunAsType.valueOf(runAsStr);
            }
            preparedStmt.setInt(9, runAs.getKey());

            // add
            int result = preparedStmt.executeUpdate();
            if (result == 0) {
                String message = "Failed to create page template. No page template created.";
                VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
            }

            // create page template parameters
            Element ptpsElem = XMLTool.getElement(root, "pagetemplateparameters");
            int[] ptpKeys = null;
            if (ptpsElem != null) {
                Element[] ptpElems = XMLTool.getElements(ptpsElem);
                for (Element ptpElem : ptpElems) {
                    ptpElem.setAttribute("pagetemplatekey", Integer.toString(key));
                }

                Document ptpDoc = XMLTool.createDocument();
                Node n = ptpDoc.importNode(ptpsElem, true);
                ptpDoc.appendChild(n);
                ptpKeys = createPageTemplParam(copyContext, ptpDoc);
            }

            // create all pageconobj entries for page
            Element contentobjectsElem = XMLTool.getElement(root, "contentobjects");
            if (contentobjectsElem != null) {
                Element[] contentobjectElems = XMLTool.getElements(contentobjectsElem);

                for (Element contentobjectElem : contentobjectElems) {
                    contentobjectElem.setAttribute("pagetemplatekey", Integer.toString(key));
                    if (copyContext != null) {
                        keyStr = contentobjectElem.getAttribute("parameterkey");
                        int newKey = copyContext.getPageTemplateParameterKey(Integer.parseInt(keyStr));
                        contentobjectElem.setAttribute("parameterkey", String.valueOf(newKey));
                    } else {
                        int pIndex = Integer
                                .parseInt(contentobjectElem.getAttribute("parameterkey").substring(1));
                        contentobjectElem.setAttribute("parameterkey", Integer.toString(ptpKeys[pIndex]));
                    }
                }

                Document coDoc = XMLTool.createDocument();
                coDoc.appendChild(coDoc.importNode(contentobjectsElem, true));
                updatePageTemplateCOs(coDoc, key, ptpKeys);
            }

            // element: contenttypes
            subelem = subelems.get("contenttypes");
            Element[] ctyElems = XMLTool.getElements(subelem);
            int[] ctys = new int[ctyElems.length];
            for (int j = 0; j < ctyElems.length; j++) {
                ctys[j] = Integer.parseInt(ctyElems[j].getAttribute("key"));
            }
            setPageTemplateContentTypes(key, ctys);
        }
    } catch (SQLException sqle) {
        String message = "Failed to create page template because of database error: %t";
        VerticalEngineLogger.errorCreate(this.getClass(), 1, message, sqle);
    } catch (NumberFormatException nfe) {
        String message = "Failed to parse a key field: %t";
        VerticalEngineLogger.errorCreate(this.getClass(), 2, message, nfe);
    } catch (VerticalKeyException gke) {
        String message = "Failed generate page template key: %t";
        VerticalEngineLogger.errorCreate(this.getClass(), 3, message, gke);
    } finally {
        close(preparedStmt);
        close(con);
    }

    return newKeys.toArray();
}

From source file:main.java.vasolsim.common.file.__NONUSEDREFERENCE_VaSOLSimExam.java

/**
 * Writes a digitized version of the VaSOLSim test, represented by an thisInstance of this class,
 * to a given file in//from   w  ww.  j a v  a  2  s .  com
 * XML format. Prior to writing, this function will (re)initialize teh Ciphers used to protect the file, and update
 * all protected information accordingly.
 *
 * @param simFile          the file on the disk to be written
 * @param canOverwriteFile can this method call write over an existing file with content
 *
 * @return if the write operation was successful
 *
 * @throws VaSolSimException thrown if insufficient information to write the file is contained in VaSolSimTest
 *                           object. Please ensure a password is provided to protect answer data and potentially
 *                           email data if test statistics and notifications are reported.
 */
public boolean write(File simFile, boolean canOverwriteFile) throws VaSolSimException {
    if (simFile.isFile()) {
        if (!canOverwriteFile) {
            throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS);
        } else {
            PrintWriter printWriter;
            try {
                printWriter = new PrintWriter(simFile);
            } catch (FileNotFoundException e) {
                throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK);
            }

            printWriter.print("");
            printWriter.close();
        }
    } else {
        if (!simFile.getParentFile().isDirectory() && !simFile.getParentFile().mkdirs()) {
            throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS);
        }

        try {
            if (!simFile.createNewFile()) {
                throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE);
            }
        } catch (IOException e) {
            throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION);
        }
    }

    //update crypto stuff
    updateCryptoEngine();
    updateCryptoProperties();

    /*
       * Check for any missing encrypted data that is required to read the test as specified
     */
    if (encryptedValidationHash.length < 1)
        throw new VaSolSimException(ERROR_MESSAGE_VALIDATION_KEY_NOT_PROVIDED);

    /*
     * Leave out for client side information gathering
     */
    /*
    if (isNotifyingCompletion && encryptedNotificationEmail.length < 1)
       throw new VaSolSimException("Notification requested with no email provided!");
       */

    if (isNotifyingCompletion && isNotifyingCompletionUsingStandaloneEmailParadigm
            && encryptedNotificationEmailPassword.length < 1)
        throw new VaSolSimException(ERROR_MESSAGE_STANDALONE_NOTIFICATION_PASSWORD_NOT_PROVIDED);

    /*
    if (isReportingStatistics && encryptedStatisticsEmail.length < 1)
       throw new VaSolSimException("Statistics requested with no email provided!");
       */

    if (isReportingStatistics && isReportingStatisticsUsingStandaloneEmailParadigm
            && encryptedStatisticsEmailPassword.length < 1)
        throw new VaSolSimException(ERROR_MESSAGE_STANDALONE_STATS_PASSWORD_NOT_PROVIDED);

    Document solExam;
    try {
        solExam = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e) {
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e);
    }

    //create document root
    Element root = solExam.createElement(xmlRootElementName);
    solExam.appendChild(root);

    //append the information sub element
    Element information = solExam.createElement(xmlInfoElementName);
    root.appendChild(information);

    Element security = solExam.createElement(xmlSecurityElementName);
    root.appendChild(security);

    /*
     * Build information element tree
     */
    createInformationElements(information, solExam);

    /*
     * Build security element tree
     */
    createSecurityElements(security, solExam);

    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
        transformer.setOutputProperty(indentationKey, "4");

        transformer.transform(new DOMSource(solExam), new StreamResult(new FileOutputStream(simFile)));
    } catch (FileNotFoundException e) {
        throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK, e);
    } catch (TransformerConfigurationException e) {
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e);
    } catch (TransformerException e) {
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_EXCEPTION, e);
    }

    return true;
}

From source file:vmTools.java

public String createVmXml(String jsonString, String server) {
    String ret = "";

    ArrayList<String> ide = new ArrayList<String>();
    ide.add("hda");
    ide.add("hdb");
    ide.add("hdc");
    ide.add("hdd");
    ide.add("hde");
    ide.add("hdf");
    ArrayList<String> scsi = new ArrayList<String>();
    scsi.add("sda");
    scsi.add("sdb");
    scsi.add("sdc");
    scsi.add("sdd");
    scsi.add("sde");
    scsi.add("sdf");

    try {/*from  w w  w . j av  a2 s  .com*/
        JSONObject jo = new JSONObject(jsonString);
        // A JSONArray is an ordered sequence of values. Its external form is a 
        // string wrapped in square brackets with commas between the values.
        // Get the JSONObject value associated with the search result key.
        String varName = jo.get("name").toString();

        String domainType = jo.get("domain_type").toString();
        String varMem = jo.get("memory").toString();
        String varCpu = jo.get("vcpu").toString();
        String varArch = jo.get("arch").toString();

        // Get the JSONArray value associated with the Result key
        JSONArray diskArray = jo.getJSONArray("diskList");
        JSONArray nicArray = jo.getJSONArray("nicList");

        // Cration d'un nouveau DOM
        DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
        DocumentBuilder constructeur = fabrique.newDocumentBuilder();
        Document document = constructeur.newDocument();

        // Proprits du DOM
        document.setXmlStandalone(true);

        // Cration de l'arborescence du DOM
        Element domain = document.createElement("domain");
        document.appendChild(domain);
        domain.setAttribute("type", domainType);

        //racine.appendChild(document.createComment("Commentaire sous la racine"));
        Element name = document.createElement("name");
        domain.appendChild(name);
        name.setTextContent(varName);

        UUID varuid = UUID.randomUUID();
        Element uid = document.createElement("uuid");
        domain.appendChild(uid);
        uid.setTextContent(varuid.toString());

        Element memory = document.createElement("memory");
        domain.appendChild(memory);
        memory.setTextContent(varMem);

        Element currentMemory = document.createElement("currentMemory");
        domain.appendChild(currentMemory);
        currentMemory.setTextContent(varMem);

        Element vcpu = document.createElement("vcpu");
        domain.appendChild(vcpu);
        vcpu.setTextContent(varCpu);
        //<os>
        Element os = document.createElement("os");
        domain.appendChild(os);
        Element type = document.createElement("type");
        os.appendChild(type);
        type.setAttribute("arch", varArch);
        type.setAttribute("machine", jo.get("machine").toString());
        type.setTextContent(jo.get("machine_type").toString());

        JSONArray bootArray = jo.getJSONArray("bootList");
        int count = bootArray.length();
        for (int i = 0; i < count; i++) {
            JSONObject bootDev = bootArray.getJSONObject(i);
            Element boot = document.createElement("boot");
            os.appendChild(boot);
            boot.setAttribute("dev", bootDev.get("dev").toString());
        }

        Element bootmenu = document.createElement("bootmenu");
        os.appendChild(bootmenu);
        bootmenu.setAttribute("enable", jo.get("bootMenu").toString());
        //</os>
        //<features>
        Element features = document.createElement("features");
        domain.appendChild(features);
        JSONArray featureArray = jo.getJSONArray("features");
        int featureCount = featureArray.length();
        for (int i = 0; i < featureCount; i++) {
            JSONObject jasonFeature = featureArray.getJSONObject(i);
            String newFeature = jasonFeature.get("opt").toString();
            Element elFeature = document.createElement(newFeature);
            features.appendChild(elFeature);
        }
        //</features>
        Element clock = document.createElement("clock");
        domain.appendChild(clock);
        // Clock settings
        clock.setAttribute("offset", jo.get("clock_offset").toString());
        JSONArray timerArray = jo.getJSONArray("timers");
        for (int i = 0; i < timerArray.length(); i++) {
            JSONObject jsonTimer = timerArray.getJSONObject(i);
            Element elTimer = document.createElement("timer");
            clock.appendChild(elTimer);
            elTimer.setAttribute("name", jsonTimer.get("name").toString());
            elTimer.setAttribute("present", jsonTimer.get("present").toString());
            elTimer.setAttribute("tickpolicy", jsonTimer.get("tickpolicy").toString());
        }

        Element poweroff = document.createElement("on_poweroff");
        domain.appendChild(poweroff);
        poweroff.setTextContent(jo.get("on_poweroff").toString());
        Element reboot = document.createElement("on_reboot");
        domain.appendChild(reboot);
        reboot.setTextContent(jo.get("on_reboot").toString());
        Element crash = document.createElement("on_crash");
        domain.appendChild(crash);
        crash.setTextContent(jo.get("on_crash").toString());
        //<devices>
        Element devices = document.createElement("devices");
        domain.appendChild(devices);
        String varEmulator = jo.get("emulator").toString();
        Element emulator = document.createElement("emulator");
        devices.appendChild(emulator);
        emulator.setTextContent(varEmulator);

        int resultCount = diskArray.length();
        for (int i = 0; i < resultCount; i++) {
            Element disk = document.createElement("disk");
            devices.appendChild(disk);
            JSONObject newDisk = diskArray.getJSONObject(i);
            String diskType = newDisk.get("type").toString();
            Element driver = document.createElement("driver");
            Element target = document.createElement("target");
            disk.appendChild(driver);
            disk.appendChild(target);
            if (diskType.equals("file")) {
                Element source = document.createElement("source");
                disk.appendChild(source);
                source.setAttribute("file", newDisk.get("source").toString());
                driver.setAttribute("cache", "none");
            }

            disk.setAttribute("type", diskType);
            disk.setAttribute("device", newDisk.get("device").toString());
            driver.setAttribute("type", newDisk.get("format").toString());
            driver.setAttribute("name", newDisk.get("driver").toString());

            //String diskDev = ide.get(0);
            //ide.remove(0);
            String diskDev = newDisk.get("bus").toString();
            String diskBus = "";
            if (diskDev.indexOf("hd") > -1) {
                diskBus = "ide";
            } else if (diskDev.indexOf("sd") > -1) {
                diskBus = "scsi";
            } else if (diskDev.indexOf("vd") > -1) {
                diskBus = "virtio";
            }

            target.setAttribute("dev", diskDev);
            target.setAttribute("bus", diskBus);

        }

        resultCount = nicArray.length();
        for (int i = 0; i < resultCount; i++) {
            JSONObject newNic = nicArray.getJSONObject(i);
            String macaddr = newNic.get("mac").toString().toLowerCase();
            if (macaddr.indexOf("automatic") > -1) {
                Random rand = new Random();
                macaddr = "52:54:00";
                String hexa = Integer.toHexString(rand.nextInt(255));
                macaddr += ":" + hexa;
                hexa = Integer.toHexString(rand.nextInt(255));
                macaddr += ":" + hexa;
                hexa = Integer.toHexString(rand.nextInt(255));
                macaddr += ":" + hexa;
            }

            Element netIf = document.createElement("interface");
            devices.appendChild(netIf);
            Element netSource = document.createElement("source");
            Element netDevice = document.createElement("model");
            Element netMac = document.createElement("mac");
            netIf.appendChild(netSource);
            netIf.appendChild(netDevice);
            netIf.appendChild(netMac);
            netIf.setAttribute("type", "network");
            netSource.setAttribute("network", newNic.get("bridge").toString());
            String portgroup = newNic.get("portgroup").toString();
            if (!portgroup.equals("")) {
                netSource.setAttribute("portgroup", portgroup);
            }
            netDevice.setAttribute("type", newNic.get("device").toString());
            netMac.setAttribute("address", macaddr);
        }

        JSONArray serialArray = jo.getJSONArray("serial");
        count = serialArray.length();
        for (int i = 0; i < count; i++) {
            JSONObject serialDev = serialArray.getJSONObject(i);
            Element serial = document.createElement("serial");
            devices.appendChild(serial);
            serial.setAttribute("type", serialDev.get("type").toString());
            Element target = document.createElement("target");
            serial.appendChild(target);
            target.setAttribute("port", serialDev.get("port").toString());
        }

        JSONArray consoleArray = jo.getJSONArray("console");
        count = consoleArray.length();
        for (int i = 0; i < count; i++) {
            JSONObject consoleDev = consoleArray.getJSONObject(i);
            Element console = document.createElement("console");
            devices.appendChild(console);
            console.setAttribute("type", "pty");
            Element target = document.createElement("target");
            console.appendChild(target);
            target.setAttribute("port", consoleDev.get("port").toString());
            target.setAttribute("type", consoleDev.get("type").toString());
        }

        JSONArray inputArray = jo.getJSONArray("input");
        count = inputArray.length();
        for (int i = 0; i < count; i++) {
            JSONObject inputDev = inputArray.getJSONObject(i);
            Element input = document.createElement("input");
            devices.appendChild(input);
            input.setAttribute("type", inputDev.get("type").toString());
            input.setAttribute("bus", inputDev.get("bus").toString());
        }

        JSONArray graphicsArray = jo.getJSONArray("graphics");
        count = graphicsArray.length();
        for (int i = 0; i < count; i++) {
            JSONObject graphicsDev = graphicsArray.getJSONObject(i);
            Element graphics = document.createElement("graphics");
            devices.appendChild(graphics);
            graphics.setAttribute("type", graphicsDev.get("type").toString());
            graphics.setAttribute("port", graphicsDev.get("port").toString());
            graphics.setAttribute("autoport", graphicsDev.get("autoport").toString());
            graphics.setAttribute("listen", graphicsDev.get("listen").toString());
            graphics.setAttribute("keymap", graphicsDev.get("keymap").toString());
        }

        JSONArray soundArray = jo.getJSONArray("sound");
        count = soundArray.length();
        for (int i = 0; i < count; i++) {
            JSONObject soundDev = soundArray.getJSONObject(i);
            Element sound = document.createElement("sound");
            devices.appendChild(sound);
            sound.setAttribute("model", soundDev.get("model").toString());
        }
        //sound.setAttribute("model", "ac97");

        JSONArray videoArray = jo.getJSONArray("video");
        count = videoArray.length();
        for (int i = 0; i < count; i++) {
            JSONObject videoDev = videoArray.getJSONObject(i);
            Element video = document.createElement("video");
            devices.appendChild(video);
            Element model = document.createElement("model");
            video.appendChild(model);
            model.setAttribute("model", videoDev.get("type").toString());
            model.setAttribute("model", videoDev.get("vram").toString());
            model.setAttribute("model", videoDev.get("heads").toString());
        }

        //write the content into xml file
        this.makeRelativeDirs("/" + server + "/vm/configs/" + varName);
        String pathToXml = RuntimeAccess.getInstance().getSession().getServletContext()
                .getRealPath("resources/data/" + server + "/vm/configs/" + varName + "/" + varName + ".xml");
        File xmlOutput = new File(pathToXml);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(xmlOutput);
        transformer.transform(source, result);

        StringWriter stw = new StringWriter();
        transformer.transform(source, new StreamResult(stw));
        ret = stw.toString();

    } catch (Exception e) {
        log(ERROR, "create xml file has failed", e);
        return e.toString();
    }
    return ret;
}

From source file:com.bluexml.xforms.controller.alfresco.agents.MappingAgent.java

/**
 * Returns an instance for workflow forms so that they can be displayed.
 * /*from w ww  .j av  a 2 s.  co  m*/
 * @param transaction
 * @param formName
 * @see {@link GetAction}
 * @param formName
 * @return the instance document, which is never <code>null</code>.
 */
public Document getInstanceWorkflow(AlfrescoTransaction transaction, String formName) {

    // DOM structure
    Document instance = AlfrescoController.getDocBuilder().newDocument();
    Element taskElt = instance.createElement(formName);
    Element rootElement = instance.createElement(MsgId.INT_INSTANCE_WKFLW_NODESET.getText());
    rootElement.appendChild(taskElt);
    instance.appendChild(rootElement);

    // fill the instance with the properties values
    Map<String, GenericClass> alfrescoNodes = new HashMap<String, GenericClass>();
    collectTaskProperties(transaction, instance, taskElt, formName, alfrescoNodes, false);

    return instance;
}

From source file:com.microsoft.windowsazure.management.sql.DacOperationsImpl.java

/**
* Exports an Azure SQL Database into a DACPAC file in Azure Blob Storage.
*
* @param serverName Required. The name of the Azure SQL Database Server in
* which the database to export resides.//from   w ww  .  j a  v  a2  s  .c  om
* @param parameters Optional. The parameters needed to initiate the export
* request.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return Represents the response that the service returns once an import
* or export operation has been initiated.
*/
@Override
public DacImportExportResponse export(String serverName, DacExportParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters != null) {
        if (parameters.getBlobCredentials() != null) {
            if (parameters.getBlobCredentials().getStorageAccessKey() == null) {
                throw new NullPointerException("parameters.BlobCredentials.StorageAccessKey");
            }
            if (parameters.getBlobCredentials().getUri() == null) {
                throw new NullPointerException("parameters.BlobCredentials.Uri");
            }
        }
        if (parameters.getConnectionInfo() != null) {
            if (parameters.getConnectionInfo().getDatabaseName() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.DatabaseName");
            }
            if (parameters.getConnectionInfo().getPassword() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.Password");
            }
            if (parameters.getConnectionInfo().getServerName() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.ServerName");
            }
            if (parameters.getConnectionInfo().getUserName() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.UserName");
            }
        }
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("serverName", serverName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "exportAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/DacOperations/Export";
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPost httpRequest = new HttpPost(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2012-03-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    if (parameters != null) {
        Element exportInputElement = requestDoc.createElementNS(
                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                "ExportInput");
        requestDoc.appendChild(exportInputElement);

        if (parameters.getBlobCredentials() != null) {
            Element blobCredentialsElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "BlobCredentials");
            exportInputElement.appendChild(blobCredentialsElement);

            Attr typeAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
                    "type");
            typeAttribute.setValue("BlobStorageAccessKeyCredentials");
            blobCredentialsElement.setAttributeNode(typeAttribute);

            Element uriElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "Uri");
            uriElement.appendChild(
                    requestDoc.createTextNode(parameters.getBlobCredentials().getUri().toString()));
            blobCredentialsElement.appendChild(uriElement);

            Element storageAccessKeyElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "StorageAccessKey");
            storageAccessKeyElement.appendChild(
                    requestDoc.createTextNode(parameters.getBlobCredentials().getStorageAccessKey()));
            blobCredentialsElement.appendChild(storageAccessKeyElement);
        }

        if (parameters.getConnectionInfo() != null) {
            Element connectionInfoElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "ConnectionInfo");
            exportInputElement.appendChild(connectionInfoElement);

            Element databaseNameElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "DatabaseName");
            databaseNameElement
                    .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getDatabaseName()));
            connectionInfoElement.appendChild(databaseNameElement);

            Element passwordElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "Password");
            passwordElement
                    .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getPassword()));
            connectionInfoElement.appendChild(passwordElement);

            Element serverNameElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "ServerName");
            serverNameElement
                    .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getServerName()));
            connectionInfoElement.appendChild(serverNameElement);

            Element userNameElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "UserName");
            userNameElement
                    .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getUserName()));
            connectionInfoElement.appendChild(userNameElement);
        }
    }

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        DacImportExportResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DacImportExportResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element guidElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/2003/10/Serialization/", "guid");
            if (guidElement != null) {
                result.setGuid(guidElement.getTextContent());
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}