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.scheduler.JobCollectionOperationsImpl.java

/**
* Update a job collection.//www .ja v  a2s  . c  o m
*
* @param cloudServiceName Required. The name of the cloud service
* containing the job collection.
* @param jobCollectionName Required. The name of the job collection to
* update.
* @param parameters Required. Parameters supplied to the Update Job
* Collection 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 Update Job Collection operation response.
*/
@Override
public JobCollectionUpdateResponse beginUpdating(String cloudServiceName, String jobCollectionName,
        JobCollectionUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (cloudServiceName == null) {
        throw new NullPointerException("cloudServiceName");
    }
    if (jobCollectionName == null) {
        throw new NullPointerException("jobCollectionName");
    }
    if (jobCollectionName.length() > 100) {
        throw new IllegalArgumentException("jobCollectionName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getETag() == null) {
        throw new NullPointerException("parameters.ETag");
    }
    if (parameters.getIntrinsicSettings() != null) {
        if (parameters.getIntrinsicSettings().getQuota() != null) {
            if (parameters.getIntrinsicSettings().getQuota().getMaxRecurrence() != null) {
                if (parameters.getIntrinsicSettings().getQuota().getMaxRecurrence().getFrequency() == null) {
                    throw new NullPointerException(
                            "parameters.IntrinsicSettings.Quota.MaxRecurrence.Frequency");
                }
            }
        }
    }

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

    // Construct URL
    String url = "";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/cloudservices/";
    url = url + URLEncoder.encode(cloudServiceName, "UTF-8");
    url = url + "/resources/";
    url = url + "scheduler";
    url = url + "/";
    url = url + "JobCollections";
    url = url + "/";
    url = url + URLEncoder.encode(jobCollectionName, "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("If-Match", parameters.getETag());
    httpRequest.setHeader("x-ms-version", "2013-03-01");

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

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

    if (parameters.getSchemaVersion() != null) {
        Element schemaVersionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "SchemaVersion");
        schemaVersionElement.appendChild(requestDoc.createTextNode(parameters.getSchemaVersion()));
        resourceElement.appendChild(schemaVersionElement);
    }

    Element eTagElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ETag");
    resourceElement.appendChild(eTagElement);

    if (parameters.getIntrinsicSettings() != null) {
        Element intrinsicSettingsElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "IntrinsicSettings");
        resourceElement.appendChild(intrinsicSettingsElement);

        if (parameters.getIntrinsicSettings().getPlan() != null) {
            Element planElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Plan");
            planElement.appendChild(
                    requestDoc.createTextNode(parameters.getIntrinsicSettings().getPlan().toString()));
            intrinsicSettingsElement.appendChild(planElement);
        }

        if (parameters.getIntrinsicSettings().getQuota() != null) {
            Element quotaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Quota");
            intrinsicSettingsElement.appendChild(quotaElement);

            if (parameters.getIntrinsicSettings().getQuota().getMaxJobCount() != null) {
                Element maxJobCountElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "MaxJobCount");
                maxJobCountElement.appendChild(requestDoc.createTextNode(
                        Integer.toString(parameters.getIntrinsicSettings().getQuota().getMaxJobCount())));
                quotaElement.appendChild(maxJobCountElement);
            }

            if (parameters.getIntrinsicSettings().getQuota().getMaxJobOccurrence() != null) {
                Element maxJobOccurrenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "MaxJobOccurrence");
                maxJobOccurrenceElement.appendChild(requestDoc.createTextNode(
                        Integer.toString(parameters.getIntrinsicSettings().getQuota().getMaxJobOccurrence())));
                quotaElement.appendChild(maxJobOccurrenceElement);
            }

            if (parameters.getIntrinsicSettings().getQuota().getMaxRecurrence() != null) {
                Element maxRecurrenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "MaxRecurrence");
                quotaElement.appendChild(maxRecurrenceElement);

                Element frequencyElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Frequency");
                frequencyElement.appendChild(requestDoc.createTextNode(parameters.getIntrinsicSettings()
                        .getQuota().getMaxRecurrence().getFrequency().toString()));
                maxRecurrenceElement.appendChild(frequencyElement);

                Element intervalElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Interval");
                intervalElement.appendChild(requestDoc.createTextNode(Integer.toString(
                        parameters.getIntrinsicSettings().getQuota().getMaxRecurrence().getInterval())));
                maxRecurrenceElement.appendChild(intervalElement);
            }
        }
    }

    if (parameters.getLabel() != null) {
        Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
        labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes())));
        resourceElement.appendChild(labelElement);
    }

    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
        JobCollectionUpdateResponse result = null;
        // Deserialize Response
        result = new JobCollectionUpdateResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("ETag").length > 0) {
            result.setETag(httpResponse.getFirstHeader("ETag").getValue());
        }
        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.network.ReservedIPOperationsImpl.java

