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:com.aliyun.odps.conf.Configuration.java

/**
 * ?? {@link OutputStream}/*from  w  w  w.  j  a  va 2  s.  c o  m*/
 *
 * @param out
 *     {@link OutputStream}
 */
@SuppressWarnings("rawtypes")
public void writeXml(OutputStream 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);

            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 (Exception e) {
        throw new RuntimeException(e);
    }
}

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

private static Document constructSvnTree(Map<String, List<String>> list, String url, String appDirName)
        throws PhrescoException {
    try {//ww w . j  a v a  2  s  . c  o m
        DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
        Document doc = documentBuilder.newDocument();

        Element rootElement = doc.createElement(ROOT);
        doc.appendChild(rootElement);

        Element rootItem = doc.createElement(ITEM);
        rootItem.setAttribute(TYPE, FOLDER);
        rootItem.setAttribute(NAME, ROOT_ITEM);

        rootElement.appendChild(rootItem);

        Element urlItem = doc.createElement(ITEM);
        urlItem.setAttribute(TYPE, FOLDER);
        urlItem.setAttribute(NAME, url);

        rootItem.appendChild(urlItem);

        Element branchItem = doc.createElement(ITEM);
        branchItem.setAttribute(TYPE, FOLDER);
        branchItem.setAttribute(NAME, BRANCHES);
        branchItem.setAttribute(URL, url);
        urlItem.appendChild(branchItem);

        Element tagItem = doc.createElement(ITEM);
        tagItem.setAttribute(TYPE, FOLDER);
        tagItem.setAttribute(NAME, TAGS);
        tagItem.setAttribute(URL, url);
        urlItem.appendChild(tagItem);

        Element trunkItem = doc.createElement(ITEM);
        trunkItem.setAttribute(TYPE, FOLDER);
        trunkItem.setAttribute(NAME, TRUNK);
        trunkItem.setAttribute(URL, url);
        urlItem.appendChild(trunkItem);

        List<String> trunkList = list.get(TRUNK);
        for (String trunk : trunkList) {
            Element trunkItems = doc.createElement(ITEM);
            trunkItems.setAttribute(NAME, trunk);
            trunkItems.setAttribute(URL, url);
            trunkItems.setAttribute(REQ_APP_DIR_NAME, appDirName);
            trunkItems.setAttribute(NATURE, TRUNK);
            trunkItem.appendChild(trunkItems);
        }

        List<String> branchList = list.get(BRANCHES);
        for (String branch : branchList) {
            Element branchItems = doc.createElement(ITEM);
            branchItems.setAttribute(NAME, branch);
            branchItems.setAttribute(URL, url);
            branchItems.setAttribute(REQ_APP_DIR_NAME, appDirName);
            branchItems.setAttribute(NATURE, BRANCHES);
            branchItem.appendChild(branchItems);
        }

        List<String> tagList = list.get(TAGS);
        for (String tag : tagList) {
            Element tagItems = doc.createElement(ITEM);
            tagItems.setAttribute(NAME, tag);
            tagItems.setAttribute(URL, url);
            tagItems.setAttribute(REQ_APP_DIR_NAME, appDirName);
            tagItems.setAttribute(NATURE, TAGS);
            tagItem.appendChild(tagItems);
        }

        return doc;
    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    }
}

From source file:com.twinsoft.convertigo.beans.transactions.HtmlTransaction.java

protected Document makeBlob(byte[] data) {
    Document document = XMLUtils.getDefaultDocumentBuilder().newDocument();
    Element blob = document.createElement("blob");
    document.appendChild(blob);

    Header[] heads = context.getResponseHeaders();

    for (int i = 0; i < heads.length; i++) {
        if (HeaderName.ContentType.is(heads[i].getName()) || HeaderName.ContentLength.is(heads[i].getName())) {
            blob.setAttribute(heads[i].getName(), heads[i].getValue());
        }/*from  w w w .ja  v a 2  s.c o  m*/
    }
    blob.setAttribute("Referer", ((HtmlConnector) context.getConnector()).getReferer());

    blob.appendChild(document.createTextNode(Base64.encodeBase64String(data)));

    return document;
}

From source file:com.microsoft.windowsazure.management.mediaservices.AccountOperationsImpl.java

