Example usage for org.w3c.dom Document createElementNS

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

Introduction

In this page you can find the example usage for org.w3c.dom Document createElementNS.

Prototype

public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;

Source Link

Document

Creates an element of the given qualified name and namespace URI.

Usage

From source file:com.microsoft.windowsazure.management.compute.LoadBalancerOperationsImpl.java

/**
* Add an internal load balancer to a an existing deployment. When used by
* an input endpoint, the internal load balancer will provide an additional
* private VIP that can be used for load balancing to the roles in this
* deployment./*  www . ja  va2 s  .  c om*/
*
* @param serviceName Required. The name of the service.
* @param deploymentName Required. The name of the deployment.
* @param parameters Required. Parameters supplied to the Create Load
* Balancer 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 response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
@Override
public OperationStatusResponse beginCreating(String serviceName, String deploymentName,
        LoadBalancerCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    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("serviceName", serviceName);
        tracingParameters.put("deploymentName", deploymentName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginCreatingAsync", 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/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/loadbalancers";
    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", "2015-04-01");

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

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

    if (parameters.getName() != null) {
        Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
        nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
        loadBalancerElement.appendChild(nameElement);
    }

    if (parameters.getFrontendIPConfiguration() != null) {
        Element frontendIpConfigurationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendIpConfiguration");
        loadBalancerElement.appendChild(frontendIpConfigurationElement);

        if (parameters.getFrontendIPConfiguration().getType() != null) {
            Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Type");
            typeElement
                    .appendChild(requestDoc.createTextNode(parameters.getFrontendIPConfiguration().getType()));
            frontendIpConfigurationElement.appendChild(typeElement);
        }

        if (parameters.getFrontendIPConfiguration().getSubnetName() != null) {
            Element subnetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "SubnetName");
            subnetNameElement.appendChild(
                    requestDoc.createTextNode(parameters.getFrontendIPConfiguration().getSubnetName()));
            frontendIpConfigurationElement.appendChild(subnetNameElement);
        }

        if (parameters.getFrontendIPConfiguration().getStaticVirtualNetworkIPAddress() != null) {
            Element staticVirtualNetworkIPAddressElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress");
            staticVirtualNetworkIPAddressElement.appendChild(requestDoc.createTextNode(parameters
                    .getFrontendIPConfiguration().getStaticVirtualNetworkIPAddress().getHostAddress()));
            frontendIpConfigurationElement.appendChild(staticVirtualNetworkIPAddressElement);
        }
    }

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

        // Create Result
        OperationStatusResponse result = null;
        // Deserialize Response
        result = new OperationStatusResponse();
        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.compute.LoadBalancerOperationsImpl.java

/**
* Updates an internal load balancer associated with an existing deployment.
*
* @param serviceName Required. The name of the service.
* @param deploymentName Required. The name of the deployment.
* @param loadBalancerName Required. The name of the loadBalancer.
* @param parameters Required. Parameters supplied to the Update Load
* Balancer operation.//  w  ww.  j av  a2 s.co  m
* @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 response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
@Override
public OperationStatusResponse beginUpdating(String serviceName, String deploymentName, String loadBalancerName,
        LoadBalancerUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (loadBalancerName == null) {
        throw new NullPointerException("loadBalancerName");
    }
    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("serviceName", serviceName);
        tracingParameters.put("deploymentName", deploymentName);
        tracingParameters.put("loadBalancerName", loadBalancerName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginUpdatingAsync", 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/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/loadbalancers/";
    url = url + URLEncoder.encode(loadBalancerName, "UTF-8");
    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
    HttpPut httpRequest = new HttpPut(url);

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

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

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

    if (parameters.getName() != null) {
        Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
        nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
        loadBalancerElement.appendChild(nameElement);
    }

    if (parameters.getFrontendIPConfiguration() != null) {
        Element frontendIpConfigurationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendIpConfiguration");
        loadBalancerElement.appendChild(frontendIpConfigurationElement);

        if (parameters.getFrontendIPConfiguration().getType() != null) {
            Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Type");
            typeElement
                    .appendChild(requestDoc.createTextNode(parameters.getFrontendIPConfiguration().getType()));
            frontendIpConfigurationElement.appendChild(typeElement);
        }

        if (parameters.getFrontendIPConfiguration().getSubnetName() != null) {
            Element subnetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "SubnetName");
            subnetNameElement.appendChild(
                    requestDoc.createTextNode(parameters.getFrontendIPConfiguration().getSubnetName()));
            frontendIpConfigurationElement.appendChild(subnetNameElement);
        }

        if (parameters.getFrontendIPConfiguration().getStaticVirtualNetworkIPAddress() != null) {
            Element staticVirtualNetworkIPAddressElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress");
            staticVirtualNetworkIPAddressElement.appendChild(requestDoc.createTextNode(parameters
                    .getFrontendIPConfiguration().getStaticVirtualNetworkIPAddress().getHostAddress()));
            frontendIpConfigurationElement.appendChild(staticVirtualNetworkIPAddressElement);
        }
    }

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

        // Create Result
        OperationStatusResponse result = null;
        // Deserialize Response
        result = new OperationStatusResponse();
        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:org.apache.cxf.cwiki.SiteExporter.java

public Future<?> loadPage(Element pageSumEl, final Set<String> allPages, final Set<Page> newPages)
        throws Exception {
    Document doc = DOMUtils.newDocument();
    Element el = doc.createElementNS(SOAPNS, "ns1:getPage");
    Element el2 = doc.createElement("in0");
    el.appendChild(el2);/*from   w  w  w.  j a  v  a 2  s  .  c  o  m*/
    el2.setTextContent(loginToken);
    el2 = doc.createElement("in1");
    el.appendChild(el2);
    el2.setTextContent(DOMUtils.getChildContent(pageSumEl, "id"));
    doc.appendChild(el);

    //make sure we only fire off about 15-20 or confluence may get a bit overloaded
    while (asyncCount.get() > 15) {
        Thread.sleep(10);
    }
    asyncCount.incrementAndGet();
    Future<?> f = getDispatch().invokeAsync(doc, new AsyncHandler<Document>() {
        public void handleResponse(Response<Document> doc) {
            try {
                Page page = new Page(doc.get(), SiteExporter.this);
                page.setExporter(SiteExporter.this);
                Page oldPage = pages.put(page.getId(), page);
                if (oldPage == null || page.getModifiedTime().compare(oldPage.getModifiedTime()) > 0) {
                    if (!modifiedPages.contains(page)) {
                        modifiedPages.add(page);
                    }
                    if (oldPage == null) {
                        //need to check parents to see if it has a {children} tag so we can re-render
                        newPages.add(page);
                    }
                }
                if (allPages.contains(page.getId())) {
                    allPages.remove(page.getId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                asyncCount.decrementAndGet();
            }
        }
    });
    return f;
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

public void loadBlog() throws Exception {
    System.out.println("Loading Blog entries for " + spaceKey);
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(SOAPNS, "ns1:getBlogEntries");
    Element el2 = doc.createElement("in0");
    el.appendChild(el2);/*  w w  w . j a va  2 s.  co m*/
    el2.setTextContent(loginToken);
    el2 = doc.createElement("in1");
    el.appendChild(el2);
    el2.setTextContent(spaceKey);
    doc.appendChild(el);
    doc = getDispatch().invoke(doc);

    Map<String, BlogEntrySummary> oldBlog = new ConcurrentHashMap<String, BlogEntrySummary>(blog);

    Node nd = doc.getDocumentElement().getFirstChild().getFirstChild();
    while (nd != null) {
        if (nd instanceof Element) {
            BlogEntrySummary entry = new BlogEntrySummary((Element) nd);
            entry.setVersion(getBlogVersion(entry.id));
            BlogEntrySummary oldEntry = blog.put(entry.getId(), entry);
            System.out.println("Found Blog entry for " + entry.getTitle() + " " + entry.getPath());

            if (oldEntry == null || oldEntry.getVersion() != entry.getVersion()) {
                System.out.println("   and it's modified");
                modifiedBlog.add(entry);
            } else {
                System.out.println("   but it's not modified");
            }
            oldBlog.remove(entry.getId());
        }
        nd = nd.getNextSibling();
    }

    for (String id : oldBlog.keySet()) {
        //these pages have been deleted
        BlogEntrySummary p = blog.remove(id);
        File file = new File(outputDir, p.getPath());
        if (file.exists()) {
            callSvn("rm", file.getAbsolutePath());
            svnCommitMessage.append("Deleted: " + file.getName() + "\n");
        }
        if (file.exists()) {
            file.delete();
        }
    }
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

public void loadPages() throws Exception {
    Document doc = DOMUtils.newDocument();
    Element el = doc.createElementNS(SOAPNS, "ns1:getPages");
    Element el2 = doc.createElement("in0");
    el.appendChild(el2);//  w  w  w  .ja  v a  2s. c  om
    el2.setTextContent(loginToken);
    el2 = doc.createElement("in1");
    el.appendChild(el2);
    el2.setTextContent(spaceKey);
    doc.appendChild(el);
    doc = getDispatch().invoke(doc);

    Set<String> allPages = new CopyOnWriteArraySet<String>(pages.keySet());
    Set<Page> newPages = new CopyOnWriteArraySet<Page>();
    List<Future<?>> futures = new ArrayList<Future<?>>(allPages.size());

    // XMLUtils.printDOM(doc.getDocumentElement());

    Node nd = doc.getDocumentElement().getFirstChild().getFirstChild();
    while (nd != null) {
        if (nd instanceof Element) {
            futures.add(loadPage((Element) nd, allPages, newPages));
        }
        nd = nd.getNextSibling();
    }
    for (Future<?> f : futures) {
        //wait for all the pages to be done
        f.get();
    }
    for (Page p : newPages) {
        //pages have been added, need to check
        checkForChildren(p);
    }
    for (String id : allPages) {
        //these pages have been deleted
        Page p = pages.remove(id);
        checkForChildren(p);

        File file = new File(outputDir, p.createFileName());
        if (file.exists()) {
            callSvn("rm", file.getAbsolutePath());
            svnCommitMessage.append("Deleted: " + file.getName() + "\n");
        }
        if (file.exists()) {
            file.delete();
        }
    }
    while (checkIncludes()) {
        // nothing
    }

}

From source file:org.apache.cxf.cwiki.SiteExporter.java

private void loadAttachments(AbstractPage p) throws Exception {
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(SOAPNS, "ns1:getAttachments");
    Element el2 = doc.createElement("in0");
    el.appendChild(el2);/* ww  w.  j  ava 2 s. com*/
    el2.setTextContent(loginToken);
    el2 = doc.createElement("in1");
    el.appendChild(el2);
    el2.setTextContent(p.getId());
    el.appendChild(el2);
    doc.appendChild(el);

    doc = getDispatch().invoke(doc);
    el = DOMUtils.getFirstElement(DOMUtils.getFirstElement(doc.getDocumentElement()));
    while (el != null) {
        try {
            String filename = DOMUtils.getChildContent(el, "fileName");
            String durl = DOMUtils.getChildContent(el, "url");
            String aid = DOMUtils.getChildContent(el, "id");

            p.addAttachment(aid, filename);

            String dirName = p.getPath();
            dirName = dirName.substring(0, dirName.lastIndexOf(".")) + ".data";
            File file = new File(outputDir, dirName);
            if (!file.exists()) {
                callSvn("mkdir", file.getAbsolutePath());
                file.mkdirs();
            }
            filename = filename.replace(' ', '-');
            file = new File(file, filename);
            boolean exists = file.exists();
            FileOutputStream out = new FileOutputStream(file);
            URL url = new URL(durl);
            InputStream ins = url.openStream();
            IOUtils.copy(ins, out);
            out.close();
            ins.close();
            if (!exists) {
                callSvn("add", file.getAbsolutePath());
                svnCommitMessage.append("Added: " + dirName + "/" + file.getName() + "\n");
            } else {
                svnCommitMessage.append("Modified: " + dirName + "/" + file.getName() + "\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        el = DOMUtils.getNextElement(el);
    }
}

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

/**
* Adds a new server-level Firewall Rule for an Azure SQL Database Server.
*
* @param serverName Required. The name of the Azure SQL Database Server to
* which this rule will be applied./*from   w ww  .java2 s .c o  m*/
* @param parameters Required. The parameters for the Create Firewall Rule
* 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 Contains the response to a Create Firewall Rule operation.
*/
@Override
public FirewallRuleCreateResponse create(String serverName, FirewallRuleCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getEndIPAddress() == null) {
        throw new NullPointerException("parameters.EndIPAddress");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getStartIPAddress() == null) {
        throw new NullPointerException("parameters.StartIPAddress");
    }

    // 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, "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/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/firewallrules";
    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 serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ServiceResource");
    requestDoc.appendChild(serviceResourceElement);

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

    Element startIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "StartIPAddress");
    startIPAddressElement
            .appendChild(requestDoc.createTextNode(parameters.getStartIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(startIPAddressElement);

    Element endIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "EndIPAddress");
    endIPAddressElement.appendChild(requestDoc.createTextNode(parameters.getEndIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(endIPAddressElement);

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

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

            Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResource");
            if (serviceResourceElement2 != null) {
                FirewallRule serviceResourceInstance = new FirewallRule();
                result.setFirewallRule(serviceResourceInstance);

                Element startIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "StartIPAddress");
                if (startIPAddressElement2 != null) {
                    InetAddress startIPAddressInstance;
                    startIPAddressInstance = InetAddress.getByName(startIPAddressElement2.getTextContent());
                    serviceResourceInstance.setStartIPAddress(startIPAddressInstance);
                }

                Element endIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "EndIPAddress");
                if (endIPAddressElement2 != null) {
                    InetAddress endIPAddressInstance;
                    endIPAddressInstance = InetAddress.getByName(endIPAddressElement2.getTextContent());
                    serviceResourceInstance.setEndIPAddress(endIPAddressInstance);
                }

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

                Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Type");
                if (typeElement != null) {
                    String typeInstance;
                    typeInstance = typeElement.getTextContent();
                    serviceResourceInstance.setType(typeInstance);
                }

                Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "State");
                if (stateElement != null) {
                    String stateInstance;
                    stateInstance = stateElement.getTextContent();
                    serviceResourceInstance.setState(stateInstance);
                }
            }

        }
        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.AffinityGroupOperationsImpl.java

/**
* The Update Affinity Group operation updates the label and/or the
* description for an affinity group for the specified subscription.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx for
* more information)/*  ww w. ja va2s .c  o m*/
*
* @param affinityGroupName Required. The name of the affinity group.
* @param parameters Required. Parameters supplied to the Update Affinity
* Group 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 A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse update(String affinityGroupName, AffinityGroupUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (affinityGroupName == null) {
        throw new NullPointerException("affinityGroupName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) {
        throw new IllegalArgumentException("parameters.Description");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getLabel().length() > 100) {
        throw new IllegalArgumentException("parameters.Label");
    }

    // 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("affinityGroupName", affinityGroupName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "updateAsync", 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 + "/affinitygroups/";
    url = url + URLEncoder.encode(affinityGroupName, "UTF-8");
    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
    HttpPut httpRequest = new HttpPut(url);

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

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

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

    Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
    labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes())));
    updateAffinityGroupElement.appendChild(labelElement);

    if (parameters.getDescription() != null) {
        Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
        updateAffinityGroupElement.appendChild(descriptionElement);
    }

    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
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        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.FirewallRuleOperationsImpl.java

/**
* Updates an existing server-level Firewall Rule for an Azure SQL Database
* Server./*from  ww w . j a  v  a 2  s  .  co m*/
*
* @param serverName Required. The name of the Azure SQL Database Server
* that has the Firewall Rule to be updated.
* @param ruleName Required. The name of the Firewall Rule to be updated.
* @param parameters Required. The parameters for the Update Firewall Rule
* 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 Represents the firewall rule update response.
*/
@Override
public FirewallRuleUpdateResponse update(String serverName, String ruleName,
        FirewallRuleUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (ruleName == null) {
        throw new NullPointerException("ruleName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getEndIPAddress() == null) {
        throw new NullPointerException("parameters.EndIPAddress");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getStartIPAddress() == null) {
        throw new NullPointerException("parameters.StartIPAddress");
    }

    // 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("ruleName", ruleName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "updateAsync", 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 + "/firewallrules/";
    url = url + URLEncoder.encode(ruleName, "UTF-8");
    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
    HttpPut httpRequest = new HttpPut(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 serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ServiceResource");
    requestDoc.appendChild(serviceResourceElement);

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

    Element startIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "StartIPAddress");
    startIPAddressElement
            .appendChild(requestDoc.createTextNode(parameters.getStartIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(startIPAddressElement);

    Element endIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "EndIPAddress");
    endIPAddressElement.appendChild(requestDoc.createTextNode(parameters.getEndIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(endIPAddressElement);

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

            Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResource");
            if (serviceResourceElement2 != null) {
                FirewallRule serviceResourceInstance = new FirewallRule();
                result.setFirewallRule(serviceResourceInstance);

                Element startIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "StartIPAddress");
                if (startIPAddressElement2 != null) {
                    InetAddress startIPAddressInstance;
                    startIPAddressInstance = InetAddress.getByName(startIPAddressElement2.getTextContent());
                    serviceResourceInstance.setStartIPAddress(startIPAddressInstance);
                }

                Element endIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "EndIPAddress");
                if (endIPAddressElement2 != null) {
                    InetAddress endIPAddressInstance;
                    endIPAddressInstance = InetAddress.getByName(endIPAddressElement2.getTextContent());
                    serviceResourceInstance.setEndIPAddress(endIPAddressInstance);
                }

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

                Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Type");
                if (typeElement != null) {
                    String typeInstance;
                    typeInstance = typeElement.getTextContent();
                    serviceResourceInstance.setType(typeInstance);
                }

                Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "State");
                if (stateElement != null) {
                    String stateInstance;
                    stateInstance = stateElement.getTextContent();
                    serviceResourceInstance.setState(stateInstance);
                }
            }

        }
        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.AffinityGroupOperationsImpl.java

/**
* The Create Affinity Group operation creates a new affinity group for the
* specified subscription.  (see/*from   w w  w  . j  av a2 s . co  m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx for
* more information)
*
* @param parameters Required. Parameters supplied to the Create Affinity
* Group 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 A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse create(AffinityGroupCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) {
        throw new IllegalArgumentException("parameters.Description");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getLabel().length() > 100) {
        throw new IllegalArgumentException("parameters.Label");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }

    // 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 + "/affinitygroups";
    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", "2014-10-01");

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

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

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

    Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
    labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes())));
    createAffinityGroupElement.appendChild(labelElement);

    if (parameters.getDescription() != null) {
        Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
        createAffinityGroupElement.appendChild(descriptionElement);
    }

    Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "Location");
    locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation()));
    createAffinityGroupElement.appendChild(locationElement);

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

        // Create Result
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        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();
        }
    }
}