/**
* The BeginAssociate begins to associate a Reserved IP with a service.
*
* @param reservedIpName Required. The name of the reserved IP.
* @param parameters Required. Parameters supplied to the Begin associating
* Reserved IP./*  w  w  w  . j  a va 2  s.c  om*/
* @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 also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse beginAssociating(String reservedIpName,
        NetworkReservedIPMobilityParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (reservedIpName == null) {
        throw new NullPointerException("reservedIpName");
    }
    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("reservedIpName", reservedIpName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginAssociatingAsync", 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/networking/reservedips/";
    url = url + URLEncoder.encode(reservedIpName, "UTF-8");
    url = url + "/operations/associate";
    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 reservedIPAssociationElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "ReservedIPAssociation");
    requestDoc.appendChild(reservedIPAssociationElement);

    if (parameters.getServiceName() != null) {
        Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ServiceName");
        serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getServiceName()));
        reservedIPAssociationElement.appendChild(serviceNameElement);
    }

    if (parameters.getDeploymentName() != null) {
        Element deploymentNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "DeploymentName");
        deploymentNameElement.appendChild(requestDoc.createTextNode(parameters.getDeploymentName()));
        reservedIPAssociationElement.appendChild(deploymentNameElement);
    }

    if (parameters.getVirtualIPName() != null) {
        Element virtualIPNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "VirtualIPName");
        virtualIPNameElement.appendChild(requestDoc.createTextNode(parameters.getVirtualIPName()));
        reservedIPAssociationElement.appendChild(virtualIPNameElement);
    }

    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.network.ReservedIPOperationsImpl.java

/**
* The BeginDisassociate begins to disassociate a Reserved IP from a service.
*
* @param reservedIpName Required. The name of the reserved IP.
* @param parameters Required. Parameters supplied to the Begin
* disassociating Reserved IP.//  w w w .  j  av a2 s  .c  o  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 also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse beginDisassociating(String reservedIpName,
        NetworkReservedIPMobilityParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (reservedIpName == null) {
        throw new NullPointerException("reservedIpName");
    }
    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("reservedIpName", reservedIpName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginDisassociatingAsync", 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/networking/reservedips/";
    url = url + URLEncoder.encode(reservedIpName, "UTF-8");
    url = url + "/operations/disassociate";
    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 reservedIPAssociationElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "ReservedIPAssociation");
    requestDoc.appendChild(reservedIPAssociationElement);

    if (parameters.getServiceName() != null) {
        Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ServiceName");
        serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getServiceName()));
        reservedIPAssociationElement.appendChild(serviceNameElement);
    }

    if (parameters.getDeploymentName() != null) {
        Element deploymentNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "DeploymentName");
        deploymentNameElement.appendChild(requestDoc.createTextNode(parameters.getDeploymentName()));
        reservedIPAssociationElement.appendChild(deploymentNameElement);
    }

    if (parameters.getVirtualIPName() != null) {
        Element virtualIPNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "VirtualIPName");
        virtualIPNameElement.appendChild(requestDoc.createTextNode(parameters.getVirtualIPName()));
        reservedIPAssociationElement.appendChild(virtualIPNameElement);
    }

    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.network.ReservedIPOperationsImpl.java

/**
* The Begin Creating Reserved IP operation creates a reserved IP from your
* the subscription./*from ww  w .j a  va2  s . c  o m*/
*
* @param parameters Required. Parameters supplied to the Begin Creating
* Reserved IP 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 also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse beginCreating(NetworkReservedIPCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    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("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/networking/reservedips";
    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 reservedIPElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ReservedIP");
    requestDoc.appendChild(reservedIPElement);

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

    if (parameters.getLabel() != null) {
        Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
        labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel()));
        reservedIPElement.appendChild(labelElement);
    }

    if (parameters.getServiceName() != null) {
        Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ServiceName");
        serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getServiceName()));
        reservedIPElement.appendChild(serviceNameElement);
    }

    if (parameters.getDeploymentName() != null) {
        Element deploymentNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "DeploymentName");
        deploymentNameElement.appendChild(requestDoc.createTextNode(parameters.getDeploymentName()));
        reservedIPElement.appendChild(deploymentNameElement);
    }

    if (parameters.getLocation() != null) {
        Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Location");
        locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation()));
        reservedIPElement.appendChild(locationElement);
    }

    if (parameters.getVirtualIPName() != null) {
        Element virtualIPNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "VirtualIPName");
        virtualIPNameElement.appendChild(requestDoc.createTextNode(parameters.getVirtualIPName()));
        reservedIPElement.appendChild(virtualIPNameElement);
    }

    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.sql.DatabaseCopyOperationsImpl.java

