Example usage for javax.xml.parsers DocumentBuilder newDocument

List of usage examples for javax.xml.parsers DocumentBuilder newDocument

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder newDocument.

Prototype


public abstract Document newDocument();

Source Link

Document

Obtain a new instance of a DOM Document object to build a DOM tree with.

Usage

From source file:com.photon.phresco.framework.rest.api.ConfigurationService.java

private static DOMSource createXML(String browsePath, String fileType) throws PhrescoException {
    try {/*from   w  ww.j  a v  a  2s  . c  o  m*/
        File inputPath = new File(browsePath);
        if (!inputPath.isDirectory() || inputPath.isFile()) {
            return null;
        }
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element rootElement = document.createElement("root");
        document.appendChild(rootElement);

        Element mainFolder = document.createElement("Item");
        mainFolder.setAttribute("name", inputPath.getName());
        mainFolder.setAttribute("path", inputPath.toString());
        mainFolder.setAttribute("type", "Folder");
        rootElement.appendChild(mainFolder);

        listDirectories(mainFolder, document, inputPath, fileType);

        DOMSource source = new DOMSource(document);
        return source;
    } catch (DOMException e) {
        throw new PhrescoException(e);
    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    }
}

From source file:serverTools.java

public String createServerConfig(String node, String jsonString) {
    String result = node + "::";
    try {//from www  . j a va2s.  c  o m
        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.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 a2s . co  m
* @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();
        }
    }
}

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

/**
* Initiates an Import of a DACPAC file from Azure Blob Storage into a Azure
* SQL Database./*from w ww.ja v  a 2  s.  c  om*/
*
* @param serverName Required. The name of the Azure SQL Database Server
* into which the database is being imported.
* @param parameters Optional. The parameters needed to initiated the Import
* 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 importMethod(String serverName, DacImportParameters 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, "importMethodAsync", 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/Import";
    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 importInputElement = requestDoc.createElementNS(
                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                "ImportInput");
        requestDoc.appendChild(importInputElement);

        if (parameters.getAzureEdition() != null) {
            Element azureEditionElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "AzureEdition");
            azureEditionElement.appendChild(requestDoc.createTextNode(parameters.getAzureEdition()));
            importInputElement.appendChild(azureEditionElement);
        }

        if (parameters.getBlobCredentials() != null) {
            Element blobCredentialsElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "BlobCredentials");
            importInputElement.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");
            importInputElement.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);
        }

        Element databaseSizeInGBElement = requestDoc.createElementNS(
                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                "DatabaseSizeInGB");
        databaseSizeInGBElement
                .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getDatabaseSizeInGB())));
        importInputElement.appendChild(databaseSizeInGBElement);
    }

    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();
        }
    }
}

From source file:com.connectsdk.service.DLNAService.java