/**
* The Create Media Services Account operation creates a new media services
* account in Windows Azure.  (see//from w ww  .j  av a2  s .  c  o  m
* http://msdn.microsoft.com/en-us/library/windowsazure/dn194267.aspx for
* more information)
*
* @param parameters Required. Parameters supplied to the Create Media
* Services Account 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.
* @return The Create Media Services Account operation response.
*/
@Override
public MediaServicesAccountCreateResponse create(MediaServicesAccountCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getAccountName() == null) {
        throw new NullPointerException("parameters.AccountName");
    }
    if (parameters.getAccountName().length() < 3) {
        throw new IllegalArgumentException("parameters.AccountName");
    }
    if (parameters.getAccountName().length() > 24) {
        throw new IllegalArgumentException("parameters.AccountName");
    }
    if (parameters.getBlobStorageEndpointUri() == null) {
        throw new NullPointerException("parameters.BlobStorageEndpointUri");
    }
    if (parameters.getRegion() == null) {
        throw new NullPointerException("parameters.Region");
    }
    if (parameters.getRegion().length() < 3) {
        throw new IllegalArgumentException("parameters.Region");
    }
    if (parameters.getRegion().length() > 256) {
        throw new IllegalArgumentException("parameters.Region");
    }
    if (parameters.getStorageAccountKey() == null) {
        throw new NullPointerException("parameters.StorageAccountKey");
    }
    if (parameters.getStorageAccountKey().length() < 14) {
        throw new IllegalArgumentException("parameters.StorageAccountKey");
    }
    if (parameters.getStorageAccountKey().length() > 256) {
        throw new IllegalArgumentException("parameters.StorageAccountKey");
    }
    if (parameters.getStorageAccountName() == null) {
        throw new NullPointerException("parameters.StorageAccountName");
    }
    if (parameters.getStorageAccountName().length() < 3) {
        throw new IllegalArgumentException("parameters.StorageAccountName");
    }
    if (parameters.getStorageAccountName().length() > 24) {
        throw new IllegalArgumentException("parameters.StorageAccountName");
    }
    for (char storageAccountNameChar : parameters.getStorageAccountName().toCharArray()) {
        if (Character.isLowerCase(storageAccountNameChar) == false
                && Character.isDigit(storageAccountNameChar) == false) {
            throw new IllegalArgumentException("parameters.StorageAccountName");
        }
    }

    // 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("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createAsync", 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/mediaservices/Accounts";
    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", "2011-10-01");

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

    Element accountCreationRequestElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
            "AccountCreationRequest");
    requestDoc.appendChild(accountCreationRequestElement);

    Element accountNameElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
            "AccountName");
    accountNameElement.appendChild(requestDoc.createTextNode(parameters.getAccountName()));
    accountCreationRequestElement.appendChild(accountNameElement);

    Element blobStorageEndpointUriElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
            "BlobStorageEndpointUri");
    blobStorageEndpointUriElement
            .appendChild(requestDoc.createTextNode(parameters.getBlobStorageEndpointUri().toString()));
    accountCreationRequestElement.appendChild(blobStorageEndpointUriElement);

    Element regionElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
            "Region");
    regionElement.appendChild(requestDoc.createTextNode(parameters.getRegion()));
    accountCreationRequestElement.appendChild(regionElement);

    Element storageAccountKeyElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
            "StorageAccountKey");
    storageAccountKeyElement.appendChild(requestDoc.createTextNode(parameters.getStorageAccountKey()));
    accountCreationRequestElement.appendChild(storageAccountKeyElement);

    Element storageAccountNameElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
            "StorageAccountName");
    storageAccountNameElement.appendChild(requestDoc.createTextNode(parameters.getStorageAccountName()));
    accountCreationRequestElement.appendChild(storageAccountNameElement);

    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_CREATED) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        MediaServicesAccountCreateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new MediaServicesAccountCreateResponse();
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                MediaServicesCreatedAccount accountInstance = new MediaServicesCreatedAccount();
                result.setAccount(accountInstance);

                JsonNode accountIdValue = responseDoc.get("AccountId");
                if (accountIdValue != null && accountIdValue instanceof NullNode == false) {
                    String accountIdInstance;
                    accountIdInstance = accountIdValue.getTextValue();
                    accountInstance.setAccountId(accountIdInstance);
                }

                JsonNode accountNameValue = responseDoc.get("AccountName");
                if (accountNameValue != null && accountNameValue instanceof NullNode == false) {
                    String accountNameInstance;
                    accountNameInstance = accountNameValue.getTextValue();
                    accountInstance.setAccountName(accountNameInstance);
                }

                JsonNode subscriptionValue = responseDoc.get("Subscription");
                if (subscriptionValue != null && subscriptionValue instanceof NullNode == false) {
                    String subscriptionInstance;
                    subscriptionInstance = subscriptionValue.getTextValue();
                    accountInstance.setSubscriptionId(subscriptionInstance);
                }
            }

        }
        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.appdynamics.connectors.vcd.VappClient.java