/**
* Updates a SQL Server database copy./*from w ww  . jav  a2  s .co  m*/
*
* @param serverName Required. The name of the source or destination SQL
* Server instance.
* @param databaseName Required. The name of the database.
* @param databaseCopyName Required. The unique identifier for the database
* copy to update.
* @param parameters Required. The additional parameters for the update
* database copy 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 a response to the update request.
*/
@Override
public DatabaseCopyUpdateResponse update(String serverName, String databaseName, String databaseCopyName,
        DatabaseCopyUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }
    if (databaseCopyName == null) {
        throw new NullPointerException("databaseCopyName");
    }
    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("serverName", serverName);
        tracingParameters.put("databaseName", databaseName);
        tracingParameters.put("databaseCopyName", databaseCopyName);
        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 + "/databases/";
    url = url + URLEncoder.encode(databaseName, "UTF-8");
    url = url + "/databasecopies/";
    url = url + URLEncoder.encode(databaseCopyName, "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);

    if (parameters.isForcedTerminate() != null) {
        Element isForcedTerminateElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "IsForcedTerminate");
        isForcedTerminateElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isForcedTerminate()).toLowerCase()));
        serviceResourceElement.appendChild(isForcedTerminateElement);
    }

    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
        DatabaseCopyUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DatabaseCopyUpdateResponse();
            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) {
                DatabaseCopy serviceResourceInstance = new DatabaseCopy();
                result.setDatabaseCopy(serviceResourceInstance);

                Element sourceServerNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SourceServerName");
                if (sourceServerNameElement != null) {
                    String sourceServerNameInstance;
                    sourceServerNameInstance = sourceServerNameElement.getTextContent();
                    serviceResourceInstance.setSourceServerName(sourceServerNameInstance);
                }

                Element sourceDatabaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SourceDatabaseName");
                if (sourceDatabaseNameElement != null) {
                    String sourceDatabaseNameInstance;
                    sourceDatabaseNameInstance = sourceDatabaseNameElement.getTextContent();
                    serviceResourceInstance.setSourceDatabaseName(sourceDatabaseNameInstance);
                }

                Element destinationServerNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "DestinationServerName");
                if (destinationServerNameElement != null) {
                    String destinationServerNameInstance;
                    destinationServerNameInstance = destinationServerNameElement.getTextContent();
                    serviceResourceInstance.setDestinationServerName(destinationServerNameInstance);
                }

                Element destinationDatabaseNameElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "DestinationDatabaseName");
                if (destinationDatabaseNameElement != null) {
                    String destinationDatabaseNameInstance;
                    destinationDatabaseNameInstance = destinationDatabaseNameElement.getTextContent();
                    serviceResourceInstance.setDestinationDatabaseName(destinationDatabaseNameInstance);
                }

                Element isContinuousElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsContinuous");
                if (isContinuousElement != null) {
                    boolean isContinuousInstance;
                    isContinuousInstance = DatatypeConverter
                            .parseBoolean(isContinuousElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsContinuous(isContinuousInstance);
                }

                Element replicationStateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "ReplicationState");
                if (replicationStateElement != null) {
                    byte replicationStateInstance;
                    replicationStateInstance = DatatypeConverter
                            .parseByte(replicationStateElement.getTextContent());
                    serviceResourceInstance.setReplicationState(replicationStateInstance);
                }

                Element replicationStateDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ReplicationStateDescription");
                if (replicationStateDescriptionElement != null) {
                    String replicationStateDescriptionInstance;
                    replicationStateDescriptionInstance = replicationStateDescriptionElement.getTextContent();
                    serviceResourceInstance.setReplicationStateDescription(replicationStateDescriptionInstance);
                }

                Element localDatabaseIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "LocalDatabaseId");
                if (localDatabaseIdElement != null) {
                    int localDatabaseIdInstance;
                    localDatabaseIdInstance = DatatypeConverter
                            .parseInt(localDatabaseIdElement.getTextContent());
                    serviceResourceInstance.setLocalDatabaseId(localDatabaseIdInstance);
                }

                Element isLocalDatabaseReplicationTargetElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "IsLocalDatabaseReplicationTarget");
                if (isLocalDatabaseReplicationTargetElement != null) {
                    boolean isLocalDatabaseReplicationTargetInstance;
                    isLocalDatabaseReplicationTargetInstance = DatatypeConverter.parseBoolean(
                            isLocalDatabaseReplicationTargetElement.getTextContent().toLowerCase());
                    serviceResourceInstance
                            .setIsLocalDatabaseReplicationTarget(isLocalDatabaseReplicationTargetInstance);
                }

                Element isInterlinkConnectedElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsInterlinkConnected");
                if (isInterlinkConnectedElement != null) {
                    boolean isInterlinkConnectedInstance;
                    isInterlinkConnectedInstance = DatatypeConverter
                            .parseBoolean(isInterlinkConnectedElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsInterlinkConnected(isInterlinkConnectedInstance);
                }

                Element startDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "StartDate");
                if (startDateElement != null) {
                    String startDateInstance;
                    startDateInstance = startDateElement.getTextContent();
                    serviceResourceInstance.setStartDate(startDateInstance);
                }

                Element modifyDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "ModifyDate");
                if (modifyDateElement != null) {
                    String modifyDateInstance;
                    modifyDateInstance = modifyDateElement.getTextContent();
                    serviceResourceInstance.setModifyDate(modifyDateInstance);
                }

                Element percentCompleteElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "PercentComplete");
                if (percentCompleteElement != null) {
                    float percentCompleteInstance;
                    percentCompleteInstance = DatatypeConverter
                            .parseFloat(percentCompleteElement.getTextContent());
                    serviceResourceInstance.setPercentComplete(percentCompleteInstance);
                }

                Element isOfflineSecondaryElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsOfflineSecondary");
                if (isOfflineSecondaryElement != null) {
                    boolean isOfflineSecondaryInstance;
                    isOfflineSecondaryInstance = DatatypeConverter
                            .parseBoolean(isOfflineSecondaryElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsOfflineSecondary(isOfflineSecondaryInstance);
                }

                Element isTerminationAllowedElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsTerminationAllowed");
                if (isTerminationAllowedElement != null) {
                    boolean isTerminationAllowedInstance;
                    isTerminationAllowedInstance = DatatypeConverter
                            .parseBoolean(isTerminationAllowedElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsTerminationAllowed(isTerminationAllowedInstance);
                }

                Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement != null) {
                    String nameInstance;
                    nameInstance = nameElement.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.sql.DatabaseCopyOperationsImpl.java

/**
* Starts a SQL Server database copy./* w ww .j a v  a 2  s  .com*/
*
* @param serverName Required. The name of the SQL Server where the source
* database resides.
* @param databaseName Required. The name of the source database.
* @param parameters Required. The additional parameters for the create
* database copy 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 a response to the create request.
*/
@Override
public DatabaseCopyCreateResponse create(String serverName, String databaseName,
        DatabaseCopyCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getPartnerDatabase() == null) {
        throw new NullPointerException("parameters.PartnerDatabase");
    }
    if (parameters.getPartnerServer() == null) {
        throw new NullPointerException("parameters.PartnerServer");
    }

    // 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("databaseName", databaseName);
        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 + "/databases/";
    url = url + URLEncoder.encode(databaseName, "UTF-8");
    url = url + "/databasecopies";
    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 partnerServerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "PartnerServer");
    partnerServerElement.appendChild(requestDoc.createTextNode(parameters.getPartnerServer()));
    serviceResourceElement.appendChild(partnerServerElement);

    Element partnerDatabaseElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "PartnerDatabase");
    partnerDatabaseElement.appendChild(requestDoc.createTextNode(parameters.getPartnerDatabase()));
    serviceResourceElement.appendChild(partnerDatabaseElement);

    Element isContinuousElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "IsContinuous");
    isContinuousElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isContinuous()).toLowerCase()));
    serviceResourceElement.appendChild(isContinuousElement);

    Element isOfflineSecondaryElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "IsOfflineSecondary");
    isOfflineSecondaryElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(parameters.isOfflineSecondary()).toLowerCase()));
    serviceResourceElement.appendChild(isOfflineSecondaryElement);

    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
        DatabaseCopyCreateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DatabaseCopyCreateResponse();
            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) {
                DatabaseCopy serviceResourceInstance = new DatabaseCopy();
                result.setDatabaseCopy(serviceResourceInstance);

                Element sourceServerNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SourceServerName");
                if (sourceServerNameElement != null) {
                    String sourceServerNameInstance;
                    sourceServerNameInstance = sourceServerNameElement.getTextContent();
                    serviceResourceInstance.setSourceServerName(sourceServerNameInstance);
                }

                Element sourceDatabaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SourceDatabaseName");
                if (sourceDatabaseNameElement != null) {
                    String sourceDatabaseNameInstance;
                    sourceDatabaseNameInstance = sourceDatabaseNameElement.getTextContent();
                    serviceResourceInstance.setSourceDatabaseName(sourceDatabaseNameInstance);
                }

                Element destinationServerNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "DestinationServerName");
                if (destinationServerNameElement != null) {
                    String destinationServerNameInstance;
                    destinationServerNameInstance = destinationServerNameElement.getTextContent();
                    serviceResourceInstance.setDestinationServerName(destinationServerNameInstance);
                }

                Element destinationDatabaseNameElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "DestinationDatabaseName");
                if (destinationDatabaseNameElement != null) {
                    String destinationDatabaseNameInstance;
                    destinationDatabaseNameInstance = destinationDatabaseNameElement.getTextContent();
                    serviceResourceInstance.setDestinationDatabaseName(destinationDatabaseNameInstance);
                }

                Element isContinuousElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsContinuous");
                if (isContinuousElement2 != null) {
                    boolean isContinuousInstance;
                    isContinuousInstance = DatatypeConverter
                            .parseBoolean(isContinuousElement2.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsContinuous(isContinuousInstance);
                }

                Element replicationStateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "ReplicationState");
                if (replicationStateElement != null) {
                    byte replicationStateInstance;
                    replicationStateInstance = DatatypeConverter
                            .parseByte(replicationStateElement.getTextContent());
                    serviceResourceInstance.setReplicationState(replicationStateInstance);
                }

                Element replicationStateDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ReplicationStateDescription");
                if (replicationStateDescriptionElement != null) {
                    String replicationStateDescriptionInstance;
                    replicationStateDescriptionInstance = replicationStateDescriptionElement.getTextContent();
                    serviceResourceInstance.setReplicationStateDescription(replicationStateDescriptionInstance);
                }

                Element localDatabaseIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "LocalDatabaseId");
                if (localDatabaseIdElement != null) {
                    int localDatabaseIdInstance;
                    localDatabaseIdInstance = DatatypeConverter
                            .parseInt(localDatabaseIdElement.getTextContent());
                    serviceResourceInstance.setLocalDatabaseId(localDatabaseIdInstance);
                }

                Element isLocalDatabaseReplicationTargetElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "IsLocalDatabaseReplicationTarget");
                if (isLocalDatabaseReplicationTargetElement != null) {
                    boolean isLocalDatabaseReplicationTargetInstance;
                    isLocalDatabaseReplicationTargetInstance = DatatypeConverter.parseBoolean(
                            isLocalDatabaseReplicationTargetElement.getTextContent().toLowerCase());
                    serviceResourceInstance
                            .setIsLocalDatabaseReplicationTarget(isLocalDatabaseReplicationTargetInstance);
                }

                Element isInterlinkConnectedElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsInterlinkConnected");
                if (isInterlinkConnectedElement != null) {
                    boolean isInterlinkConnectedInstance;
                    isInterlinkConnectedInstance = DatatypeConverter
                            .parseBoolean(isInterlinkConnectedElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsInterlinkConnected(isInterlinkConnectedInstance);
                }

                Element startDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "StartDate");
                if (startDateElement != null) {
                    String startDateInstance;
                    startDateInstance = startDateElement.getTextContent();
                    serviceResourceInstance.setStartDate(startDateInstance);
                }

                Element modifyDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "ModifyDate");
                if (modifyDateElement != null) {
                    String modifyDateInstance;
                    modifyDateInstance = modifyDateElement.getTextContent();
                    serviceResourceInstance.setModifyDate(modifyDateInstance);
                }

                Element percentCompleteElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "PercentComplete");
                if (percentCompleteElement != null) {
                    float percentCompleteInstance;
                    percentCompleteInstance = DatatypeConverter
                            .parseFloat(percentCompleteElement.getTextContent());
                    serviceResourceInstance.setPercentComplete(percentCompleteInstance);
                }

                Element isOfflineSecondaryElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsOfflineSecondary");
                if (isOfflineSecondaryElement2 != null) {
                    boolean isOfflineSecondaryInstance;
                    isOfflineSecondaryInstance = DatatypeConverter
                            .parseBoolean(isOfflineSecondaryElement2.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsOfflineSecondary(isOfflineSecondaryInstance);
                }

                Element isTerminationAllowedElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsTerminationAllowed");
                if (isTerminationAllowedElement != null) {
                    boolean isTerminationAllowedInstance;
                    isTerminationAllowedInstance = DatatypeConverter
                            .parseBoolean(isTerminationAllowedElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsTerminationAllowed(isTerminationAllowedInstance);
                }

                Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement != null) {
                    String nameInstance;
                    nameInstance = nameElement.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.bluexml.xforms.controller.navigation.NavigationManager.java

/**
 * @param req/*www.j a va2s  . c o  m*/
 * @param sessionId
 * @param pageId
 * @param statusDisplayedMsg
 * @param currentPage
 * @return
 * @throws IOException
 * @throws ServletException
 * @throws DOMException
 */
private Document loadXFormsDocument(HttpServletRequest req, String sessionId, String pageId,
        String statusDisplayedMsg, Page currentPage) throws IOException, ServletException, DOMException {
    String xformsString;
    String dataType = currentPage.getFormName();
    FormTypeEnum formType = currentPage.getFormType();
    boolean dataTypeSet = currentPage.isDataTypeSet();
    String templateId = currentPage.getTemplate();
    String pageLanguage = currentPage.getLanguage();
    Map<String, String> initParams = currentPage.getInitParams();
    xformsString = getXFormsString(formType, dataType, dataTypeSet, templateId, sessionId, pageId,
            req.getContextPath(), pageLanguage, initParams, req);
    Document doc;
    // try {
    // doc = org.chiba.xml.dom.DOMUtil.parseString(xformsString, true, false);
    // } catch (ParserConfigurationException e) {
    // throw new ServletException(e);
    // } catch (SAXException e) {
    // throw new ServletException(e);
    // }
    doc = DOMUtil.getDocumentFromString(xformsString);
    if (doc == null) {
        throw new RuntimeException("Unable to build the XForms document");
    }
    Element docElt = doc.getDocumentElement();

    // add CSS file if one is provided
    if (StringUtils.trimToNull(controller.getCssUrl()) != null) {
        Element head = DOMUtil.getChild(docElt, "xhtml:head");
        Element css = doc.createElementNS("http://www.w3.org/1999/xhtml", "link");
        css.setAttribute("rel", "stylesheet");
        css.setAttribute("type", "text/css");
        css.setAttribute("href", controller.getCssUrl());
        head.appendChild(css);
    }
    // hide buttons if applicable
    if (currentPage.isShowSubmitButtons() == false) {
        String tagName = MsgId.INT_SUBMIT_BUTTONS_GROUP_ID.getText();
        DOMUtil.removeEltInDescentByAttrValue(docElt, "id", tagName);
    } else { // #1181: individual hiding of submission buttons
        if (currentPage.isShowCancel() == false) {
            removeSubmitButton(docElt, MsgId.CAPTION_BUTTON_CANCEL);
        }
        if (currentPage.isShowDelete() == false) {
            removeSubmitButton(docElt, MsgId.CAPTION_BUTTON_DELETE);
        }
        if (currentPage.isShowValidate() == false) {
            removeSubmitButton(docElt, MsgId.CAPTION_BUTTON_SUBMIT);
        }
    }
    // add status message
    String statusMsg = statusDisplayedMsg;
    if (statusMsg != null) {
        String tagVal = MsgId.INT_CSS_STATUS_BAR_ID.getText();
        Element status = DOMUtil.getEltInDescentByAttrValue(docElt, "id", tagVal);
        status.setTextContent(statusMsg);
    }
    return doc;
}

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

/**
* Creates a source control user with permissions to publish to this web
* space.//from   w  w  w .ja va  2  s  . c om
*
* @param username Required. The user name.
* @param password Required. The user password.
* @param parameters Optional. Parameters supplied to the Create Publishing
* User 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 Publishing User operation response.
*/
@Override
public WebSpacesCreatePublishingUserResponse createPublishingUser(String username, String password,
        WebSpacesCreatePublishingUserParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (username == null) {
        throw new NullPointerException("username");
    }
    if (password == null) {
        throw new NullPointerException("password");
    }
    if (parameters != null) {
        if (parameters.getPublishingPassword() == null) {
            throw new NullPointerException("parameters.PublishingPassword");
        }
        if (parameters.getPublishingUserName() == null) {
            throw new NullPointerException("parameters.PublishingUserName");
        }
    }

    // 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("username", username);
        tracingParameters.put("password", password);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createPublishingUserAsync", 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/WebSpaces";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("properties=publishingCredentials");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    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-04-01");

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

    if (parameters != null) {
        Element userElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "User");
        requestDoc.appendChild(userElement);

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

        Element publishingPasswordElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "PublishingPassword");
        publishingPasswordElement.appendChild(requestDoc.createTextNode(parameters.getPublishingPassword()));
        userElement.appendChild(publishingPasswordElement);

        Element publishingUserNameElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "PublishingUserName");
        publishingUserNameElement.appendChild(requestDoc.createTextNode(parameters.getPublishingUserName()));
        userElement.appendChild(publishingUserNameElement);
    }

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

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

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

                Element publishingPasswordElement2 = XmlUtility.getElementByTagNameNS(userElement2,
                        "http://schemas.microsoft.com/windowsazure", "PublishingPassword");
                if (publishingPasswordElement2 != null) {
                    String publishingPasswordInstance;
                    publishingPasswordInstance = publishingPasswordElement2.getTextContent();
                    result.setPublishingPassword(publishingPasswordInstance);
                }

                Element publishingUserNameElement2 = XmlUtility.getElementByTagNameNS(userElement2,
                        "http://schemas.microsoft.com/windowsazure", "PublishingUserName");
                if (publishingUserNameElement2 != null) {
                    String publishingUserNameInstance;
                    publishingUserNameInstance = publishingUserNameElement2.getTextContent();
                    result.setPublishingUserName(publishingUserNameInstance);
                }
            }

        }
        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.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * This method processes the SOAP response from the IdP, and converts it
 * for presenting it back to the WSP that requested a delegated SAML
 * assertion./*from  ww w .  java2s.c om*/
 * 
 * @param samlSession SAML session
 * @param authnState 
 * @return true, if successful
 */