protected String getMessageXml(String serviceURN, String method, String instanceId,
        Map<String, String> params) {
    try {/* w w  w.ja v  a  2s. c o m*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.newDocument();
        doc.setXmlStandalone(true);
        doc.setXmlVersion("1.0");

        Element root = doc.createElement("s:Envelope");
        Element bodyElement = doc.createElement("s:Body");
        Element methodElement = doc.createElementNS(serviceURN, "u:" + method);
        Element instanceElement = doc.createElement("InstanceID");

        root.setAttribute("s:encodingStyle", "http://schemas.xmlsoap.org/soap/encoding/");
        root.setAttribute("xmlns:s", "http://schemas.xmlsoap.org/soap/envelope/");

        doc.appendChild(root);
        root.appendChild(bodyElement);
        bodyElement.appendChild(methodElement);
        if (instanceId != null) {
            instanceElement.setTextContent(instanceId);
            methodElement.appendChild(instanceElement);
        }

        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                Element element = doc.createElement(key);
                element.setTextContent(value);
                methodElement.appendChild(element);
            }
        }
        return xmlToString(doc, true);
    } catch (Exception e) {
        return null;
    }
}

From source file:org.shareok.data.sagedata.SageSourceDataHandlerImpl.java

/** 
 * Convert the article data to dublin core xml metadata and save the the file
 * //from  w w w. ja  va 2  s. c  o  m
 * @param journalData : the SageJournalData
 * @param fileName : the root folder contains all the uploading article data
 */
public void exportXmlByJournalData(SageJournalData journalData, String outputPath) {

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        org.w3c.dom.Document doc = docBuilder.newDocument();
        org.w3c.dom.Element rootElement = doc.createElement("dublin_core");
        doc.appendChild(rootElement);

        // Add the type node:
        org.w3c.dom.Element element = doc.createElement("dcvalue");
        element.appendChild(doc.createTextNode(journalData.getType()));
        rootElement.appendChild(element);

        Attr attr = doc.createAttribute("element");
        attr.setValue("type");
        element.setAttributeNode(attr);

        attr = doc.createAttribute("language");
        attr.setValue("en_US");
        element.setAttributeNode(attr);

        attr = doc.createAttribute("qualifier");
        attr.setValue("none");
        element.setAttributeNode(attr);

        // Add the abstract node:
        String abs = journalData.getAbstractText();
        if (null != abs) {
            org.w3c.dom.Element elementAbs = doc.createElement("dcvalue");
            elementAbs.appendChild(doc.createTextNode(abs));
            rootElement.appendChild(elementAbs);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementAbs.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementAbs.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("abstract");
            elementAbs.setAttributeNode(attr);
        }

        // Add the language node:
        String lang = journalData.getLanguage();
        if (null != lang) {
            org.w3c.dom.Element elementLang = doc.createElement("dcvalue");
            elementLang.appendChild(doc.createTextNode(lang));
            rootElement.appendChild(elementLang);

            attr = doc.createAttribute("element");
            attr.setValue("language");
            elementLang.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementLang.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("iso");
            elementLang.setAttributeNode(attr);
        }

        // Add the title node:
        String tit = journalData.getTitle();
        if (null != tit) {
            org.w3c.dom.Element elementTitle = doc.createElement("dcvalue");
            elementTitle.appendChild(doc.createTextNode(tit));
            rootElement.appendChild(elementTitle);

            attr = doc.createAttribute("element");
            attr.setValue("title");
            elementTitle.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementTitle.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementTitle.setAttributeNode(attr);
        }

        // Add the available date node:
        //            Element elementAvailable = doc.createElement("dcvalue");
        //            elementAvailable.appendChild(doc.createTextNode(getDateAvailable().toString()));
        //            rootElement.appendChild(elementAvailable);
        //            
        //            attr = doc.createAttribute("element");
        //            attr.setValue("date");
        //            elementAvailable.setAttributeNode(attr);
        //            
        //            attr = doc.createAttribute("qualifier");
        //            attr.setValue("available");
        //            elementAvailable.setAttributeNode(attr);

        // Add the issued date node:
        Date issueDate = journalData.getDateIssued();
        if (null != issueDate) {
            SimpleDateFormat format_issuedDate = new SimpleDateFormat("yyyy-MM-dd");
            org.w3c.dom.Element elementIssued = doc.createElement("dcvalue");
            elementIssued.appendChild(doc.createTextNode(format_issuedDate.format(issueDate)));
            rootElement.appendChild(elementIssued);

            attr = doc.createAttribute("element");
            attr.setValue("date");
            elementIssued.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("issued");
            elementIssued.setAttributeNode(attr);
        }

        // Add the author nodes:
        String[] authorSet = journalData.getAuthors();
        if (null != authorSet && authorSet.length > 0) {
            for (String author : authorSet) {
                org.w3c.dom.Element elementAuthor = doc.createElement("dcvalue");
                elementAuthor.appendChild(doc.createTextNode(author));
                rootElement.appendChild(elementAuthor);

                attr = doc.createAttribute("element");
                attr.setValue("contributor");
                elementAuthor.setAttributeNode(attr);

                attr = doc.createAttribute("qualifier");
                attr.setValue("author");
                elementAuthor.setAttributeNode(attr);
            }
        }

        // Add the acknowledgements node:
        String ack = journalData.getAcknowledgements();
        if (null != ack) {
            org.w3c.dom.Element elementAck = doc.createElement("dcvalue");
            elementAck.appendChild(doc.createTextNode(ack));
            rootElement.appendChild(elementAck);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementAck.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementAck.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementAck.setAttributeNode(attr);
        }

        // Add the author contributions node:
        String contrib = journalData.getAuthorContributions();
        if (null != contrib) {
            org.w3c.dom.Element elementContribution = doc.createElement("dcvalue");
            elementContribution.appendChild(doc.createTextNode(contrib));
            rootElement.appendChild(elementContribution);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementContribution.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementContribution.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementContribution.setAttributeNode(attr);
        }

        // Add the publisher node:
        String puber = journalData.getPublisher();
        if (null != puber) {
            org.w3c.dom.Element elementPublisher = doc.createElement("dcvalue");
            elementPublisher.appendChild(doc.createTextNode(puber));
            rootElement.appendChild(elementPublisher);

            attr = doc.createAttribute("element");
            attr.setValue("publisher");
            elementPublisher.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementPublisher.setAttributeNode(attr);
        }

        // Add the citation node:
        String cit = journalData.getCitation();
        if (null != cit) {
            org.w3c.dom.Element elementCitation = doc.createElement("dcvalue");
            elementCitation.appendChild(doc.createTextNode(cit));
            rootElement.appendChild(elementCitation);

            attr = doc.createAttribute("element");
            attr.setValue("identifier");
            elementCitation.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementCitation.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("citation");
            elementCitation.setAttributeNode(attr);
        }

        // Add the rights node:
        String rit = journalData.getRights();
        if (null != rit) {
            org.w3c.dom.Element elementRights = doc.createElement("dcvalue");
            elementRights.appendChild(doc.createTextNode(rit));
            rootElement.appendChild(elementRights);

            attr = doc.createAttribute("element");
            attr.setValue("rights");
            elementRights.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementRights.setAttributeNode(attr);
        }

        // Add the rights URI node:
        String ritUri = journalData.getRightsUri();
        if (null != ritUri) {
            org.w3c.dom.Element elementRightsUri = doc.createElement("dcvalue");
            elementRightsUri.appendChild(doc.createTextNode(ritUri));
            rootElement.appendChild(elementRightsUri);

            attr = doc.createAttribute("element");
            attr.setValue("rights");
            elementRightsUri.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("uri");
            elementRightsUri.setAttributeNode(attr);
        }

        // Add the rights requestable node:
        org.w3c.dom.Element elementRightsRequestable = doc.createElement("dcvalue");
        elementRightsRequestable
                .appendChild(doc.createTextNode(Boolean.toString(journalData.isRightsRequestable())));
        rootElement.appendChild(elementRightsRequestable);

        attr = doc.createAttribute("element");
        attr.setValue("rights");
        elementRightsRequestable.setAttributeNode(attr);

        attr = doc.createAttribute("language");
        attr.setValue("en_US");
        elementRightsRequestable.setAttributeNode(attr);

        attr = doc.createAttribute("qualifier");
        attr.setValue("requestable");
        elementRightsRequestable.setAttributeNode(attr);

        // Add the is part of node:
        String partOf = journalData.getIsPartOfSeries();
        if (null != partOf) {
            org.w3c.dom.Element elementIsPartOf = doc.createElement("dcvalue");
            elementIsPartOf.appendChild(doc.createTextNode(partOf));
            rootElement.appendChild(elementIsPartOf);

            attr = doc.createAttribute("element");
            attr.setValue("relation");
            elementIsPartOf.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("ispartofseries");
            elementIsPartOf.setAttributeNode(attr);
        }

        // Add the relation uri node:
        String reUri = journalData.getRelationUri();
        if (null != reUri) {
            org.w3c.dom.Element elementRelationUri = doc.createElement("dcvalue");
            elementRelationUri.appendChild(doc.createTextNode(reUri));
            rootElement.appendChild(elementRelationUri);

            attr = doc.createAttribute("element");
            attr.setValue("relation");
            elementRelationUri.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("uri");
            elementRelationUri.setAttributeNode(attr);
        }

        // Add the subject nodes:
        String[] subjectSet = journalData.getSubjects();
        if (null != subjectSet && subjectSet.length > 0) {
            for (String subject : subjectSet) {
                org.w3c.dom.Element elementSubject = doc.createElement("dcvalue");
                elementSubject.appendChild(doc.createTextNode(subject));
                rootElement.appendChild(elementSubject);

                attr = doc.createAttribute("element");
                attr.setValue("subject");
                elementSubject.setAttributeNode(attr);

                attr = doc.createAttribute("language");
                attr.setValue("en_US");
                elementSubject.setAttributeNode(attr);

                attr = doc.createAttribute("qualifier");
                attr.setValue("none");
                elementSubject.setAttributeNode(attr);
            }
        }

        // Add the peerReview node:
        String review = journalData.getPeerReview();
        if (null != review) {
            org.w3c.dom.Element elementPeerReview = doc.createElement("dcvalue");
            elementPeerReview.appendChild(doc.createTextNode(review));
            rootElement.appendChild(elementPeerReview);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementPeerReview.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementPeerReview.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("peerreview");
            elementPeerReview.setAttributeNode(attr);
        }

        // Add the peer review notes node:
        String peer = journalData.getPeerReviewNotes();
        if (null != peer) {
            org.w3c.dom.Element elementPeerReviewNotes = doc.createElement("dcvalue");
            elementPeerReviewNotes.appendChild(doc.createTextNode(peer));
            rootElement.appendChild(elementPeerReviewNotes);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementPeerReviewNotes.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementPeerReviewNotes.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("peerreviewnotes");
            elementPeerReviewNotes.setAttributeNode(attr);
        }

        // Add the doi node:
        String doi = journalData.getDoi();
        if (null != doi) {
            org.w3c.dom.Element elementDoi = doc.createElement("dcvalue");
            elementDoi.appendChild(doc.createTextNode(doi));
            rootElement.appendChild(elementDoi);

            attr = doc.createAttribute("element");
            attr.setValue("identifier");
            elementDoi.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementDoi.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("doi");
            elementDoi.setAttributeNode(attr);
        }

        File outputFolder = new File(outputPath + File.separator + journalData.getDoi().replaceAll("/", "."));
        if (!outputFolder.exists()) {
            outputFolder.mkdirs();
        }
        String filePath = outputFolder + File.separator + "dublin_core.xml";
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filePath));

        transformer.transform(source, result);

    } catch (ParserConfigurationException | DOMException | BeansException pce) {
        pce.printStackTrace();
    } catch (TransformerException ex) {
        Logger.getLogger(SageSourceDataHandlerImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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  ww w  .  j  a v a  2 s.co m
        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:jef.tools.XMLUtils.java

/**
 * XML/*  w w  w  . j  a  v  a2 s. c o  m*/
 * 
 * @return XML
 */
public static Document newDocument() {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        document.setXmlStandalone(true);
        return document;
    } catch (ParserConfigurationException e) {
        LogUtil.exception(e);
        return null;
    }
}

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

/**
* Gets the status of the import or export operation in the specified server
* with the corresponding request ID.  The request ID is provided in the
* responses of the import or export operation.
*
* @param serverName Required. The name of the server in which the import or
* export operation is taking place.// w ww  . j  av  a  2  s  .  c  om
* @param parameters Required. The parameters needed to get the status of an
* import or export operation.
* @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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Represents a list of import or export status values returned from
* GetStatus.
*/
@Override
public DacGetStatusResponse getStatusPost(String serverName, DacGetStatusParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getPassword() == null) {
        throw new NullPointerException("parameters.Password");
    }
    if (parameters.getRequestId() == null) {
        throw new NullPointerException("parameters.RequestId");
    }
    if (parameters.getServerName() == null) {
        throw new NullPointerException("parameters.ServerName");
    }
    if (parameters.getUserName() == null) {
        throw new NullPointerException("parameters.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, "getStatusPostAsync", 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/Status";
    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();

    Element statusInputElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
            "StatusInput");
    requestDoc.appendChild(statusInputElement);

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

    Element requestIdElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
            "RequestId");
    requestIdElement.appendChild(requestDoc.createTextNode(parameters.getRequestId()));
    statusInputElement.appendChild(requestIdElement);

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

    Element userNameElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
            "UserName");
    userNameElement.appendChild(requestDoc.createTextNode(parameters.getUserName()));
    statusInputElement.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
        DacGetStatusResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DacGetStatusResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element arrayOfStatusInfoElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "ArrayOfStatusInfo");
            if (arrayOfStatusInfoElement != null) {
                if (arrayOfStatusInfoElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(arrayOfStatusInfoElement,
                                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                    "StatusInfo")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element statusInfoElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(arrayOfStatusInfoElement,
                                        "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                        "StatusInfo")
                                .get(i1));
                        StatusInfo statusInfoInstance = new StatusInfo();
                        result.getStatusInfoList().add(statusInfoInstance);

                        Element blobUriElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "BlobUri");
                        if (blobUriElement != null) {
                            URI blobUriInstance;
                            blobUriInstance = new URI(blobUriElement.getTextContent());
                            statusInfoInstance.setBlobUri(blobUriInstance);
                        }

                        Element databaseNameElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "DatabaseName");
                        if (databaseNameElement != null) {
                            String databaseNameInstance;
                            databaseNameInstance = databaseNameElement.getTextContent();
                            statusInfoInstance.setDatabaseName(databaseNameInstance);
                        }

                        Element errorMessageElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "ErrorMessage");
                        if (errorMessageElement != null) {
                            boolean isNil = false;
                            Attr nilAttribute = errorMessageElement
                                    .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                            if (nilAttribute != null) {
                                isNil = "true".equals(nilAttribute.getValue());
                            }
                            if (isNil == false) {
                                String errorMessageInstance;
                                errorMessageInstance = errorMessageElement.getTextContent();
                                statusInfoInstance.setErrorMessage(errorMessageInstance);
                            }
                        }

                        Element lastModifiedTimeElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "LastModifiedTime");
                        if (lastModifiedTimeElement != null) {
                            Calendar lastModifiedTimeInstance;
                            lastModifiedTimeInstance = DatatypeConverter
                                    .parseDateTime(lastModifiedTimeElement.getTextContent());
                            statusInfoInstance.setLastModifiedTime(lastModifiedTimeInstance);
                        }

                        Element queuedTimeElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "QueuedTime");
                        if (queuedTimeElement != null) {
                            Calendar queuedTimeInstance;
                            queuedTimeInstance = DatatypeConverter
                                    .parseDateTime(queuedTimeElement.getTextContent());
                            statusInfoInstance.setQueuedTime(queuedTimeInstance);
                        }

                        Element requestIdElement2 = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "RequestId");
                        if (requestIdElement2 != null) {
                            String requestIdInstance;
                            requestIdInstance = requestIdElement2.getTextContent();
                            statusInfoInstance.setRequestId(requestIdInstance);
                        }

                        Element requestTypeElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "RequestType");
                        if (requestTypeElement != null) {
                            String requestTypeInstance;
                            requestTypeInstance = requestTypeElement.getTextContent();
                            statusInfoInstance.setRequestType(requestTypeInstance);
                        }

                        Element serverNameElement2 = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "ServerName");
                        if (serverNameElement2 != null) {
                            String serverNameInstance;
                            serverNameInstance = serverNameElement2.getTextContent();
                            statusInfoInstance.setServerName(serverNameInstance);
                        }

                        Element statusElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "Status");
                        if (statusElement != null) {
                            String statusInstance;
                            statusInstance = statusElement.getTextContent();
                            statusInfoInstance.setStatus(statusInstance);
                        }
                    }
                }
            }

        }
        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();
        }
    }
}