public IMachine createVm(IImage image, IMachineDescriptor machineDescriptor, IComputeCenter computeCenter)
        throws ConnectorException {

    String vmName = createName(Utils.VM_PREFIX);

    try {/*from w  w  w  .j a  v a2  s.  c  om*/
        //
        // Getting appropriate information for creating recompose body
        //
        String response = doGet(vAppLink);

        Document doc = RestClient.stringToXmlDocument(response);
        Element childrenElement = (Element) doc.getElementsByTagName(Constants.CHILDREN).item(0);
        Element vmElement = (Element) childrenElement.getElementsByTagName(Constants.VM).item(0);

        String vmType = vmElement.getAttribute(Constants.TYPE);
        String vmRef = vmElement.getAttribute(Constants.HREF);

        //
        // Create RecomposeVAppParams body
        //
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        doc = docBuilder.newDocument();
        Element rootElement = doc.createElement(Constants.RECOMPOSE_VAPP);
        doc.appendChild(rootElement);

        rootElement.setAttribute("name", getvAppName());
        rootElement.setAttribute("xmlns", Constants.XMLNS);
        rootElement.setAttribute("xmlns:xsi", Constants.XMLNS_XSI);
        rootElement.setAttribute("xmlns:ovf", Constants.XMLNS_OVF);

        Element sourcedItem = doc.createElement(Constants.SOURCED_ITEM);
        sourcedItem.setAttribute(Constants.SOURCE_DELETE, "false");

        Element source = doc.createElement(Constants.SOURCE);
        source.setAttribute(Constants.TYPE, vmType);
        source.setAttribute(Constants.NAME, vmName);
        source.setAttribute(Constants.HREF, vmRef);

        sourcedItem.appendChild(source);
        rootElement.appendChild(sourcedItem);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource dSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);

        transformer.transform(dSource, result);
        String xmlBody = writer.toString();

        //
        // sending a POST request
        //

        StringEntity entity = new StringEntity(xmlBody);
        entity.setContentType(Constants.RECOMPOSE_VAPP_LINK);
        String createResponse = doPost(vAppLink + Constants.RECOMPOSE_ACTION, entity);

        IMachine machine = controllerServices.createMachineInstance(vmName, vmName, computeCenter,
                machineDescriptor, image, controllerServices.getDefaultAgentPort());
        return machine;
    } catch (Exception e) {
        throw new ConnectorException(e.getMessage());
    }
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseReader.java

private void updateIncomingData(String[] data) {
    try {/*from  w  w w  .  j  a  va  2s. c o m*/
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element resultElement = document.createElement("result");
        for (int i = 0; i < data.length; i++) {
            Element columnElement = document.createElement(data[i]);
            columnElement.setTextContent("value");
            resultElement.appendChild(columnElement);
        }
        document.appendChild(resultElement);

        DocumentSerializer docSerializer = new DocumentSerializer();

        String xml = docSerializer.toXML(document);

        //            parent.channelEditPanel.currentChannel.getSourceConnector().getTransformer().setInboundTemplate(xml.replaceAll("\\r\\n", "\n"));  // Not required with current text area
        parent.channelEditPanel.currentChannel.getSourceConnector().getTransformer().setInboundTemplate(xml);

        if (parent.channelEditPanel.currentChannel.getSourceConnector().getTransformer().getOutboundDataType()
                .equals(UIConstants.DATATYPE_XML)
                && parent.channelEditPanel.currentChannel.getSourceConnector().getTransformer()
                        .getOutboundTemplate() != null
                && parent.channelEditPanel.currentChannel.getSourceConnector().getTransformer()
                        .getOutboundTemplate().length() == 0) {
            List<Connector> list = parent.channelEditPanel.currentChannel.getDestinationConnectors();
            for (Connector c : list) {
                //                    c.getTransformer().setInboundTemplate(xml.replaceAll("\\r\\n", "\n"));  // Not required with current text area
                c.getTransformer().setInboundTemplate(xml);
            }
        }
    } catch (Exception ex) {
    }
}

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