private boolean processSOAPResponse(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) {
    this.logger.debug("Step 5 of 5: Processing SOAP response");

    try {
        String expression = "/soap:Envelope/soap:Header/ecp:Response";
        InputStream is = new ByteArrayInputStream(authnState.getSoapResponse().getBytes());
        InputSource source = new InputSource(is);
        DOMParser parser = new DOMParser();
        parser.setFeature("http://xml.org/sax/features/namespaces", true);
        parser.parse(source);
        Document doc = parser.getDocument();
        Node node = EXPRESSION_POOL.evaluate(expression, doc, XPathConstants.NODE);

        if (node != null) {
            String responseConsumerURL = node.getAttributes().getNamedItem("AssertionConsumerServiceURL")
                    .getTextContent();

            logger.debug("Found {} node found in SOAP response.", expression);

            if (responseConsumerURL != null
                    && responseConsumerURL.equals(authnState.getResponseConsumerURL())) {
                logger.debug("responseConsumerURL {} matches {}", responseConsumerURL,
                        authnState.getResponseConsumerURL());

                // Retrieve and save the SOAP prefix used
                String soapPrefix = node.getParentNode().getPrefix();
                Element ecpResponse = (Element) node;
                Element soapHeader = (Element) ecpResponse.getParentNode();
                removeAllChildren(soapHeader);

                // Now on to the PAOS Response
                Element paosResponse = doc.createElementNS("urn:liberty:paos:2003-08", "paos:Response");
                paosResponse.setAttribute(soapPrefix + ":mustUnderstand", "1");
                paosResponse.setAttribute(soapPrefix + ":actor", "http://schemas.xmlsoap.org/soap/actor/next");

                // messageID is optional
                if (authnState.getPaosMessageID() != null)
                    paosResponse.setAttribute("refToMessageID", authnState.getPaosMessageID());

                soapHeader.appendChild(paosResponse);

                if (authnState.getRelayStateElement() != null) {
                    Node relayState = doc.importNode(authnState.getRelayStateElement(), true);
                    soapHeader.appendChild(relayState);
                }

                // Store the modified SOAP Request in the SAML Session
                String modifiedSOAPResponse = writeDomToString(doc);
                authnState.setModifiedSOAPResponse(modifiedSOAPResponse);
                return true;
            }

            logger.debug("responseConsumerURL {} does not match {}", responseConsumerURL,
                    authnState.getResponseConsumerURL());
            Document soapFaultMessage = createSOAPFaultDocument(
                    "AssertionConsumerServiceURL attribute missing or not matching the expected value.");
            Element soapHeader = (Element) soapFaultMessage.getFirstChild().getFirstChild();
            // Now on to the PAOS Response
            Element paosResponse = soapFaultMessage.createElementNS("urn:liberty:paos:2003-08",
                    "paos:Response");
            paosResponse.setAttribute(SOAP_PREFIX + ":mustUnderstand", "1");
            paosResponse.setAttribute(SOAP_PREFIX + ":actor", "http://schemas.xmlsoap.org/soap/actor/next");

            // messageID is optional
            if (authnState.getPaosMessageID() != null) {
                paosResponse.setAttribute("refToMessageID", authnState.getPaosMessageID());
            }

            soapHeader.appendChild(paosResponse);

            if (authnState.getRelayStateElement() != null) {
                Node relayState = soapFaultMessage.importNode(authnState.getRelayStateElement(), true);
                soapHeader.appendChild(relayState);
            }
            // Store the SOAP Fault in the SAML Session
            String modifiedSOAPResponse = writeDomToString(soapFaultMessage);
            authnState.setModifiedSOAPResponse(modifiedSOAPResponse);
            sendSOAPFault(samlSession, authnState);
            return false;

        }

        // There was no response for the ECP.  Look for and propagate an error.
        String errorMessage = getSOAPFaultAsString(is);

        logger.warn("No {} node found in SOAP response. Error: {}", expression, errorMessage);

        if (errorMessage != null) {
            throw new DelegatedAuthenticationRuntimeException(errorMessage);
        }

        return false;
    } catch (XPathExpressionException ex) {
        logger.error("XPath programming error.", ex);
        throw new DelegatedAuthenticationRuntimeException("XPath programming error.", ex);
    } catch (SAXNotRecognizedException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException("XPath programming error.", ex);
    } catch (SAXNotSupportedException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (SAXException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (DOMException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (IOException ex) {
        logger.error(
                "This exception should not ever really occur, as the only I/O this method performs is on a ByteArrayInputStream.",
                ex);
        throw new DelegatedAuthenticationRuntimeException(
                "This exception should not ever really occur, as the only I/O this method performs is on a ByteArrayInputStream.",
                ex);
    } catch (SOAPException ex) {
        logger.error("Error processing a SOAP message.", ex);
        throw new DelegatedAuthenticationRuntimeException("Error processing a SOAP message.", ex);
    }
}

From source file:com.microsoft.windowsazure.management.storage.StorageAccountOperationsImpl.java

/**
* The Regenerate Keys operation regenerates the primary or secondary access
* key for the specified storage account.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460795.aspx for
* more information)//from   w  w w  .  ja v  a  2 s. c o m
*
* @param parameters Required. Parameters supplied to the Regenerate Keys
* 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 primary and secondary access keys for a storage account.
*/
@Override
public StorageAccountRegenerateKeysResponse regenerateKeys(StorageAccountRegenerateKeysParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getKeyType() == null) {
        throw new NullPointerException("parameters.KeyType");
    }
    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, "regenerateKeysAsync", 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/storageservices/";
    url = url + URLEncoder.encode(parameters.getName(), "UTF-8");
    url = url + "/keys";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("action=regenerate");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    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 regenerateKeysElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "RegenerateKeys");
    requestDoc.appendChild(regenerateKeysElement);

    Element keyTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "KeyType");
    keyTypeElement.appendChild(requestDoc.createTextNode(parameters.getKeyType().toString()));
    regenerateKeysElement.appendChild(keyTypeElement);

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

            Element storageServiceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "StorageService");
            if (storageServiceElement != null) {
                Element urlElement = XmlUtility.getElementByTagNameNS(storageServiceElement,
                        "http://schemas.microsoft.com/windowsazure", "Url");
                if (urlElement != null) {
                    URI urlInstance;
                    urlInstance = new URI(urlElement.getTextContent());
                    result.setUri(urlInstance);
                }

                Element storageServiceKeysElement = XmlUtility.getElementByTagNameNS(storageServiceElement,
                        "http://schemas.microsoft.com/windowsazure", "StorageServiceKeys");
                if (storageServiceKeysElement != null) {
                    Element primaryElement = XmlUtility.getElementByTagNameNS(storageServiceKeysElement,
                            "http://schemas.microsoft.com/windowsazure", "Primary");
                    if (primaryElement != null) {
                        String primaryInstance;
                        primaryInstance = primaryElement.getTextContent();
                        result.setPrimaryKey(primaryInstance);
                    }

                    Element secondaryElement = XmlUtility.getElementByTagNameNS(storageServiceKeysElement,
                            "http://schemas.microsoft.com/windowsazure", "Secondary");
                    if (secondaryElement != null) {
                        String secondaryInstance;
                        secondaryInstance = secondaryElement.getTextContent();
                        result.setSecondaryKey(secondaryInstance);
                    }
                }
            }

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