private static DOMSource createXML(String browsePath, String fileType) throws PhrescoException {
    try {//from w  w  w .j a  v a 2s .  c  om
        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:hoot.services.controllers.osm.ElementResource.java

private Document getElementsXml(final String mapId, final String[] elementIdsStr, final ElementType elementType,
        final boolean multiLayerUniqueElementIds, final boolean addChildren, Connection dbConn)
        throws Exception {
    long mapIdNum = -1;
    try {/*from ww  w .  jav  a2 s.  c  o  m*/
        QMaps maps = QMaps.maps;
        //input mapId may be a map ID or a map name
        mapIdNum = ModelDaoUtils.getRecordIdForInputString(mapId, dbConn, maps, maps.id, maps.displayName);
    } catch (Exception e) {
        if (e.getMessage().startsWith("Multiple records exist")) {
            ResourceErrorHandler.handleError(
                    e.getMessage().replaceAll("records", "maps").replaceAll("record", "map"), Status.NOT_FOUND,
                    log);
        } else if (e.getMessage().startsWith("No record exists")) {
            ResourceErrorHandler.handleError(
                    e.getMessage().replaceAll("records", "maps").replaceAll("record", "map"), Status.NOT_FOUND,
                    log);
        }
        ResourceErrorHandler.handleError("Error requesting map with ID: " + mapId + " (" + e.getMessage() + ")",
                Status.BAD_REQUEST, log);
    }

    Document elementDoc = null;
    Set<Long> elementIds = new HashSet<Long>();
    //
    for (String elemId : elementIdsStr) {
        long elementId = Long.parseLong(elemId);
        elementIds.add(elementId);
    }

    @SuppressWarnings("unchecked")
    final List<Tuple> elementRecords = (List<Tuple>) Element.getElementRecordsWithUserInfo(mapIdNum,
            elementType, elementIds, dbConn);
    if (elementRecords == null || elementRecords.size() == 0) {
        ResourceErrorHandler.handleError("Elements with IDs: " + StringUtils.join(elementIdsStr) + " and type: "
                + elementType + " does not exist.", Status.NOT_FOUND, log);
    }
    assert (elementRecords.size() == 1);

    elementDoc = XmlDocumentBuilder.create();
    org.w3c.dom.Element elementRootXml = OsmResponseHeaderGenerator.getOsmDataHeader(elementDoc);
    elementDoc.appendChild(elementRootXml);

    for (int i = 0; i < elementRecords.size(); i++) {
        final Element element = ElementFactory.getInstance().create(elementType, elementRecords.get(i), dbConn,
                Long.parseLong(mapId));
        Users usersTable = elementRecords.get(i).get(QUsers.users);

        org.w3c.dom.Element elementXml = element.toXml(elementRootXml, usersTable.getId(),
                usersTable.getDisplayName(), multiLayerUniqueElementIds, addChildren);
        elementRootXml.appendChild(elementXml);
    }

    return elementDoc;
}

From source file:com.microsoft.windowsazure.management.websites.ServerFarmOperationsImpl.java

/**
* You can create a server farm by issuing an HTTP POST request. Only one
* server farm per webspace is permitted. You can retrieve server farm
* details by using HTTP GET, change server farm properties by using HTTP
* PUT, and delete a server farm by using HTTP DELETE. A request body is
* required for server farm creation (HTTP POST) and server farm update
* (HTTP PUT). Warning: Creating a server farm changes your webspace's
* Compute Mode from Shared to Dedicated. You will be charged from the
* moment the server farm is created, even if all your sites are still
* running in Free mode.  (see//from  ww  w  .j ava2  s.co m
* http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @param parameters Required. Parameters supplied to the Create Server Farm
* 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 The Create Server Farm operation response.
*/
@Override
public ServerFarmCreateResponse create(String webSpaceName, ServerFarmCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // 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("webSpaceName", webSpaceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createAsync", tracingParameters);
    }

    // Construct URL
    String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null
            ? this.getClient().getCredentials().getSubscriptionId().trim()
            : "") + "/services/WebSpaces/" + webSpaceName.trim() + "/ServerFarms";
    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;

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

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

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

    Element serverFarmElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ServerFarm");
    requestDoc.appendChild(serverFarmElement);

    if (parameters.getCurrentNumberOfWorkers() != null) {
        Element currentNumberOfWorkersElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
        currentNumberOfWorkersElement.appendChild(
                requestDoc.createTextNode(Integer.toString(parameters.getCurrentNumberOfWorkers())));
        serverFarmElement.appendChild(currentNumberOfWorkersElement);
    }

    if (parameters.getCurrentWorkerSize() != null) {
        Element currentWorkerSizeElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
        currentWorkerSizeElement
                .appendChild(requestDoc.createTextNode(parameters.getCurrentWorkerSize().toString()));
        serverFarmElement.appendChild(currentWorkerSizeElement);
    }

    Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
    nameElement.appendChild(requestDoc.createTextNode("DefaultServerFarm"));
    serverFarmElement.appendChild(nameElement);

    Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "NumberOfWorkers");
    numberOfWorkersElement
            .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers())));
    serverFarmElement.appendChild(numberOfWorkersElement);

    Element workerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "WorkerSize");
    workerSizeElement.appendChild(requestDoc.createTextNode(parameters.getWorkerSize().toString()));
    serverFarmElement.appendChild(workerSizeElement);

    if (parameters.getStatus() != null) {
        Element statusElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Status");
        statusElement.appendChild(requestDoc.createTextNode(parameters.getStatus().toString()));
        serverFarmElement.appendChild(statusElement);
    }

    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
        ServerFarmCreateResponse result = null;
        // Deserialize Response
        InputStream responseContent = httpResponse.getEntity().getContent();
        result = new ServerFarmCreateResponse();
        DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
        documentBuilderFactory2.setNamespaceAware(true);
        DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
        Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

        Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                "http://schemas.microsoft.com/windowsazure", "ServerFarm");
        if (serverFarmElement2 != null) {
            Element currentNumberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
            if (currentNumberOfWorkersElement2 != null) {
                int currentNumberOfWorkersInstance;
                currentNumberOfWorkersInstance = DatatypeConverter
                        .parseInt(currentNumberOfWorkersElement2.getTextContent());
                result.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance);
            }

            Element currentWorkerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
            if (currentWorkerSizeElement2 != null) {
                ServerFarmWorkerSize currentWorkerSizeInstance;
                currentWorkerSizeInstance = ServerFarmWorkerSize
                        .valueOf(currentWorkerSizeElement2.getTextContent());
                result.setCurrentWorkerSize(currentWorkerSizeInstance);
            }

            Element nameElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "Name");
            if (nameElement2 != null) {
                String nameInstance;
                nameInstance = nameElement2.getTextContent();
                result.setName(nameInstance);
            }

            Element numberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers");
            if (numberOfWorkersElement2 != null) {
                int numberOfWorkersInstance;
                numberOfWorkersInstance = DatatypeConverter.parseInt(numberOfWorkersElement2.getTextContent());
                result.setNumberOfWorkers(numberOfWorkersInstance);
            }

            Element workerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "WorkerSize");
            if (workerSizeElement2 != null) {
                ServerFarmWorkerSize workerSizeInstance;
                workerSizeInstance = ServerFarmWorkerSize.valueOf(workerSizeElement2.getTextContent());
                result.setWorkerSize(workerSizeInstance);
            }

            Element statusElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "Status");
            if (statusElement2 != null) {
                ServerFarmStatus statusInstance;
                statusInstance = ServerFarmStatus.valueOf(statusElement2.getTextContent());
                result.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();
        }
    }
}

From source file:com.microsoft.windowsazure.management.websites.ServerFarmOperationsImpl.java

/**
* You can create a server farm by issuing an HTTP POST request. Only one
* server farm per webspace is permitted. You can retrieve server farm
* details by using HTTP GET, change server farm properties by using HTTP
* PUT, and delete a server farm by using HTTP DELETE. A request body is
* required for server farm creation (HTTP POST) and server farm update
* (HTTP PUT). Warning: Creating a server farm changes your webspace's
* Compute Mode from Shared to Dedicated. You will be charged from the
* moment the server farm is created, even if all your sites are still
* running in Free mode.  (see//w  w  w.  j  a  v  a2  s .  c  om
* http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @param parameters Required. Parameters supplied to the Update Server Farm
* 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 The Update Server Farm operation response.
*/
@Override
public ServerFarmUpdateResponse update(String webSpaceName, ServerFarmUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // 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("webSpaceName", webSpaceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters);
    }

    // Construct URL
    String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null
            ? this.getClient().getCredentials().getSubscriptionId().trim()
            : "") + "/services/WebSpaces/" + webSpaceName.trim() + "/ServerFarms/DefaultServerFarm";
    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;

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

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

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

    Element serverFarmElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ServerFarm");
    requestDoc.appendChild(serverFarmElement);

    if (parameters.getCurrentNumberOfWorkers() != null) {
        Element currentNumberOfWorkersElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
        currentNumberOfWorkersElement.appendChild(
                requestDoc.createTextNode(Integer.toString(parameters.getCurrentNumberOfWorkers())));
        serverFarmElement.appendChild(currentNumberOfWorkersElement);
    }

    if (parameters.getCurrentWorkerSize() != null) {
        Element currentWorkerSizeElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
        currentWorkerSizeElement
                .appendChild(requestDoc.createTextNode(parameters.getCurrentWorkerSize().toString()));
        serverFarmElement.appendChild(currentWorkerSizeElement);
    }

    Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
    nameElement.appendChild(requestDoc.createTextNode("DefaultServerFarm"));
    serverFarmElement.appendChild(nameElement);

    Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "NumberOfWorkers");
    numberOfWorkersElement
            .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers())));
    serverFarmElement.appendChild(numberOfWorkersElement);

    Element workerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "WorkerSize");
    workerSizeElement.appendChild(requestDoc.createTextNode(parameters.getWorkerSize().toString()));
    serverFarmElement.appendChild(workerSizeElement);

    if (parameters.getStatus() != null) {
        Element statusElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Status");
        statusElement.appendChild(requestDoc.createTextNode(parameters.getStatus().toString()));
        serverFarmElement.appendChild(statusElement);
    }

    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
        ServerFarmUpdateResponse result = null;
        // Deserialize Response
        InputStream responseContent = httpResponse.getEntity().getContent();
        result = new ServerFarmUpdateResponse();
        DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
        documentBuilderFactory2.setNamespaceAware(true);
        DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
        Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

        Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                "http://schemas.microsoft.com/windowsazure", "ServerFarm");
        if (serverFarmElement2 != null) {
            Element currentNumberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
            if (currentNumberOfWorkersElement2 != null) {
                int currentNumberOfWorkersInstance;
                currentNumberOfWorkersInstance = DatatypeConverter
                        .parseInt(currentNumberOfWorkersElement2.getTextContent());
                result.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance);
            }

            Element currentWorkerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
            if (currentWorkerSizeElement2 != null) {
                ServerFarmWorkerSize currentWorkerSizeInstance;
                currentWorkerSizeInstance = ServerFarmWorkerSize
                        .valueOf(currentWorkerSizeElement2.getTextContent());
                result.setCurrentWorkerSize(currentWorkerSizeInstance);
            }

            Element nameElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "Name");
            if (nameElement2 != null) {
                String nameInstance;
                nameInstance = nameElement2.getTextContent();
                result.setName(nameInstance);
            }

            Element numberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers");
            if (numberOfWorkersElement2 != null) {
                int numberOfWorkersInstance;
                numberOfWorkersInstance = DatatypeConverter.parseInt(numberOfWorkersElement2.getTextContent());
                result.setNumberOfWorkers(numberOfWorkersInstance);
            }

            Element workerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "WorkerSize");
            if (workerSizeElement2 != null) {
                ServerFarmWorkerSize workerSizeInstance;
                workerSizeInstance = ServerFarmWorkerSize.valueOf(workerSizeElement2.getTextContent());
                result.setWorkerSize(workerSizeInstance);
            }

            Element statusElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "Status");
            if (statusElement2 != null) {
                ServerFarmStatus statusInstance;
                statusInstance = ServerFarmStatus.valueOf(statusElement2.getTextContent());
                result.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();
        }
    }
}